Skip to content

Instantly share code, notes, and snippets.

@abarnert
Created June 12, 2018 18:52
Show Gist options
  • Save abarnert/c00ea060364ae6cb88a687c5886746a8 to your computer and use it in GitHub Desktop.
Save abarnert/c00ea060364ae6cb88a687c5886746a8 to your computer and use it in GitHub Desktop.
#include <Python.h>
#include <math.h>
static PyObject* interpolate(PyObject* self, PyObject* args) {
const Py_ssize_t tl = 2;
const Py_ssize_t ll = 0;
int nx, ny, angle, distance;
if (!PyArg_ParseTuple(args, "iiii", &nx, &ny, &angle, &distance)) {
return NULL;
}
PyObject* pos_list = PyList_New(ll);
for (int i = 0; i < distance; i++) {
double x = -i * cos(angle * M_PI / 180);
double y = -i * sin(angle * M_PI / 180);
PyObject *pos = Py_BuildValue("(ff)", x, y);
PyList_Append(pos_list, pos);
}
return pos_list;
}
static PyMethodDef gameMathMethods[] = {
{"interpolate", interpolate, METH_VARARGS,
"interpolate(nx, ny, angle, distance) -> [(x0, y0), (x1, y1), ...]"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
static struct PyModuleDef gameMathmodule = {
PyModuleDef_HEAD_INIT,
"gameMath", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
gameMathMethods
};
PyMODINIT_FUNC
PyInit_gameMath(void)
{
return PyModule_Create(&gameMathmodule);
}
/* setup.py
from distutils.core import setup, Extension
module1 = Extension('gameMath',
sources = ['interpolate.c'],
include_dirs = ['/usr/include'],
libraries = ['m'])
setup (name = 'gameMath',
version = '1.0',
description = 'game math',
ext_modules = [module1])
*/
/* test.py
import gameMath
a = gameMath.interpolate(2, 2, 135, 4)
print(a)
*/
/* output
[(-0.0, 0.0), (0.7071067811865475, -0.7071067811865476), (1.414213562373095, -1.4142135623730951), (2.1213203435596424, -2.121320343559643)]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment