part 1 of merge from trunk at r30358; it compiles, but doesn't link quite yet :)

This commit is contained in:
2010-07-19 04:44:37 +00:00
1714 changed files with 119636 additions and 84178 deletions

View File

@@ -1,5 +1,5 @@
/**
* $Id: IDProp.c
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -23,17 +23,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "DNA_ID.h"
#include "BKE_idprop.h"
#include "IDProp.h"
// #include "gen_utils.h"
#include "MEM_guardedalloc.h"
#define BSTR_EQ(a, b) (*(a) == *(b) && !strcmp(a, b))
/*** Function to wrap ID properties ***/
PyObject *BPy_Wrap_IDProperty(ID *id, IDProperty *prop, IDProperty *parent);

View File

@@ -1,5 +1,5 @@
/**
* $Id: IDProp.h
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*

View File

@@ -1,5 +1,5 @@
/*
* $Id: bgl.c 27189 2010-02-28 15:44:18Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -61,16 +61,19 @@ static PyObject *Buffer_item( PyObject * self, int i );
static PyObject *Buffer_slice( PyObject * self, int begin, int end );
static int Buffer_ass_item( PyObject * self, int i, PyObject * v );
static int Buffer_ass_slice( PyObject * self, int begin, int end,
PyObject * seq );
PyObject * seq );
static PySequenceMethods Buffer_SeqMethods = {
( lenfunc ) Buffer_len, /*sq_length */
( binaryfunc ) 0, /*sq_concat */
( ssizeargfunc ) 0, /*sq_repeat */
( ssizeargfunc ) Buffer_item, /*sq_item */
( ssizessizeargfunc ) Buffer_slice, /*sq_slice */
( ssizeobjargproc ) Buffer_ass_item, /*sq_ass_item */
( ssizessizeobjargproc ) Buffer_ass_slice, /*sq_ass_slice */
( lenfunc ) Buffer_len, /*sq_length */
( binaryfunc ) NULL, /*sq_concat */
( ssizeargfunc ) NULL, /*sq_repeat */
( ssizeargfunc ) Buffer_item, /*sq_item */
( ssizessizeargfunc ) Buffer_slice, /*sq_slice, deprecated TODO, replace */
( ssizeobjargproc ) Buffer_ass_item, /*sq_ass_item */
( ssizessizeobjargproc ) Buffer_ass_slice, /*sq_ass_slice, deprecated TODO, replace */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static void Buffer_dealloc( PyObject * self );
@@ -319,20 +322,20 @@ static int Buffer_ass_item(PyObject *self, int i, PyObject *v)
}
if (buf->type==GL_BYTE) {
if (!PyArg_Parse(v, "b;Coordinates must be ints", &buf->buf.asbyte[i]))
if (!PyArg_Parse(v, "b:Coordinates must be ints", &buf->buf.asbyte[i]))
return -1;
} else if (buf->type==GL_SHORT) {
if (!PyArg_Parse(v, "h;Coordinates must be ints", &buf->buf.asshort[i]))
if (!PyArg_Parse(v, "h:Coordinates must be ints", &buf->buf.asshort[i]))
return -1;
} else if (buf->type==GL_INT) {
if (!PyArg_Parse(v, "i;Coordinates must be ints", &buf->buf.asint[i]))
if (!PyArg_Parse(v, "i:Coordinates must be ints", &buf->buf.asint[i]))
return -1;
} else if (buf->type==GL_FLOAT) {
if (!PyArg_Parse(v, "f;Coordinates must be floats", &buf->buf.asfloat[i]))
if (!PyArg_Parse(v, "f:Coordinates must be floats", &buf->buf.asfloat[i]))
return -1;
} else if (buf->type==GL_DOUBLE) {
if (!PyArg_Parse(v, "d;Coordinates must be floats", &buf->buf.asdouble[i]))
if (!PyArg_Parse(v, "d:Coordinates must be floats", &buf->buf.asdouble[i]))
return -1;
}
return 0;
@@ -355,7 +358,10 @@ static int Buffer_ass_slice(PyObject *self, int begin, int end, PyObject *seq)
}
if (PySequence_Length(seq)!=(end-begin)) {
PyErr_SetString(PyExc_TypeError, "size mismatch in assignment");
int seq_len = PySequence_Length(seq);
char err_str[128];
sprintf(err_str, "size mismatch in assignment. Expected size: %d (size provided: %d)", seq_len, (end-begin));
PyErr_SetString(PyExc_TypeError, err_str);
return -1;
}
@@ -430,7 +436,7 @@ BGL_Wrap(3, AreTexturesResident, GLboolean, (GLsizei, GLuintP, GLbooleanP))
BGL_Wrap(1, Begin, void, (GLenum))
BGL_Wrap(2, BindTexture, void, (GLenum, GLuint))
BGL_Wrap(7, Bitmap, void, (GLsizei, GLsizei, GLfloat,
GLfloat, GLfloat, GLfloat, GLubyteP))
GLfloat, GLfloat, GLfloat, GLubyteP))
BGL_Wrap(2, BlendFunc, void, (GLenum, GLenum))
BGL_Wrap(1, CallList, void, (GLuint))
BGL_Wrap(3, CallLists, void, (GLsizei, GLenum, GLvoidP))
@@ -476,6 +482,7 @@ BGL_Wrap(1, Color4usv, void, (GLushortP))
BGL_Wrap(4, ColorMask, void, (GLboolean, GLboolean, GLboolean, GLboolean))
BGL_Wrap(2, ColorMaterial, void, (GLenum, GLenum))
BGL_Wrap(5, CopyPixels, void, (GLint, GLint, GLsizei, GLsizei, GLenum))
BGL_Wrap(8, CopyTexImage2D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint))
BGL_Wrap(1, CullFace, void, (GLenum))
BGL_Wrap(2, DeleteLists, void, (GLuint, GLsizei))
BGL_Wrap(2, DeleteTextures, void, (GLsizei, GLuintP))
@@ -511,7 +518,7 @@ BGL_Wrap(2, Fogi, void, (GLenum, GLint))
BGL_Wrap(2, Fogiv, void, (GLenum, GLintP))
BGL_Wrap(1, FrontFace, void, (GLenum))
BGL_Wrap(6, Frustum, void, (GLdouble, GLdouble,
GLdouble, GLdouble, GLdouble, GLdouble))
GLdouble, GLdouble, GLdouble, GLdouble))
BGL_Wrap(1, GenLists, GLuint, (GLsizei))
BGL_Wrap(2, GenTextures, void, (GLsizei, GLuintP))
BGL_Wrap(2, GetBooleanv, void, (GLenum, GLbooleanP))
@@ -573,19 +580,19 @@ BGL_Wrap(1, LoadMatrixf, void, (GLfloatP))
BGL_Wrap(1, LoadName, void, (GLuint))
BGL_Wrap(1, LogicOp, void, (GLenum))
BGL_Wrap(6, Map1d, void, (GLenum, GLdouble, GLdouble,
GLint, GLint, GLdoubleP))
GLint, GLint, GLdoubleP))
BGL_Wrap(6, Map1f, void, (GLenum, GLfloat, GLfloat,
GLint, GLint, GLfloatP))
GLint, GLint, GLfloatP))
BGL_Wrap(10, Map2d, void, (GLenum, GLdouble, GLdouble,
GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdoubleP))
GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdoubleP))
BGL_Wrap(10, Map2f, void, (GLenum, GLfloat, GLfloat,
GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloatP))
GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloatP))
BGL_Wrap(3, MapGrid1d, void, (GLint, GLdouble, GLdouble))
BGL_Wrap(3, MapGrid1f, void, (GLint, GLfloat, GLfloat))
BGL_Wrap(6, MapGrid2d, void, (GLint, GLdouble, GLdouble,
GLint, GLdouble, GLdouble))
GLint, GLdouble, GLdouble))
BGL_Wrap(6, MapGrid2f, void, (GLint, GLfloat, GLfloat,
GLint, GLfloat, GLfloat))
GLint, GLfloat, GLfloat))
BGL_Wrap(3, Materialf, void, (GLenum, GLenum, GLfloat))
BGL_Wrap(3, Materialfv, void, (GLenum, GLenum, GLfloatP))
BGL_Wrap(3, Materiali, void, (GLenum, GLenum, GLint))
@@ -605,7 +612,7 @@ BGL_Wrap(1, Normal3iv, void, (GLintP))
BGL_Wrap(3, Normal3s, void, (GLshort, GLshort, GLshort))
BGL_Wrap(1, Normal3sv, void, (GLshortP))
BGL_Wrap(6, Ortho, void, (GLdouble, GLdouble,
GLdouble, GLdouble, GLdouble, GLdouble))
GLdouble, GLdouble, GLdouble, GLdouble))
BGL_Wrap(1, PassThrough, void, (GLfloat))
BGL_Wrap(3, PixelMapfv, void, (GLenum, GLint, GLfloatP))
BGL_Wrap(3, PixelMapuiv, void, (GLenum, GLint, GLuintP))
@@ -654,7 +661,7 @@ BGL_Wrap(4, RasterPos4s, void, (GLshort, GLshort, GLshort, GLshort))
BGL_Wrap(1, RasterPos4sv, void, (GLshortP))
BGL_Wrap(1, ReadBuffer, void, (GLenum))
BGL_Wrap(7, ReadPixels, void, (GLint, GLint, GLsizei,
GLsizei, GLenum, GLenum, GLvoidP))
GLsizei, GLenum, GLenum, GLvoidP))
BGL_Wrap(4, Rectd, void, (GLdouble, GLdouble, GLdouble, GLdouble))
BGL_Wrap(2, Rectdv, void, (GLdoubleP, GLdoubleP))
BGL_Wrap(4, Rectf, void, (GLfloat, GLfloat, GLfloat, GLfloat))
@@ -717,9 +724,9 @@ BGL_Wrap(3, TexGenfv, void, (GLenum, GLenum, GLfloatP))
BGL_Wrap(3, TexGeni, void, (GLenum, GLenum, GLint))
BGL_Wrap(3, TexGeniv, void, (GLenum, GLenum, GLintP))
BGL_Wrap(8, TexImage1D, void, (GLenum, GLint, GLint,
GLsizei, GLint, GLenum, GLenum, GLvoidP))
GLsizei, GLint, GLenum, GLenum, GLvoidP))
BGL_Wrap(9, TexImage2D, void, (GLenum, GLint, GLint,
GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP))
GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP))
BGL_Wrap(3, TexParameterf, void, (GLenum, GLenum, GLfloat))
BGL_Wrap(3, TexParameterfv, void, (GLenum, GLenum, GLfloatP))
BGL_Wrap(3, TexParameteri, void, (GLenum, GLenum, GLint))
@@ -819,6 +826,7 @@ static struct PyMethodDef BGL_methods[] = {
MethodDef(ColorMask),
MethodDef(ColorMaterial),
MethodDef(CopyPixels),
MethodDef(CopyTexImage2D),
MethodDef(CullFace),
MethodDef(DeleteLists),
MethodDef(DeleteTextures),
@@ -1605,4 +1613,3 @@ PyObject *BGL_Init(void)
return mod;
}

View File

@@ -1,5 +1,5 @@
/*
* $Id: bgl.h 27188 2010-02-28 14:57:26Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -36,10 +36,6 @@
#ifndef EXPP_BGL_H
#define EXPP_BGL_H
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <Python.h>
PyObject *BGL_Init(void);

View File

@@ -1,196 +0,0 @@
/**
* $Id:
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
#include "blf.h"
#include "../../blenfont/BLF_api.h"
static char py_blf_position_doc[] =
".. function:: position(x, y, z)\n"
"\n"
" Set the position for drawing text.";
static PyObject *py_blf_position(PyObject *self, PyObject *args)
{
float x, y, z;
if (!PyArg_ParseTuple(args, "fff:BLF.position", &x, &y, &z))
return NULL;
BLF_position(x, y, z);
Py_RETURN_NONE;
}
static char py_blf_size_doc[] =
".. function:: size(size, dpi)\n"
"\n"
" Set the size and dpi for drawing text.\n"
"\n"
" :arg size: Point size of the font.\n"
" :type size: int\n"
" :arg dpi: dots per inch value to use for drawing.\n"
" :type dpi: int\n";
static PyObject *py_blf_size(PyObject *self, PyObject *args)
{
int size, dpi;
if (!PyArg_ParseTuple(args, "ii:BLF.size", &size, &dpi))
return NULL;
BLF_size(size, dpi);
Py_RETURN_NONE;
}
static char py_blf_aspect_doc[] =
".. function:: aspect(aspect)\n"
"\n"
" Set the aspect for drawing text.\n"
"\n"
" :arg aspect: The aspect ratio for text drawing to use.\n"
" :type aspect: float\n";
static PyObject *py_blf_aspect(PyObject *self, PyObject *args)
{
float aspect;
if (!PyArg_ParseTuple(args, "f:BLF.aspect", &aspect))
return NULL;
BLF_aspect(aspect);
Py_RETURN_NONE;
}
static char py_blf_blur_doc[] =
".. function:: blur(radius)\n"
"\n"
" Set the blur radius for drawing text.\n"
"\n"
" :arg radius: The radius for blurring text (in pixels).\n"
" :type radius: int\n";
static PyObject *py_blf_blur(PyObject *self, PyObject *args)
{
int blur;
if (!PyArg_ParseTuple(args, "i:BLF.blur", &blur))
return NULL;
BLF_blur(blur);
Py_RETURN_NONE;
}
static char py_blf_draw_doc[] =
".. function:: draw(text)\n"
"\n"
" Draw text in the current context.\n"
"\n"
" :arg text: the text to draw.\n"
" :type text: string\n";
static PyObject *py_blf_draw(PyObject *self, PyObject *args)
{
char *text;
if (!PyArg_ParseTuple(args, "s:BLF.draw", &text))
return NULL;
BLF_draw(text);
Py_RETURN_NONE;
}
static char py_blf_dimensions_doc[] =
".. function:: dimensions(text)\n"
"\n"
" Return the width and hight of the text.\n"
"\n"
" :arg text: the text to draw.\n"
" :type text: string\n"
" :return: the width and height of the text.\n"
" :rtype: tuple of 2 floats\n";
static PyObject *py_blf_dimensions(PyObject *self, PyObject *args)
{
char *text;
float r_width, r_height;
PyObject *ret;
if (!PyArg_ParseTuple(args, "s:BLF.dimensions", &text))
return NULL;
BLF_width_and_height(text, &r_width, &r_height);
ret= PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(r_width));
PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(r_height));
return ret;
}
/*----------------------------MODULE INIT-------------------------*/
struct PyMethodDef BLF_methods[] = {
{"position", (PyCFunction)py_blf_position, METH_VARARGS, py_blf_position_doc},
{"size", (PyCFunction) py_blf_size, METH_VARARGS, py_blf_size_doc},
{"aspect", (PyCFunction) py_blf_aspect, METH_VARARGS, py_blf_aspect_doc},
{"blur", (PyCFunction) py_blf_blur, METH_VARARGS, py_blf_blur_doc},
{"draw", (PyCFunction) py_blf_draw, METH_VARARGS, py_blf_draw_doc},
{"dimensions", (PyCFunction) py_blf_dimensions, METH_VARARGS, py_blf_dimensions_doc},
{NULL, NULL, 0, NULL}
};
static char BLF_doc[] =
"This module provides access to blenders text drawing functions.\n";
static struct PyModuleDef BLF_module_def = {
PyModuleDef_HEAD_INIT,
"blf", /* m_name */
BLF_doc, /* m_doc */
0, /* m_size */
BLF_methods, /* m_methods */
0, /* m_reload */
0, /* m_traverse */
0, /* m_clear */
0, /* m_free */
};
PyObject *BLF_Init(void)
{
PyObject *submodule;
submodule = PyModule_Create(&BLF_module_def);
PyDict_SetItemString(PySys_GetObject("modules"), BLF_module_def.m_name, submodule);
return (submodule);
}

View File

@@ -0,0 +1,405 @@
/**
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
#include <Python.h>
#include "blf_api.h"
#include "../../blenfont/BLF_api.h"
static char py_blf_position_doc[] =
".. function:: position(fontid, x, y, z)\n"
"\n"
" Set the position for drawing text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg x: X axis position to draw the text.\n"
" :type x: float\n"
" :arg y: Y axis position to draw the text.\n"
" :type y: float\n"
" :arg z: Z axis position to draw the text.\n"
" :type x: float\n";
static PyObject *py_blf_position(PyObject *self, PyObject *args)
{
int fontid;
float x, y, z;
if (!PyArg_ParseTuple(args, "ifff:blf.position", &fontid, &x, &y, &z))
return NULL;
BLF_position(fontid, x, y, z);
Py_RETURN_NONE;
}
static char py_blf_size_doc[] =
".. function:: size(fontid, size, dpi)\n"
"\n"
" Set the size and dpi for drawing text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg size: Point size of the font.\n"
" :type size: int\n"
" :arg dpi: dots per inch value to use for drawing.\n"
" :type dpi: int\n";
static PyObject *py_blf_size(PyObject *self, PyObject *args)
{
int fontid, size, dpi;
if (!PyArg_ParseTuple(args, "iii:blf.size", &fontid, &size, &dpi))
return NULL;
BLF_size(fontid, size, dpi);
Py_RETURN_NONE;
}
static char py_blf_aspect_doc[] =
".. function:: aspect(fontid, aspect)\n"
"\n"
" Set the aspect for drawing text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg aspect: The aspect ratio for text drawing to use.\n"
" :type aspect: float\n";
static PyObject *py_blf_aspect(PyObject *self, PyObject *args)
{
float aspect;
int fontid;
if (!PyArg_ParseTuple(args, "if:blf.aspect", &fontid, &aspect))
return NULL;
BLF_aspect(fontid, aspect);
Py_RETURN_NONE;
}
static char py_blf_blur_doc[] =
".. function:: blur(fontid, radius)\n"
"\n"
" Set the blur radius for drawing text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg radius: The radius for blurring text (in pixels).\n"
" :type radius: int\n";
static PyObject *py_blf_blur(PyObject *self, PyObject *args)
{
int blur, fontid;
if (!PyArg_ParseTuple(args, "ii:blf.blur", &fontid, &blur))
return NULL;
BLF_blur(fontid, blur);
Py_RETURN_NONE;
}
static char py_blf_draw_doc[] =
".. function:: draw(fontid, text)\n"
"\n"
" Draw text in the current context.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg text: the text to draw.\n"
" :type text: string\n";
static PyObject *py_blf_draw(PyObject *self, PyObject *args)
{
char *text;
int fontid;
if (!PyArg_ParseTuple(args, "is:blf.draw", &fontid, &text))
return NULL;
BLF_draw(fontid, text);
Py_RETURN_NONE;
}
static char py_blf_dimensions_doc[] =
".. function:: dimensions(fontid, text)\n"
"\n"
" Return the width and hight of the text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg text: the text to draw.\n"
" :type text: string\n"
" :return: the width and height of the text.\n"
" :rtype: tuple of 2 floats\n";
static PyObject *py_blf_dimensions(PyObject *self, PyObject *args)
{
char *text;
float r_width, r_height;
PyObject *ret;
int fontid;
if (!PyArg_ParseTuple(args, "is:blf.dimensions", &fontid, &text))
return NULL;
BLF_width_and_height(fontid, text, &r_width, &r_height);
ret= PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(r_width));
PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(r_height));
return ret;
}
static char py_blf_clipping_doc[] =
".. function:: clipping(fontid, xmin, ymin, xmax, ymax)\n"
"\n"
" Set the clipping, enable/disable using CLIPPING.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg xmin: Clip the drawing area by these bounds.\n"
" :type xmin: float\n"
" :arg ymin: Clip the drawing area by these bounds.\n"
" :type ymin: float\n"
" :arg xmax: Clip the drawing area by these bounds.\n"
" :type xmax: float\n"
" :arg ymax: Clip the drawing area by these bounds.\n"
" :type ymax: float\n";
static PyObject *py_blf_clipping(PyObject *self, PyObject *args)
{
float xmin, ymin, xmax, ymax;
int fontid;
if (!PyArg_ParseTuple(args, "iffff:blf.clipping", &fontid, &xmin, &ymin, &xmax, &ymax))
return NULL;
BLF_clipping(fontid, xmin, ymin, xmax, ymax);
Py_RETURN_NONE;
}
static char py_blf_disable_doc[] =
".. function:: disable(fontid, option)\n"
"\n"
" Disable option.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg option: One of ROTATION, CLIPPING, SHADOW or KERNING_DEFAULT.\n"
" :type option: int\n";
static PyObject *py_blf_disable(PyObject *self, PyObject *args)
{
int option, fontid;
if (!PyArg_ParseTuple(args, "ii:blf.disable", &fontid, &option))
return NULL;
BLF_disable(fontid, option);
Py_RETURN_NONE;
}
static char py_blf_enable_doc[] =
".. function:: enable(fontid, option)\n"
"\n"
" Enable option.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg option: One of ROTATION, CLIPPING, SHADOW or KERNING_DEFAULT.\n"
" :type option: int\n";
static PyObject *py_blf_enable(PyObject *self, PyObject *args)
{
int option, fontid;
if (!PyArg_ParseTuple(args, "ii:blf.enable", &fontid, &option))
return NULL;
BLF_enable(fontid, option);
Py_RETURN_NONE;
}
static char py_blf_rotation_doc[] =
".. function:: rotation(fontid, angle)\n"
"\n"
" Set the text rotation angle, enable/disable using ROTATION.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg angle: The angle for text drawing to use.\n"
" :type aspect: float\n";
static PyObject *py_blf_rotation(PyObject *self, PyObject *args)
{
float angle;
int fontid;
if (!PyArg_ParseTuple(args, "if:blf.rotation", &fontid, &angle))
return NULL;
BLF_rotation(fontid, angle);
Py_RETURN_NONE;
}
static char py_blf_shadow_doc[] =
".. function:: shadow(fontid, level, r, g, b, a)\n"
"\n"
" Shadow options, enable/disable using SHADOW .\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg level: The blur level, can be 3, 5 or 0.\n"
" :type level: int\n"
" :arg r: Shadow color (red channel 0.0 - 1.0).\n"
" :type r: float\n"
" :arg g: Shadow color (green channel 0.0 - 1.0).\n"
" :type g: float\n"
" :arg b: Shadow color (blue channel 0.0 - 1.0).\n"
" :type b: float\n"
" :arg a: Shadow color (alpha channel 0.0 - 1.0).\n"
" :type a: float\n";
static PyObject *py_blf_shadow(PyObject *self, PyObject *args)
{
int level, fontid;
float r, g, b, a;
if (!PyArg_ParseTuple(args, "iiffff:blf.shadow", &fontid, &level, &r, &g, &b, &a))
return NULL;
if (level != 0 && level != 3 && level != 5) {
PyErr_SetString(PyExc_TypeError, "blf.shadow expected arg to be in (0, 3, 5)");
return NULL;
}
BLF_shadow(fontid, level, r, g, b, a);
Py_RETURN_NONE;
}
static char py_blf_shadow_offset_doc[] =
".. function:: shadow_offset(fontid, x, y)\n"
"\n"
" Set the offset for shadow text.\n"
"\n"
" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
" :type fontid: int\n"
" :arg x: Vertical shadow offset value in pixels.\n"
" :type x: float\n"
" :arg y: Horizontal shadow offset value in pixels.\n"
" :type y: float\n";
static PyObject *py_blf_shadow_offset(PyObject *self, PyObject *args)
{
int x, y, fontid;
if (!PyArg_ParseTuple(args, "iii:blf.shadow_offset", &fontid, &x, &y))
return NULL;
BLF_shadow_offset(fontid, x, y);
Py_RETURN_NONE;
}
static char py_blf_load_doc[] =
".. function:: load(filename)\n"
"\n"
" Load a new font.\n"
"\n"
" :arg filename: the filename of the font.\n"
" :type filename: string\n"
" :return: the new font's fontid or -1 if there was an error.\n"
" :rtype: integer\n";
static PyObject *py_blf_load(PyObject *self, PyObject *args)
{
char* filename;
if (!PyArg_ParseTuple(args, "s:blf.load", &filename))
return NULL;
return PyLong_FromLong(BLF_load(filename));
}
/*----------------------------MODULE INIT-------------------------*/
struct PyMethodDef BLF_methods[] = {
{"aspect", (PyCFunction) py_blf_aspect, METH_VARARGS, py_blf_aspect_doc},
{"blur", (PyCFunction) py_blf_blur, METH_VARARGS, py_blf_blur_doc},
{"clipping", (PyCFunction) py_blf_clipping, METH_VARARGS, py_blf_clipping_doc},
{"disable", (PyCFunction) py_blf_disable, METH_VARARGS, py_blf_disable_doc},
{"dimensions", (PyCFunction) py_blf_dimensions, METH_VARARGS, py_blf_dimensions_doc},
{"draw", (PyCFunction) py_blf_draw, METH_VARARGS, py_blf_draw_doc},
{"enable", (PyCFunction) py_blf_enable, METH_VARARGS, py_blf_enable_doc},
{"position", (PyCFunction)py_blf_position, METH_VARARGS, py_blf_position_doc},
{"rotation", (PyCFunction) py_blf_rotation, METH_VARARGS, py_blf_rotation_doc},
{"shadow", (PyCFunction) py_blf_shadow, METH_VARARGS, py_blf_shadow_doc},
{"shadow_offset", (PyCFunction) py_blf_shadow_offset, METH_VARARGS, py_blf_shadow_offset_doc},
{"size", (PyCFunction) py_blf_size, METH_VARARGS, py_blf_size_doc},
{"load", (PyCFunction) py_blf_load, METH_VARARGS, py_blf_load_doc},
{NULL, NULL, 0, NULL}
};
static char BLF_doc[] =
"This module provides access to blenders text drawing functions.\n";
static struct PyModuleDef BLF_module_def = {
PyModuleDef_HEAD_INIT,
"blf", /* m_name */
BLF_doc, /* m_doc */
0, /* m_size */
BLF_methods, /* m_methods */
0, /* m_reload */
0, /* m_traverse */
0, /* m_clear */
0, /* m_free */
};
PyObject *BLF_Init(void)
{
PyObject *submodule;
submodule = PyModule_Create(&BLF_module_def);
PyDict_SetItemString(PySys_GetObject("modules"), BLF_module_def.m_name, submodule);
PyModule_AddIntConstant(submodule, "ROTATION", BLF_ROTATION);
PyModule_AddIntConstant(submodule, "CLIPPING", BLF_CLIPPING);
PyModule_AddIntConstant(submodule, "SHADOW", BLF_SHADOW);
PyModule_AddIntConstant(submodule, "KERNING_DEFAULT", BLF_KERNING_DEFAULT);
return (submodule);
}

View File

@@ -1,5 +1,5 @@
/**
* $Id:
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*

View File

@@ -28,12 +28,13 @@
#include "bpy_internal_import.h"
#include "DNA_text_types.h"
#include "DNA_ID.h"
#include "MEM_guardedalloc.h"
#include "BKE_text.h" /* txt_to_buf */
#include "BKE_main.h"
#include "BKE_global.h" /* grr, only for G.sce */
#include "BLI_listbase.h"
#include "BLI_path_util.h"
#include <stddef.h>
static Main *bpy_import_main= NULL;
@@ -56,6 +57,12 @@ void bpy_import_main_set(struct Main *maggie)
bpy_import_main= maggie;
}
/* returns a dummy filename for a textblock so we can tell what file a text block comes from */
void bpy_text_filename_get(char *fn, Text *text)
{
sprintf(fn, "%s/%s", text->id.lib ? text->id.lib->filepath : G.sce, text->id.name+2);
}
PyObject *bpy_text_import( Text *text )
{
char *buf = NULL;
@@ -63,8 +70,11 @@ PyObject *bpy_text_import( Text *text )
int len;
if( !text->compiled ) {
char fn_dummy[256];
bpy_text_filename_get(fn_dummy, text);
buf = txt_to_buf( text );
text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
text->compiled = Py_CompileString( buf, fn_dummy, Py_file_input );
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
@@ -120,8 +130,8 @@ PyObject *bpy_text_import_name( char *name, int *found )
PyObject *bpy_text_reimport( PyObject *module, int *found )
{
Text *text;
const char *txtname;
const char *name;
char *filepath;
char *buf = NULL;
//XXX Main *maggie= bpy_import_main ? bpy_import_main:G.main;
Main *maggie= bpy_import_main;
@@ -134,14 +144,14 @@ PyObject *bpy_text_reimport( PyObject *module, int *found )
*found= 0;
/* get name, filename from the module itself */
if((name= PyModule_GetName(module)) == NULL)
return NULL;
txtname = PyModule_GetFilename( module );
name = PyModule_GetName( module );
if( !txtname || !name)
if((filepath= (char *)PyModule_GetFilename(module)) == NULL)
return NULL;
/* look up the text object */
text= BLI_findstring(&maggie->text, txtname, offsetof(ID, name) + 2);
text= BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);
/* uh-oh.... didn't find it */
if( !text )
@@ -187,7 +197,7 @@ static PyObject *blender_import( PyObject * self, PyObject * args, PyObject * k
static char *kwlist[] = {"name", "globals", "locals", "fromlist", "level", 0};
if( !PyArg_ParseTupleAndKeywords( args, kw, "s|OOOi:bpy_import_meth", kwlist,
&name, &globals, &locals, &fromlist, &dummy_val) )
&name, &globals, &locals, &fromlist, &dummy_val) )
return NULL;
/* import existing builtin modules or modules that have been imported alredy */
@@ -227,16 +237,11 @@ static PyObject *blender_import( PyObject * self, PyObject * args, PyObject * k
* our reload() module, to handle reloading in-memory scripts
*/
static PyObject *blender_reload( PyObject * self, PyObject * args )
static PyObject *blender_reload( PyObject * self, PyObject * module )
{
PyObject *exception, *err, *tb;
PyObject *module = NULL;
PyObject *newmodule = NULL;
int found= 0;
/* check for a module arg */
if( !PyArg_ParseTuple( args, "O:bpy_reload_meth", &module ) )
return NULL;
/* try reimporting from file */
newmodule = PyImport_ReloadModule( module );
@@ -270,7 +275,7 @@ static PyObject *blender_reload( PyObject * self, PyObject * args )
}
PyMethodDef bpy_import_meth[] = { {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"} };
PyMethodDef bpy_reload_meth[] = { {"bpy_reload_meth", (PyCFunction)blender_reload, METH_VARARGS, "blenders reload"} };
PyMethodDef bpy_reload_meth[] = { {"bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"} };
/* Clear user modules.

View File

@@ -50,6 +50,9 @@ PyObject* bpy_text_import( struct Text *text );
PyObject* bpy_text_import_name( char *name, int *found );
PyObject* bpy_text_reimport( PyObject *module, int *found );
/* void bpy_text_clear_modules( int clear_all );*/ /* Clear user modules */
void bpy_text_filename_get(char *fn, struct Text *text);
extern PyMethodDef bpy_import_meth[];
extern PyMethodDef bpy_reload_meth[];

View File

@@ -1,5 +1,5 @@
/*
* $Id: Geometry.c 21254 2009-06-30 00:42:17Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -27,12 +27,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "Geometry.h"
/* - Not needed for now though other geometry functions will probably need them
#include "BLI_math.h"
#include "BKE_utildefines.h"
*/
#include "geometry.h"
/* Used for PolyFill */
#include "BKE_displist.h"
@@ -49,7 +44,7 @@
/*-------------------------DOC STRINGS ---------------------------*/
static char M_Geometry_doc[] = "The Blender Geometry module\n\n";
static char M_Geometry_doc[] = "The Blender geometry module\n\n";
static char M_Geometry_Intersect_doc[] = "(v1, v2, v3, ray, orig, clip=1) - returns the intersection between a ray and a triangle, if possible, returns None otherwise";
static char M_Geometry_TriangleArea_doc[] = "(v1, v2, v3) - returns the area size of the 2D or 3D triangle defined";
static char M_Geometry_TriangleNormal_doc[] = "(v1, v2, v3) - returns the normal of the 3D triangle defined";
@@ -64,7 +59,7 @@ static char M_Geometry_BoxPack2D_doc[] = "";
static char M_Geometry_BezierInterp_doc[] = "";
//---------------------------------INTERSECTION FUNCTIONS--------------------
//----------------------------------Mathutils.Intersect() -------------------
//----------------------------------geometry.Intersect() -------------------
static PyObject *M_Geometry_Intersect( PyObject * self, PyObject * args )
{
VectorObject *ray, *ray_off, *vec1, *vec2, *vec3;
@@ -136,7 +131,7 @@ static PyObject *M_Geometry_Intersect( PyObject * self, PyObject * args )
return newVectorObject(pvec, 3, Py_NEW, NULL);
}
//----------------------------------Mathutils.LineIntersect() -------------------
//----------------------------------geometry.LineIntersect() -------------------
/* Line-Line intersection using algorithm from mathworld.wolfram.com */
static PyObject *M_Geometry_LineIntersect( PyObject * self, PyObject * args )
{
@@ -205,7 +200,7 @@ static PyObject *M_Geometry_LineIntersect( PyObject * self, PyObject * args )
//---------------------------------NORMALS FUNCTIONS--------------------
//----------------------------------Mathutils.QuadNormal() -------------------
//----------------------------------geometry.QuadNormal() -------------------
static PyObject *M_Geometry_QuadNormal( PyObject * self, PyObject * args )
{
VectorObject *vec1;
@@ -256,7 +251,7 @@ static PyObject *M_Geometry_QuadNormal( PyObject * self, PyObject * args )
return newVectorObject(n1, 3, Py_NEW, NULL);
}
//----------------------------Mathutils.TriangleNormal() -------------------
//----------------------------geometry.TriangleNormal() -------------------
static PyObject *M_Geometry_TriangleNormal( PyObject * self, PyObject * args )
{
VectorObject *vec1, *vec2, *vec3;
@@ -293,14 +288,14 @@ static PyObject *M_Geometry_TriangleNormal( PyObject * self, PyObject * args )
}
//--------------------------------- AREA FUNCTIONS--------------------
//----------------------------------Mathutils.TriangleArea() -------------------
//----------------------------------geometry.TriangleArea() -------------------
static PyObject *M_Geometry_TriangleArea( PyObject * self, PyObject * args )
{
VectorObject *vec1, *vec2, *vec3;
float v1[3], v2[3], v3[3];
if( !PyArg_ParseTuple
( args, "O!O!O!", &vector_Type, &vec1, &vector_Type, &vec2
( args, "O!O!O!", &vector_Type, &vec1, &vector_Type, &vec2
, &vector_Type, &vec3 ) ) {
PyErr_SetString( PyExc_TypeError, "expected 3 vector types\n");
return NULL;
@@ -338,7 +333,7 @@ static PyObject *M_Geometry_TriangleArea( PyObject * self, PyObject * args )
}
}
/*----------------------------------Geometry.PolyFill() -------------------*/
/*----------------------------------geometry.PolyFill() -------------------*/
/* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
{
@@ -368,7 +363,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if (!PySequence_Check(polyLine)) {
freedisplist(&dispbase);
Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
PyErr_SetString( PyExc_TypeError, "One or more of the polylines is not a sequence of Mathutils.Vector's" );
PyErr_SetString( PyExc_TypeError, "One or more of the polylines is not a sequence of mathutils.Vector's" );
return NULL;
}
@@ -378,7 +373,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if (EXPP_check_sequence_consistency( polyLine, &vector_Type ) != 1) {
freedisplist(&dispbase);
Py_DECREF(polyLine);
PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a Mathutils.Vector type" );
PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a mathutils.Vector type" );
return NULL;
}
#endif
@@ -419,12 +414,12 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if(ls_error) {
freedisplist(&dispbase); /* possible some dl was allocated */
PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a Mathutils.Vector type" );
PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a mathutils.Vector type" );
return NULL;
}
else if (totpoints) {
/* now make the list to return */
filldisplist(&dispbase, &dispbase);
filldisplist(&dispbase, &dispbase, 0);
/* The faces are stored in a new DisplayList
thats added to the head of the listbase */
@@ -433,7 +428,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
tri_list= PyList_New(dl->parts);
if( !tri_list ) {
freedisplist(&dispbase);
PyErr_SetString( PyExc_RuntimeError, "Geometry.PolyFill failed to make a new list" );
PyErr_SetString( PyExc_RuntimeError, "geometry.PolyFill failed to make a new list" );
return NULL;
}
@@ -824,7 +819,7 @@ struct PyMethodDef M_Geometry_methods[] = {
static struct PyModuleDef M_Geometry_module_def = {
PyModuleDef_HEAD_INIT,
"Geometry", /* m_name */
"geometry", /* m_name */
M_Geometry_doc, /* m_doc */
0, /* m_size */
M_Geometry_methods, /* m_methods */

View File

@@ -1,5 +1,5 @@
/*
* $Id: Geometry.h 21094 2009-06-23 00:09:26Z gsrb3d $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -32,7 +32,7 @@
#define EXPP_Geometry_H
#include <Python.h>
#include "Mathutils.h"
#include "mathutils.h"
PyObject *Geometry_Init(void);

View File

@@ -1,5 +1,5 @@
/*
* $Id: Mathutils.c 21559 2009-07-13 12:17:07Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -29,6 +29,7 @@
/* Note: Changes to Mathutils since 2.4x
* use radians rather then degrees
* - Mathutils.Vector/Euler/Quaternion(), now only take single sequence arguments.
* - Mathutils.MidpointVecs --> vector.lerp(other, fac)
* - Mathutils.AngleBetweenVecs --> vector.angle(other)
* - Mathutils.ProjectVecs --> vector.project(other)
@@ -47,16 +48,50 @@
* Moved to Geometry module: Intersect, TriangleArea, TriangleNormal, QuadNormal, LineIntersect
*/
#include "Mathutils.h"
#include "mathutils.h"
#include "BLI_math.h"
#include "PIL_time.h"
#include "BKE_utildefines.h"
//-------------------------DOC STRINGS ---------------------------
static char M_Mathutils_doc[] =
"This module provides access to matrices, eulers, quaternions and vectors.";
/* helper functionm returns length of the 'value', -1 on error */
int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
{
PyObject *value_fast= NULL;
int i, size;
/* non list/tuple cases */
if(!(value_fast=PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
size= PySequence_Fast_GET_SIZE(value_fast);
if(size > array_max || size < array_min) {
if (array_max == array_min) PyErr_Format(PyExc_ValueError, "%.200s: sequence size is %d, expected %d", error_prefix, size, array_max);
else PyErr_Format(PyExc_ValueError, "%.200s: sequence size is %d, expected [%d - %d]", error_prefix, size, array_min, array_max);
Py_DECREF(value_fast);
return -1;
}
i= size;
do {
i--;
if(((array[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i))) == -1.0) && PyErr_Occurred()) {
PyErr_Format(PyExc_ValueError, "%.200s: sequence index %d is not a float", error_prefix, i);
Py_DECREF(value_fast);
return -1;
}
} while(i);
Py_XDECREF(value_fast);
return size;
}
//-----------------------------METHODS----------------------------
//-----------------quat_rotation (internal)-----------
//This function multiplies a vector/point * quat or vice versa
@@ -126,14 +161,14 @@ PyObject *quat_rotation(PyObject *arg1, PyObject *arg2)
}
//----------------------------------MATRIX FUNCTIONS--------------------
//----------------------------------Mathutils.RotationMatrix() ----------
//----------------------------------mathutils.RotationMatrix() ----------
//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
static char M_Mathutils_RotationMatrix_doc[] =
".. function:: RotationMatrix(angle, size, axis)\n"
"\n"
" Create a matrix representing a rotation.\n"
"\n"
" :arg angle: The angle of rotation desired.\n"
" :arg angle: The angle of rotation desired, in radians.\n"
" :type angle: float\n"
" :arg size: The size of the rotation matrix to construct [2, 4].\n"
" :type size: int\n"
@@ -152,14 +187,14 @@ static PyObject *M_Mathutils_RotationMatrix(PyObject * self, PyObject * args)
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
if(!PyArg_ParseTuple(args, "fi|O", &angle, &matSize, &vec)) {
PyErr_SetString(PyExc_TypeError, "Mathutils.RotationMatrix(angle, size, axis): expected float int and a string or vector\n");
PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(angle, size, axis): expected float int and a string or vector\n");
return NULL;
}
if(vec && !VectorObject_Check(vec)) {
axis= _PyUnicode_AsString((PyObject *)vec);
if(axis==NULL || axis[0]=='\0' || axis[1]!='\0' || axis[0] < 'X' || axis[0] > 'Z') {
PyErr_SetString(PyExc_TypeError, "Mathutils.RotationMatrix(): 3rd argument axis value must be a 3D vector or a string in 'X', 'Y', 'Z'\n");
PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(): 3rd argument axis value must be a 3D vector or a string in 'X', 'Y', 'Z'\n");
return NULL;
}
else {
@@ -174,20 +209,20 @@ static PyObject *M_Mathutils_RotationMatrix(PyObject * self, PyObject * args)
angle-=(Py_PI*2);
if(matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
return NULL;
}
if(matSize == 2 && (vec != NULL)) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): cannot create a 2x2 rotation matrix around arbitrary axis\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): cannot create a 2x2 rotation matrix around arbitrary axis\n");
return NULL;
}
if((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): please choose an axis of rotation for 3d and 4d matrices\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): please choose an axis of rotation for 3d and 4d matrices\n");
return NULL;
}
if(vec) {
if(vec->size != 3) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): the vector axis must be a 3D vector\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): the vector axis must be a 3D vector\n");
return NULL;
}
@@ -230,7 +265,7 @@ static PyObject *M_Mathutils_RotationMatrix(PyObject * self, PyObject * args)
}
else {
/* should never get here */
PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): unknown error\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): unknown error\n");
return NULL;
}
@@ -265,11 +300,11 @@ static PyObject *M_Mathutils_TranslationMatrix(PyObject * self, VectorObject * v
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
if(!VectorObject_Check(vec)) {
PyErr_SetString(PyExc_TypeError, "Mathutils.TranslationMatrix(): expected vector\n");
PyErr_SetString(PyExc_TypeError, "mathutils.TranslationMatrix(): expected vector\n");
return NULL;
}
if(vec->size != 3 && vec->size != 4) {
PyErr_SetString(PyExc_TypeError, "Mathutils.TranslationMatrix(): vector must be 3D or 4D\n");
PyErr_SetString(PyExc_TypeError, "mathutils.TranslationMatrix(): vector must be 3D or 4D\n");
return NULL;
}
@@ -284,7 +319,7 @@ static PyObject *M_Mathutils_TranslationMatrix(PyObject * self, VectorObject * v
return newMatrixObject(mat, 4, 4, Py_NEW, NULL);
}
//----------------------------------Mathutils.ScaleMatrix() -------------
//----------------------------------mathutils.ScaleMatrix() -------------
//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
static char M_Mathutils_ScaleMatrix_doc[] =
".. function:: ScaleMatrix(factor, size, axis)\n"
@@ -309,16 +344,16 @@ static PyObject *M_Mathutils_ScaleMatrix(PyObject * self, PyObject * args)
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
if(!PyArg_ParseTuple(args, "fi|O!", &factor, &matSize, &vector_Type, &vec)) {
PyErr_SetString(PyExc_TypeError, "Mathutils.ScaleMatrix(): expected float int and optional vector\n");
PyErr_SetString(PyExc_TypeError, "mathutils.ScaleMatrix(): expected float int and optional vector\n");
return NULL;
}
if(matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.ScaleMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.ScaleMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
return NULL;
}
if(vec) {
if(vec->size > 2 && matSize == 2) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.ScaleMatrix(): please use 2D vectors when scaling in 2D\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.ScaleMatrix(): please use 2D vectors when scaling in 2D\n");
return NULL;
}
@@ -375,7 +410,7 @@ static PyObject *M_Mathutils_ScaleMatrix(PyObject * self, PyObject * args)
//pass to matrix creation
return newMatrixObject(mat, matSize, matSize, Py_NEW, NULL);
}
//----------------------------------Mathutils.OrthoProjectionMatrix() ---
//----------------------------------mathutils.OrthoProjectionMatrix() ---
//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
static char M_Mathutils_OrthoProjectionMatrix_doc[] =
".. function:: OrthoProjectionMatrix(plane, size, axis)\n"
@@ -400,16 +435,16 @@ static PyObject *M_Mathutils_OrthoProjectionMatrix(PyObject * self, PyObject * a
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
if(!PyArg_ParseTuple(args, "si|O!", &plane, &matSize, &vector_Type, &vec)) {
PyErr_SetString(PyExc_TypeError, "Mathutils.OrthoProjectionMatrix(): expected string and int and optional vector\n");
PyErr_SetString(PyExc_TypeError, "mathutils.OrthoProjectionMatrix(): expected string and int and optional vector\n");
return NULL;
}
if(matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_AttributeError,"Mathutils.OrthoProjectionMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
PyErr_SetString(PyExc_AttributeError,"mathutils.OrthoProjectionMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
return NULL;
}
if(vec) {
if(vec->size > 2 && matSize == 2) {
PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): please use 2D vectors when scaling in 2D\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): please use 2D vectors when scaling in 2D\n");
return NULL;
}
@@ -432,7 +467,7 @@ static PyObject *M_Mathutils_OrthoProjectionMatrix(PyObject * self, PyObject * a
mat[4] = 1.0f;
mat[8] = 1.0f;
} else {
PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): unknown plane - expected: X, Y, XY, XZ, YZ\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): unknown plane - expected: X, Y, XY, XZ, YZ\n");
return NULL;
}
} else { //arbitrary plane
@@ -460,7 +495,7 @@ static PyObject *M_Mathutils_OrthoProjectionMatrix(PyObject * self, PyObject * a
mat[7] = -(vec->vec[1] * vec->vec[2]);
mat[8] = 1 - (vec->vec[2] * vec->vec[2]);
} else {
PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): unknown plane - expected: 'r' expected for axis designation\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): unknown plane - expected: 'r' expected for axis designation\n");
return NULL;
}
}
@@ -502,16 +537,16 @@ static PyObject *M_Mathutils_ShearMatrix(PyObject * self, PyObject * args)
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
if(!PyArg_ParseTuple(args, "sfi", &plane, &factor, &matSize)) {
PyErr_SetString(PyExc_TypeError,"Mathutils.ShearMatrix(): expected string float and int\n");
PyErr_SetString(PyExc_TypeError,"mathutils.ShearMatrix(): expected string float and int\n");
return NULL;
}
if(matSize != 2 && matSize != 3 && matSize != 4) {
PyErr_SetString(PyExc_AttributeError,"Mathutils.ShearMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
PyErr_SetString(PyExc_AttributeError,"mathutils.ShearMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
return NULL;
}
if((strcmp(plane, "X") == 0)
&& matSize == 2) {
&& matSize == 2) {
mat[0] = 1.0f;
mat[2] = factor;
mat[3] = 1.0f;
@@ -537,7 +572,7 @@ static PyObject *M_Mathutils_ShearMatrix(PyObject * self, PyObject * args)
mat[4] = 1.0f;
mat[8] = 1.0f;
} else {
PyErr_SetString(PyExc_AttributeError, "Mathutils.ShearMatrix(): expected: x, y, xy, xz, yz or wrong matrix size for shearing plane\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.ShearMatrix(): expected: x, y, xy, xz, yz or wrong matrix size for shearing plane\n");
return NULL;
}
if(matSize == 4) {
@@ -611,40 +646,44 @@ int Mathutils_RegisterCallback(Mathutils_Callback *cb)
int _BaseMathObject_ReadCallback(BaseMathObject *self)
{
Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
if(cb->get(self->cb_user, self->cb_subtype, self->data))
if(cb->get(self, self->cb_subtype))
return 1;
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
if(!PyErr_Occurred())
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
return 0;
}
int _BaseMathObject_WriteCallback(BaseMathObject *self)
{
Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
if(cb->set(self->cb_user, self->cb_subtype, self->data))
if(cb->set(self, self->cb_subtype))
return 1;
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
if(!PyErr_Occurred())
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
return 0;
}
int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
{
Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
if(cb->get_index(self->cb_user, self->cb_subtype, self->data, index))
if(cb->get_index(self, self->cb_subtype, index))
return 1;
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
if(!PyErr_Occurred())
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
return 0;
}
int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
{
Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
if(cb->set_index(self->cb_user, self->cb_subtype, self->data, index))
if(cb->set_index(self, self->cb_subtype, index))
return 1;
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
if(!PyErr_Occurred())
PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
return 0;
}
@@ -685,7 +724,7 @@ struct PyMethodDef M_Mathutils_methods[] = {
static struct PyModuleDef M_Mathutils_module_def = {
PyModuleDef_HEAD_INIT,
"Mathutils", /* m_name */
"mathutils", /* m_name */
M_Mathutils_doc, /* m_doc */
0, /* m_size */
M_Mathutils_methods, /* m_methods */
@@ -707,7 +746,9 @@ PyObject *Mathutils_Init(void)
return NULL;
if( PyType_Ready( &quaternion_Type ) < 0 )
return NULL;
if( PyType_Ready( &color_Type ) < 0 )
return NULL;
submodule = PyModule_Create(&M_Mathutils_module_def);
PyDict_SetItemString(PySys_GetObject("modules"), M_Mathutils_module_def.m_name, submodule);
@@ -716,6 +757,7 @@ PyObject *Mathutils_Init(void)
PyModule_AddObject( submodule, "Matrix", (PyObject *)&matrix_Type );
PyModule_AddObject( submodule, "Euler", (PyObject *)&euler_Type );
PyModule_AddObject( submodule, "Quaternion", (PyObject *)&quaternion_Type );
PyModule_AddObject( submodule, "Color", (PyObject *)&color_Type );
mathutils_matrix_vector_cb_index= Mathutils_RegisterCallback(&mathutils_matrix_vector_cb);

View File

@@ -1,5 +1,5 @@
/*
* $Id: Mathutils.h 21499 2009-07-10 18:09:53Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -33,25 +33,29 @@
#include <Python.h>
#include "vector.h"
#include "matrix.h"
#include "quat.h"
#include "euler.h"
/* Can cast different mathutils types to this, use for generic funcs */
extern char BaseMathObject_Wrapped_doc[];
extern char BaseMathObject_Owner_doc[];
#define BASE_MATH_MEMBERS(_data) \
PyObject_VAR_HEAD \
float *_data; /* array of data (alias), wrapped status depends on wrapped status */ \
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */ \
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */ \
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */ \
unsigned char wrapped; /* wrapped data type? */ \
typedef struct {
PyObject_VAR_HEAD
float *data; /*array of data (alias), wrapped status depends on wrapped status */
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
unsigned char wrapped; /* wrapped data type? */
BASE_MATH_MEMBERS(data)
} BaseMathObject;
#include "mathutils_vector.h"
#include "mathutils_matrix.h"
#include "mathutils_quat.h"
#include "mathutils_euler.h"
#include "mathutils_color.h"
PyObject *BaseMathObject_getOwner( BaseMathObject * self, void * );
PyObject *BaseMathObject_getWrapped( BaseMathObject *self, void * );
void BaseMathObject_dealloc(BaseMathObject * self);
@@ -84,18 +88,18 @@ int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps);
typedef struct Mathutils_Callback Mathutils_Callback;
typedef int (*BaseMathCheckFunc)(PyObject *);
typedef int (*BaseMathGetFunc)(PyObject *, int, float *);
typedef int (*BaseMathSetFunc)(PyObject *, int, float *);
typedef int (*BaseMathGetIndexFunc)(PyObject *, int, float *, int);
typedef int (*BaseMathSetIndexFunc)(PyObject *, int, float *, int);
typedef int (*BaseMathCheckFunc)(BaseMathObject *); /* checks the user is still valid */
typedef int (*BaseMathGetFunc)(BaseMathObject *, int); /* gets the vector from the user */
typedef int (*BaseMathSetFunc)(BaseMathObject *, int); /* sets the users vector values once the vector is modified */
typedef int (*BaseMathGetIndexFunc)(BaseMathObject *, int, int); /* same as above but only for an index */
typedef int (*BaseMathSetIndexFunc)(BaseMathObject *, int, int); /* same as above but only for an index */
struct Mathutils_Callback {
int (*check)(PyObject *user); /* checks the user is still valid */
int (*get)(PyObject *user, int subtype, float *from); /* gets the vector from the user */
int (*set)(PyObject *user, int subtype, float *to); /* sets the users vector values once the vector is modified */
int (*get_index)(PyObject *user, int subtype, float *from,int index); /* same as above but only for an index */
int (*set_index)(PyObject *user, int subtype, float *to, int index); /* same as above but only for an index */
BaseMathCheckFunc check;
BaseMathGetFunc get;
BaseMathSetFunc set;
BaseMathGetIndexFunc get_index;
BaseMathSetIndexFunc set_index;
};
int Mathutils_RegisterCallback(Mathutils_Callback *cb);
@@ -111,4 +115,7 @@ int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index);
#define BaseMath_ReadIndexCallback(_self, _index) (((_self)->cb_user ? _BaseMathObject_ReadIndexCallback((BaseMathObject *)_self, _index):1))
#define BaseMath_WriteIndexCallback(_self, _index) (((_self)->cb_user ? _BaseMathObject_WriteIndexCallback((BaseMathObject *)_self, _index):1))
/* utility func */
int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix);
#endif /* EXPP_Mathutils_H */

View File

@@ -0,0 +1,560 @@
/*
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Contributor(s): Campbell Barton
*
* ***** END GPL LICENSE BLOCK *****
*/
#include "mathutils.h"
#include "BLI_math.h"
#include "BKE_utildefines.h"
#define COLOR_SIZE 3
//----------------------------------mathutils.Color() -------------------
//makes a new color for you to play with
static PyObject *Color_new(PyTypeObject * type, PyObject * args, PyObject * kwargs)
{
float col[3]= {0.0f, 0.0f, 0.0f};
switch(PyTuple_GET_SIZE(args)) {
case 0:
break;
case 1:
if((mathutils_array_parse(col, COLOR_SIZE, COLOR_SIZE, PyTuple_GET_ITEM(args, 0), "mathutils.Color()")) == -1)
return NULL;
break;
default:
PyErr_SetString(PyExc_TypeError, "mathutils.Color(): more then a single arg given");
return NULL;
}
return newColorObject(col, Py_NEW, type);
}
//-----------------------------METHODS----------------------------
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Color_ToTupleExt(ColorObject *self, int ndigits)
{
PyObject *ret;
int i;
ret= PyTuple_New(COLOR_SIZE);
if(ndigits >= 0) {
for(i= 0; i < COLOR_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->col[i], ndigits)));
}
}
else {
for(i= 0; i < COLOR_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->col[i]));
}
}
return ret;
}
static char Color_copy_doc[] =
".. function:: copy()\n"
"\n"
" Returns a copy of this color.\n"
"\n"
" :return: A copy of the color.\n"
" :rtype: :class:`Color`\n"
"\n"
" .. note:: use this to get a copy of a wrapped color with no reference to the original data.\n";
static PyObject *Color_copy(ColorObject * self, PyObject *args)
{
if(!BaseMath_ReadCallback(self))
return NULL;
return newColorObject(self->col, Py_NEW, Py_TYPE(self));
}
//----------------------------print object (internal)--------------
//print the object to screen
static PyObject *Color_repr(ColorObject * self)
{
PyObject *ret, *tuple;
if(!BaseMath_ReadCallback(self))
return NULL;
tuple= Color_ToTupleExt(self, -1);
ret= PyUnicode_FromFormat("Color(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
//------------------------tp_richcmpr
//returns -1 execption, 0 false, 1 true
static PyObject* Color_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
{
ColorObject *colA = NULL, *colB = NULL;
int result = 0;
if(ColorObject_Check(objectA)) {
colA = (ColorObject*)objectA;
if(!BaseMath_ReadCallback(colA))
return NULL;
}
if(ColorObject_Check(objectB)) {
colB = (ColorObject*)objectB;
if(!BaseMath_ReadCallback(colB))
return NULL;
}
if (!colA || !colB){
if (comparison_type == Py_NE){
Py_RETURN_TRUE;
}else{
Py_RETURN_FALSE;
}
}
colA = (ColorObject*)objectA;
colB = (ColorObject*)objectB;
switch (comparison_type){
case Py_EQ:
result = EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1);
break;
case Py_NE:
result = !EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1);
break;
default:
printf("The result of the comparison could not be evaluated");
break;
}
if (result == 1){
Py_RETURN_TRUE;
}else{
Py_RETURN_FALSE;
}
}
//---------------------SEQUENCE PROTOCOLS------------------------
//----------------------------len(object)------------------------
//sequence length
static int Color_len(ColorObject * self)
{
return COLOR_SIZE;
}
//----------------------------object[]---------------------------
//sequence accessor (get)
static PyObject *Color_item(ColorObject * self, int i)
{
if(i<0) i= COLOR_SIZE-i;
if(i < 0 || i >= COLOR_SIZE) {
PyErr_SetString(PyExc_IndexError, "color[attribute]: array index out of range");
return NULL;
}
if(!BaseMath_ReadIndexCallback(self, i))
return NULL;
return PyFloat_FromDouble(self->col[i]);
}
//----------------------------object[]-------------------------
//sequence accessor (set)
static int Color_ass_item(ColorObject * self, int i, PyObject * value)
{
float f = PyFloat_AsDouble(value);
if(f == -1 && PyErr_Occurred()) { // parsed item not a number
PyErr_SetString(PyExc_TypeError, "color[attribute] = x: argument not a number");
return -1;
}
if(i<0) i= COLOR_SIZE-i;
if(i < 0 || i >= COLOR_SIZE){
PyErr_SetString(PyExc_IndexError, "color[attribute] = x: array assignment index out of range\n");
return -1;
}
self->col[i] = f;
if(!BaseMath_WriteIndexCallback(self, i))
return -1;
return 0;
}
//----------------------------object[z:y]------------------------
//sequence slice (get)
static PyObject *Color_slice(ColorObject * self, int begin, int end)
{
PyObject *list = NULL;
int count;
if(!BaseMath_ReadCallback(self))
return NULL;
CLAMP(begin, 0, COLOR_SIZE);
if (end<0) end= (COLOR_SIZE + 1) + end;
CLAMP(end, 0, COLOR_SIZE);
begin = MIN2(begin,end);
list = PyList_New(end - begin);
for(count = begin; count < end; count++) {
PyList_SetItem(list, count - begin,
PyFloat_FromDouble(self->col[count]));
}
return list;
}
//----------------------------object[z:y]------------------------
//sequence slice (set)
static int Color_ass_slice(ColorObject * self, int begin, int end, PyObject * seq)
{
int i, size;
float col[COLOR_SIZE];
if(!BaseMath_ReadCallback(self))
return -1;
CLAMP(begin, 0, COLOR_SIZE);
if (end<0) end= (COLOR_SIZE + 1) + end;
CLAMP(end, 0, COLOR_SIZE);
begin = MIN2(begin,end);
if((size=mathutils_array_parse(col, 0, COLOR_SIZE, seq, "mathutils.Color[begin:end] = []")) == -1)
return -1;
if(size != (end - begin)){
PyErr_SetString(PyExc_TypeError, "color[begin:end] = []: size mismatch in slice assignment");
return -1;
}
for(i= 0; i < COLOR_SIZE; i++)
self->col[begin + i] = col[i];
BaseMath_WriteCallback(self);
return 0;
}
static PyObject *Color_subscript(ColorObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (i < 0)
i += COLOR_SIZE;
return Color_item(self, i);
} else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0)
return NULL;
if (slicelength <= 0) {
return PyList_New(0);
}
else if (step == 1) {
return Color_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with color");
return NULL;
}
}
else {
PyErr_Format(PyExc_TypeError,
"color indices must be integers, not %.200s",
item->ob_type->tp_name);
return NULL;
}
}
static int Color_ass_subscript(ColorObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return -1;
if (i < 0)
i += COLOR_SIZE;
return Color_ass_item(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0)
return -1;
if (step == 1)
return Color_ass_slice(self, start, stop, value);
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with color");
return -1;
}
}
else {
PyErr_Format(PyExc_TypeError,
"color indices must be integers, not %.200s",
item->ob_type->tp_name);
return -1;
}
}
//-----------------PROTCOL DECLARATIONS--------------------------
static PySequenceMethods Color_SeqMethods = {
(lenfunc) Color_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
(ssizeargfunc) NULL, /* sq_repeat */
(ssizeargfunc) Color_item, /* sq_item */
(ssizessizeargfunc) NULL, /* sq_slice, deprecated */
(ssizeobjargproc) Color_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyMappingMethods Color_AsMapping = {
(lenfunc)Color_len,
(binaryfunc)Color_subscript,
(objobjargproc)Color_ass_subscript
};
/* color channel, vector.r/g/b */
static PyObject *Color_getChannel( ColorObject * self, void *type )
{
return Color_item(self, GET_INT_FROM_POINTER(type));
}
static int Color_setChannel(ColorObject * self, PyObject * value, void * type)
{
return Color_ass_item(self, GET_INT_FROM_POINTER(type), value);
}
/* color channel (HSV), color.h/s/v */
static PyObject *Color_getChannelHSV( ColorObject * self, void *type )
{
float hsv[3];
int i= GET_INT_FROM_POINTER(type);
if(!BaseMath_ReadCallback(self))
return NULL;
rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
return PyFloat_FromDouble(hsv[i]);
}
static int Color_setChannelHSV(ColorObject * self, PyObject * value, void * type)
{
float hsv[3];
int i= GET_INT_FROM_POINTER(type);
float f = PyFloat_AsDouble(value);
if(f == -1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "color.h/s/v = value: argument not a number");
return -1;
}
if(!BaseMath_ReadCallback(self))
return -1;
rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
CLAMP(f, 0.0f, 1.0f);
hsv[i] = f;
hsv_to_rgb(hsv[0], hsv[1], hsv[2], &(self->col[0]), &(self->col[1]), &(self->col[2]));
if(!BaseMath_WriteCallback(self))
return -1;
return 0;
}
/* color channel (HSV), color.h/s/v */
static PyObject *Color_getHSV(ColorObject * self, void *type)
{
float hsv[3];
PyObject *ret;
if(!BaseMath_ReadCallback(self))
return NULL;
rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
ret= PyTuple_New(3);
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(hsv[0]));
PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(hsv[1]));
PyTuple_SET_ITEM(ret, 2, PyFloat_FromDouble(hsv[2]));
return ret;
}
static int Color_setHSV(ColorObject * self, PyObject * value, void * type)
{
float hsv[3];
if(mathutils_array_parse(hsv, 3, 3, value, "mathutils.Color.hsv = value") == -1)
return -1;
CLAMP(hsv[0], 0.0f, 1.0f);
CLAMP(hsv[1], 0.0f, 1.0f);
CLAMP(hsv[2], 0.0f, 1.0f);
hsv_to_rgb(hsv[0], hsv[1], hsv[2], &(self->col[0]), &(self->col[1]), &(self->col[2]));
if(!BaseMath_WriteCallback(self))
return -1;
return 0;
}
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Color_getseters[] = {
{"r", (getter)Color_getChannel, (setter)Color_setChannel, "Red color channel. **type** float", (void *)0},
{"g", (getter)Color_getChannel, (setter)Color_setChannel, "Green color channel. **type** float", (void *)1},
{"b", (getter)Color_getChannel, (setter)Color_setChannel, "Blue color channel. **type** float", (void *)2},
{"h", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Hue component in [0, 1]. **type** float", (void *)0},
{"s", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Saturation component in [0, 1]. **type** float", (void *)1},
{"v", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Value component in [0, 1]. **type** float", (void *)2},
{"hsv", (getter)Color_getHSV, (setter)Color_setHSV, "HSV Values in [0, 1]. **type** float triplet", (void *)0},
{"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
{"_owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
//-----------------------METHOD DEFINITIONS ----------------------
static struct PyMethodDef Color_methods[] = {
{"__copy__", (PyCFunction) Color_copy, METH_VARARGS, Color_copy_doc},
{"copy", (PyCFunction) Color_copy, METH_VARARGS, Color_copy_doc},
{NULL, NULL, 0, NULL}
};
//------------------PY_OBECT DEFINITION--------------------------
static char color_doc[] =
"This object gives access to Colors in Blender.";
PyTypeObject color_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"color", //tp_name
sizeof(ColorObject), //tp_basicsize
0, //tp_itemsize
(destructor)BaseMathObject_dealloc, //tp_dealloc
0, //tp_print
0, //tp_getattr
0, //tp_setattr
0, //tp_compare
(reprfunc) Color_repr, //tp_repr
0, //tp_as_number
&Color_SeqMethods, //tp_as_sequence
&Color_AsMapping, //tp_as_mapping
0, //tp_hash
0, //tp_call
0, //tp_str
0, //tp_getattro
0, //tp_setattro
0, //tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, //tp_flags
color_doc, //tp_doc
0, //tp_traverse
0, //tp_clear
(richcmpfunc)Color_richcmpr, //tp_richcompare
0, //tp_weaklistoffset
0, //tp_iter
0, //tp_iternext
Color_methods, //tp_methods
0, //tp_members
Color_getseters, //tp_getset
0, //tp_base
0, //tp_dict
0, //tp_descr_get
0, //tp_descr_set
0, //tp_dictoffset
0, //tp_init
0, //tp_alloc
Color_new, //tp_new
0, //tp_free
0, //tp_is_gc
0, //tp_bases
0, //tp_mro
0, //tp_cache
0, //tp_subclasses
0, //tp_weaklist
0 //tp_del
};
//------------------------newColorObject (internal)-------------
//creates a new color object
/*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
(i.e. it was allocated elsewhere by MEM_mallocN())
pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
(i.e. it must be created here with PyMEM_malloc())*/
PyObject *newColorObject(float *col, int type, PyTypeObject *base_type)
{
ColorObject *self;
if(base_type) self = (ColorObject *)base_type->tp_alloc(base_type, 0);
else self = PyObject_NEW(ColorObject, &color_Type);
/* init callbacks as NULL */
self->cb_user= NULL;
self->cb_type= self->cb_subtype= 0;
if(type == Py_WRAP){
self->col = col;
self->wrapped = Py_WRAP;
}
else if (type == Py_NEW){
self->col = PyMem_Malloc(COLOR_SIZE * sizeof(float));
if(col)
copy_v3_v3(self->col, col);
else
zero_v3(self->col);
self->wrapped = Py_NEW;
}
else {
return NULL;
}
return (PyObject *)self;
}
PyObject *newColorObject_cb(PyObject *cb_user, int cb_type, int cb_subtype)
{
ColorObject *self= (ColorObject *)newColorObject(NULL, Py_NEW, NULL);
if(self) {
Py_INCREF(cb_user);
self->cb_user= cb_user;
self->cb_type= (unsigned char)cb_type;
self->cb_subtype= (unsigned char)cb_subtype;
}
return (PyObject *)self;
}

View File

@@ -0,0 +1,52 @@
/*
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): Joseph Gilbert
*
* ***** END GPL LICENSE BLOCK *****
*
*/
#ifndef EXPP_color_h
#define EXPP_color_h
#include <Python.h>
extern PyTypeObject color_Type;
#define ColorObject_Check(_v) PyObject_TypeCheck((_v), &color_Type)
typedef struct {
BASE_MATH_MEMBERS(col)
} ColorObject;
/*struct data contains a pointer to the actual data that the
object uses. It can use either PyMem allocated data (which will
be stored in py_data) or be a wrapper for data allocated through
blender (stored in blend_data). This is an either/or struct not both*/
//prototypes
PyObject *newColorObject( float *col, int type, PyTypeObject *base_type);
PyObject *newColorObject_cb(PyObject *cb_user, int cb_type, int cb_subtype);
#endif /* EXPP_color_h */

View File

@@ -1,5 +1,5 @@
/*
* $Id: euler.c 21462 2009-07-09 15:40:04Z ton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -26,60 +26,41 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "Mathutils.h"
#include "mathutils.h"
#include "BLI_math.h"
#include "BKE_utildefines.h"
#include "BLI_blenlib.h"
#ifndef int32_t
#include "BLO_sys_types.h"
#endif
//----------------------------------Mathutils.Euler() -------------------
#define EULER_SIZE 3
//----------------------------------mathutils.Euler() -------------------
//makes a new euler for you to play with
static PyObject *Euler_new(PyTypeObject * type, PyObject * args, PyObject * kwargs)
{
PyObject *listObject = NULL;
int size, i;
float eul[3];
PyObject *e;
short order= 0; // TODO, add order option
PyObject *seq= NULL;
char *order_str= NULL;
size = PyTuple_GET_SIZE(args);
if (size == 1) {
listObject = PyTuple_GET_ITEM(args, 0);
if (PySequence_Check(listObject)) {
size = PySequence_Length(listObject);
} else { // Single argument was not a sequence
PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
return NULL;
}
} else if (size == 0) {
//returns a new empty 3d euler
return newEulerObject(NULL, order, Py_NEW, NULL);
} else {
listObject = args;
}
float eul[EULER_SIZE]= {0.0f, 0.0f, 0.0f};
short order= EULER_ORDER_XYZ;
if (size != 3) { // Invalid euler size
PyErr_SetString(PyExc_AttributeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
if(!PyArg_ParseTuple(args, "|Os:mathutils.Euler", &seq, &order_str))
return NULL;
}
for (i=0; i<size; i++) {
e = PySequence_GetItem(listObject, i);
if (e == NULL) { // Failed to read sequence
Py_DECREF(listObject);
PyErr_SetString(PyExc_RuntimeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
switch(PyTuple_GET_SIZE(args)) {
case 0:
break;
case 2:
if((order=euler_order_from_string(order_str, "mathutils.Euler()")) == -1)
return NULL;
}
eul[i]= (float)PyFloat_AsDouble(e);
Py_DECREF(e);
if(eul[i]==-1 && PyErr_Occurred()) { // parsed item is not a number
PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
/* intentionally pass through */
case 1:
if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1)
return NULL;
}
break;
}
return newEulerObject(eul, order, Py_NEW, NULL);
}
@@ -88,12 +69,12 @@ short euler_order_from_string(const char *str, const char *error_prefix)
{
if((str[0] && str[1] && str[2] && str[3]=='\0')) {
switch(*((int32_t *)str)) {
case 'X'|'Y'<<8|'Z'<<16: return 0;
case 'X'|'Z'<<8|'Y'<<16: return 1;
case 'Y'|'X'<<8|'Z'<<16: return 2;
case 'Y'|'Z'<<8|'X'<<16: return 3;
case 'Z'|'X'<<8|'Y'<<16: return 4;
case 'Z'|'Y'<<8|'X'<<16: return 5;
case 'X'|'Y'<<8|'Z'<<16: return EULER_ORDER_XYZ;
case 'X'|'Z'<<8|'Y'<<16: return EULER_ORDER_XZY;
case 'Y'|'X'<<8|'Z'<<16: return EULER_ORDER_YXZ;
case 'Y'|'Z'<<8|'X'<<16: return EULER_ORDER_YZX;
case 'Z'|'X'<<8|'Y'<<16: return EULER_ORDER_ZXY;
case 'Z'|'Y'<<8|'X'<<16: return EULER_ORDER_ZYX;
}
}
@@ -101,8 +82,29 @@ short euler_order_from_string(const char *str, const char *error_prefix)
return -1;
}
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Euler_ToTupleExt(EulerObject *self, int ndigits)
{
PyObject *ret;
int i;
ret= PyTuple_New(EULER_SIZE);
if(ndigits >= 0) {
for(i= 0; i < EULER_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->eul[i], ndigits)));
}
}
else {
for(i= 0; i < EULER_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->eul[i]));
}
}
return ret;
}
//-----------------------------METHODS----------------------------
//----------------------------Euler.toQuat()----------------------
//return a quaternion representation of the euler
static char Euler_ToQuat_doc[] =
@@ -120,12 +122,12 @@ static PyObject *Euler_ToQuat(EulerObject * self)
if(!BaseMath_ReadCallback(self))
return NULL;
if(self->order==0) eul_to_quat(quat, self->eul);
else eulO_to_quat(quat, self->eul, self->order);
if(self->order==EULER_ORDER_XYZ) eul_to_quat(quat, self->eul);
else eulO_to_quat(quat, self->eul, self->order);
return newQuaternionObject(quat, Py_NEW, NULL);
}
//----------------------------Euler.toMatrix()---------------------
//return a matrix representation of the euler
static char Euler_ToMatrix_doc[] =
".. method:: to_matrix()\n"
@@ -142,12 +144,12 @@ static PyObject *Euler_ToMatrix(EulerObject * self)
if(!BaseMath_ReadCallback(self))
return NULL;
if(self->order==0) eul_to_mat3((float (*)[3])mat, self->eul);
else eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
if(self->order==EULER_ORDER_XYZ) eul_to_mat3((float (*)[3])mat, self->eul);
else eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
return newMatrixObject(mat, 3, 3 , Py_NEW, NULL);
}
//----------------------------Euler.unique()-----------------------
//sets the x,y,z values to a unique euler rotation
// TODO, check if this works with rotation order!!!
static char Euler_Unique_doc[] =
@@ -206,7 +208,7 @@ static PyObject *Euler_Unique(EulerObject * self)
Py_INCREF(self);
return (PyObject *)self;
}
//----------------------------Euler.zero()-------------------------
//sets the euler to 0,0,0
static char Euler_Zero_doc[] =
".. method:: zero()\n"
@@ -226,28 +228,38 @@ static PyObject *Euler_Zero(EulerObject * self)
Py_INCREF(self);
return (PyObject *)self;
}
//----------------------------Euler.rotate()-----------------------
//rotates a euler a certain amount and returns the result
//should return a unique euler rotation (i.e. no 720 degree pitches :)
static char Euler_Rotate_doc[] =
".. method:: rotate(angle, axis)\n"
"\n"
" Rotates the euler a certain amount and returning a unique euler rotation (no 720 degree pitches).\n"
"\n"
" :arg angle: angle in radians.\n"
" :type angle: float\n"
" :arg axis: single character in ['X, 'Y', 'Z'].\n"
" :type axis: string\n"
" :return: an instance of itself\n"
" :rtype: :class:`Euler`";
static PyObject *Euler_Rotate(EulerObject * self, PyObject *args)
{
float angle = 0.0f;
char *axis;
if(!PyArg_ParseTuple(args, "fs", &angle, &axis)){
PyErr_SetString(PyExc_TypeError, "euler.rotate():expected angle (float) and axis (x,y,z)");
if(!PyArg_ParseTuple(args, "fs:rotate", &angle, &axis)){
PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected angle (float) and axis (x,y,z)");
return NULL;
}
if(ELEM3(*axis, 'x', 'y', 'z') && axis[1]=='\0'){
PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'x', 'y' or 'z'");
if(ELEM3(*axis, 'X', 'Y', 'Z') && axis[1]=='\0'){
PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'X', 'Y' or 'Z'");
return NULL;
}
if(!BaseMath_ReadCallback(self))
return NULL;
if(self->order == 0) rotate_eul(self->eul, *axis, angle);
else rotate_eulO(self->eul, self->order, *axis, angle);
if(self->order == EULER_ORDER_XYZ) rotate_eul(self->eul, *axis, angle);
else rotate_eulO(self->eul, self->order, *axis, angle);
BaseMath_WriteCallback(self);
Py_INCREF(self);
@@ -311,16 +323,22 @@ static PyObject *Euler_copy(EulerObject * self, PyObject *args)
//----------------------------print object (internal)--------------
//print the object to screen
static PyObject *Euler_repr(EulerObject * self)
{
char str[64];
PyObject *ret, *tuple;
if(!BaseMath_ReadCallback(self))
return NULL;
sprintf(str, "[%.6f, %.6f, %.6f](euler)", self->eul[0], self->eul[1], self->eul[2]);
return PyUnicode_FromString(str);
tuple= Euler_ToTupleExt(self, -1);
ret= PyUnicode_FromFormat("Euler(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
//------------------------tp_richcmpr
//returns -1 execption, 0 false, 1 true
static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
@@ -351,10 +369,10 @@ static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int compar
switch (comparison_type){
case Py_EQ:
result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
break;
case Py_NE:
result = !EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
result = !EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
break;
default:
printf("The result of the comparison could not be evaluated");
@@ -372,15 +390,15 @@ static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int compar
//sequence length
static int Euler_len(EulerObject * self)
{
return 3;
return EULER_SIZE;
}
//----------------------------object[]---------------------------
//sequence accessor (get)
static PyObject *Euler_item(EulerObject * self, int i)
{
if(i<0) i= 3-i;
if(i<0) i= EULER_SIZE-i;
if(i < 0 || i >= 3) {
if(i < 0 || i >= EULER_SIZE) {
PyErr_SetString(PyExc_IndexError, "euler[attribute]: array index out of range");
return NULL;
}
@@ -402,9 +420,9 @@ static int Euler_ass_item(EulerObject * self, int i, PyObject * value)
return -1;
}
if(i<0) i= 3-i;
if(i<0) i= EULER_SIZE-i;
if(i < 0 || i >= 3){
if(i < 0 || i >= EULER_SIZE){
PyErr_SetString(PyExc_IndexError, "euler[attribute] = x: array assignment index out of range\n");
return -1;
}
@@ -426,9 +444,9 @@ static PyObject *Euler_slice(EulerObject * self, int begin, int end)
if(!BaseMath_ReadCallback(self))
return NULL;
CLAMP(begin, 0, 3);
if (end<0) end= 4+end;
CLAMP(end, 0, 3);
CLAMP(begin, 0, EULER_SIZE);
if (end<0) end= (EULER_SIZE + 1) + end;
CLAMP(end, 0, EULER_SIZE);
begin = MIN2(begin,end);
list = PyList_New(end - begin);
@@ -441,64 +459,123 @@ static PyObject *Euler_slice(EulerObject * self, int begin, int end)
}
//----------------------------object[z:y]------------------------
//sequence slice (set)
static int Euler_ass_slice(EulerObject * self, int begin, int end,
PyObject * seq)
static int Euler_ass_slice(EulerObject * self, int begin, int end, PyObject * seq)
{
int i, y, size = 0;
float eul[3];
PyObject *e;
int i, size;
float eul[EULER_SIZE];
if(!BaseMath_ReadCallback(self))
return -1;
CLAMP(begin, 0, 3);
if (end<0) end= 4+end;
CLAMP(end, 0, 3);
CLAMP(begin, 0, EULER_SIZE);
if (end<0) end= (EULER_SIZE + 1) + end;
CLAMP(end, 0, EULER_SIZE);
begin = MIN2(begin,end);
size = PySequence_Length(seq);
if((size=mathutils_array_parse(eul, 0, EULER_SIZE, seq, "mathutils.Euler[begin:end] = []")) == -1)
return -1;
if(size != (end - begin)){
PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: size mismatch in slice assignment");
return -1;
}
for (i = 0; i < size; i++) {
e = PySequence_GetItem(seq, i);
if (e == NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "euler[begin:end] = []: unable to read sequence");
return -1;
}
eul[i] = (float)PyFloat_AsDouble(e);
Py_DECREF(e);
if(eul[i]==-1 && PyErr_Occurred()) { // parsed item not a number
PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: sequence argument not a number");
return -1;
}
}
//parsed well - now set in vector
for(y = 0; y < 3; y++){
self->eul[begin + y] = eul[y];
}
for(i= 0; i < EULER_SIZE; i++)
self->eul[begin + i] = eul[i];
BaseMath_WriteCallback(self);
return 0;
}
static PyObject *Euler_subscript(EulerObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (i < 0)
i += EULER_SIZE;
return Euler_item(self, i);
} else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
return NULL;
if (slicelength <= 0) {
return PyList_New(0);
}
else if (step == 1) {
return Euler_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with eulers");
return NULL;
}
}
else {
PyErr_Format(PyExc_TypeError,
"euler indices must be integers, not %.200s",
item->ob_type->tp_name);
return NULL;
}
}
static int Euler_ass_subscript(EulerObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return -1;
if (i < 0)
i += EULER_SIZE;
return Euler_ass_item(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
return -1;
if (step == 1)
return Euler_ass_slice(self, start, stop, value);
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with euler");
return -1;
}
}
else {
PyErr_Format(PyExc_TypeError,
"euler indices must be integers, not %.200s",
item->ob_type->tp_name);
return -1;
}
}
//-----------------PROTCOL DECLARATIONS--------------------------
static PySequenceMethods Euler_SeqMethods = {
(lenfunc) Euler_len, /* sq_length */
(binaryfunc) 0, /* sq_concat */
(ssizeargfunc) 0, /* sq_repeat */
(ssizeargfunc) Euler_item, /* sq_item */
(ssizessizeargfunc) Euler_slice, /* sq_slice */
(ssizeobjargproc) Euler_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) Euler_ass_slice, /* sq_ass_slice */
(lenfunc) Euler_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
(ssizeargfunc) NULL, /* sq_repeat */
(ssizeargfunc) Euler_item, /* sq_item */
(ssizessizeargfunc) NULL, /* sq_slice, deprecated */
(ssizeobjargproc) Euler_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyMappingMethods Euler_AsMapping = {
(lenfunc)Euler_len,
(binaryfunc)Euler_subscript,
(objobjargproc)Euler_ass_subscript
};
/*
* vector axis, vector.x/y/z/w
* euler axis, euler.x/y/z
*/
static PyObject *Euler_getAxis( EulerObject * self, void *type )
{
@@ -513,8 +590,12 @@ static int Euler_setAxis( EulerObject * self, PyObject * value, void * type )
/* rotation order */
static PyObject *Euler_getOrder(EulerObject *self, void *type)
{
static char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
return PyUnicode_FromString(order[self->order]);
const char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
if(!BaseMath_ReadCallback(self)) /* can read order too */
return NULL;
return PyUnicode_FromString(order[self->order-EULER_ORDER_XYZ]);
}
static int Euler_setOrder( EulerObject * self, PyObject * value, void * type )
@@ -522,15 +603,11 @@ static int Euler_setOrder( EulerObject * self, PyObject * value, void * type )
char *order_str= _PyUnicode_AsString(value);
short order= euler_order_from_string(order_str, "euler.order");
if(order < 0)
if(order == -1)
return -1;
if(self->cb_user) {
PyErr_SetString(PyExc_TypeError, "euler.order: assignment is not allowed on eulers with an owner");
return -1;
}
self->order= order;
BaseMath_WriteCallback(self); /* order can be written back */
return 0;
}
@@ -555,7 +632,7 @@ static struct PyMethodDef Euler_methods[] = {
{"unique", (PyCFunction) Euler_Unique, METH_NOARGS, Euler_Unique_doc},
{"to_matrix", (PyCFunction) Euler_ToMatrix, METH_NOARGS, Euler_ToMatrix_doc},
{"to_quat", (PyCFunction) Euler_ToQuat, METH_NOARGS, Euler_ToQuat_doc},
{"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, NULL},
{"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, Euler_Rotate_doc},
{"make_compatible", (PyCFunction) Euler_MakeCompatible, METH_O, Euler_MakeCompatible_doc},
{"__copy__", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
{"copy", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
@@ -579,7 +656,7 @@ PyTypeObject euler_Type = {
(reprfunc) Euler_repr, //tp_repr
0, //tp_as_number
&Euler_SeqMethods, //tp_as_sequence
0, //tp_as_mapping
&Euler_AsMapping, //tp_as_mapping
0, //tp_hash
0, //tp_call
0, //tp_str
@@ -623,7 +700,6 @@ PyTypeObject euler_Type = {
PyObject *newEulerObject(float *eul, short order, int type, PyTypeObject *base_type)
{
EulerObject *self;
int x;
if(base_type) self = (EulerObject *)base_type->tp_alloc(base_type, 0);
else self = PyObject_NEW(EulerObject, &euler_Type);
@@ -632,20 +708,20 @@ PyObject *newEulerObject(float *eul, short order, int type, PyTypeObject *base_t
self->cb_user= NULL;
self->cb_type= self->cb_subtype= 0;
if(type == Py_WRAP){
if(type == Py_WRAP) {
self->eul = eul;
self->wrapped = Py_WRAP;
}else if (type == Py_NEW){
self->eul = PyMem_Malloc(3 * sizeof(float));
if(!eul) { //new empty
for(x = 0; x < 3; x++) {
self->eul[x] = 0.0f;
}
}else{
VECCOPY(self->eul, eul);
}
}
else if (type == Py_NEW){
self->eul = PyMem_Malloc(EULER_SIZE * sizeof(float));
if(eul)
copy_v3_v3(self->eul, eul);
else
zero_v3(self->eul);
self->wrapped = Py_NEW;
}else{ //bad type
}
else{
return NULL;
}

View File

@@ -1,5 +1,5 @@
/*
* $Id: euler.h 21254 2009-06-30 00:42:17Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -37,14 +37,7 @@ extern PyTypeObject euler_Type;
#define EulerObject_Check(_v) PyObject_TypeCheck((_v), &euler_Type)
typedef struct {
PyObject_VAR_HEAD
float *eul; /*1D array of data */
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
unsigned char wrapped; /* wrapped data type? */
/* end BaseMathObject */
BASE_MATH_MEMBERS(eul)
unsigned char order; /* rotation order */
} EulerObject;

View File

@@ -1,5 +1,5 @@
/*
* $Id: matrix.c 21293 2009-07-01 20:55:32Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "Mathutils.h"
#include "mathutils.h"
#include "BKE_utildefines.h"
#include "BLI_math.h"
@@ -37,60 +37,60 @@ static PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject*
/* matrix vector callbacks */
int mathutils_matrix_vector_cb_index= -1;
static int mathutils_matrix_vector_check(PyObject *self_p)
static int mathutils_matrix_vector_check(BaseMathObject *bmo)
{
MatrixObject *self= (MatrixObject*)self_p;
MatrixObject *self= (MatrixObject *)bmo->cb_user;
return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_vector_get(PyObject *self_p, int subtype, float *vec_from)
static int mathutils_matrix_vector_get(BaseMathObject *bmo, int subtype)
{
MatrixObject *self= (MatrixObject*)self_p;
MatrixObject *self= (MatrixObject *)bmo->cb_user;
int i;
if(!BaseMath_ReadCallback(self))
return 0;
for(i=0; i<self->colSize; i++)
vec_from[i]= self->matrix[subtype][i];
for(i=0; i < self->colSize; i++)
bmo->data[i]= self->matrix[subtype][i];
return 1;
}
static int mathutils_matrix_vector_set(PyObject *self_p, int subtype, float *vec_to)
static int mathutils_matrix_vector_set(BaseMathObject *bmo, int subtype)
{
MatrixObject *self= (MatrixObject*)self_p;
MatrixObject *self= (MatrixObject *)bmo->cb_user;
int i;
if(!BaseMath_ReadCallback(self))
return 0;
for(i=0; i<self->colSize; i++)
self->matrix[subtype][i]= vec_to[i];
for(i=0; i < self->colSize; i++)
self->matrix[subtype][i]= bmo->data[i];
BaseMath_WriteCallback(self);
return 1;
}
static int mathutils_matrix_vector_get_index(PyObject *self_p, int subtype, float *vec_from, int index)
static int mathutils_matrix_vector_get_index(BaseMathObject *bmo, int subtype, int index)
{
MatrixObject *self= (MatrixObject*)self_p;
MatrixObject *self= (MatrixObject *)bmo->cb_user;
if(!BaseMath_ReadCallback(self))
return 0;
vec_from[index]= self->matrix[subtype][index];
bmo->data[index]= self->matrix[subtype][index];
return 1;
}
static int mathutils_matrix_vector_set_index(PyObject *self_p, int subtype, float *vec_to, int index)
static int mathutils_matrix_vector_set_index(BaseMathObject *bmo, int subtype, int index)
{
MatrixObject *self= (MatrixObject*)self_p;
MatrixObject *self= (MatrixObject *)bmo->cb_user;
if(!BaseMath_ReadCallback(self))
return 0;
self->matrix[subtype][index]= vec_to[index];
self->matrix[subtype][index]= bmo->data[index];
BaseMath_WriteCallback(self);
return 1;
@@ -105,7 +105,7 @@ Mathutils_Callback mathutils_matrix_vector_cb = {
};
/* matrix vector callbacks, this is so you can do matrix[i][j] = val */
//----------------------------------Mathutils.Matrix() -----------------
//----------------------------------mathutils.Matrix() -----------------
//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
//create a new matrix type
static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -118,8 +118,8 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
float scalar;
argSize = PyTuple_GET_SIZE(args);
if(argSize > 4){ //bad arg nums
PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
if(argSize > MATRIX_MAX_DIM) { //bad arg nums
PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
} else if (argSize == 0) { //return empty 4D matrix
return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
@@ -141,13 +141,13 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
if (PySequence_Check(argObject)) { //seq?
if(seqSize){ //0 at first
if(PySequence_Length(argObject) != seqSize){ //seq size not same
PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
}
seqSize = PySequence_Length(argObject);
}else{ //arg not a sequence
PyErr_SetString(PyExc_TypeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
PyErr_SetString(PyExc_TypeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
}
@@ -155,14 +155,14 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
for (i = 0; i < argSize; i++){
m = PyTuple_GET_ITEM(args, i);
if (m == NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
PyErr_SetString(PyExc_RuntimeError, "mathutils.Matrix(): failed to parse arguments...\n");
return NULL;
}
for (j = 0; j < seqSize; j++) {
s = PySequence_GetItem(m, j);
if (s == NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
PyErr_SetString(PyExc_RuntimeError, "mathutils.Matrix(): failed to parse arguments...\n");
return NULL;
}
@@ -170,7 +170,7 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Py_DECREF(s);
if(scalar==-1 && PyErr_Occurred()) { // parsed item is not a number
PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
@@ -221,7 +221,7 @@ static PyObject *Matrix_toQuat(MatrixObject * self)
return NULL;
}
if(self->colSize == 3){
mat3_to_quat( quat,(float (*)[3])self->contigPtr);
mat3_to_quat( quat,(float (*)[3])self->contigPtr);
}else{
mat4_to_quat( quat,(float (*)[4])self->contigPtr);
}
@@ -245,7 +245,7 @@ static char Matrix_toEuler_doc[] =
PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
{
char *order_str= NULL;
short order= 0;
short order= EULER_ORDER_XYZ;
float eul[3], eul_compatf[3];
EulerObject *eul_compat = NULL;
@@ -262,7 +262,7 @@ PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
if(!BaseMath_ReadCallback(eul_compat))
return NULL;
VECCOPY(eul_compatf, eul_compat->eul);
copy_v3_v3(eul_compatf, eul_compat->eul);
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
@@ -279,16 +279,16 @@ PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
if(order_str) {
order= euler_order_from_string(order_str, "Matrix.to_euler()");
if(order < 0)
if(order == -1)
return NULL;
}
if(eul_compat) {
if(order == 0) mat3_to_compatible_eul( eul, eul_compatf, mat);
if(order == 1) mat3_to_compatible_eul( eul, eul_compatf, mat);
else mat3_to_compatible_eulO(eul, eul_compatf, order, mat);
}
else {
if(order == 0) mat3_to_eul(eul, mat);
if(order == 1) mat3_to_eul(eul, mat);
else mat3_to_eulO(eul, order, mat);
}
@@ -321,11 +321,6 @@ PyObject *Matrix_Resize4x4(MatrixObject * self)
PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
return NULL;
}
self->matrix = PyMem_Realloc(self->matrix, (sizeof(float *) * 4));
if(self->matrix == NULL) {
PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
return NULL;
}
/*set row pointers*/
for(x = 0; x < 4; x++) {
self->matrix[x] = self->contigPtr + (x * 4);
@@ -728,27 +723,25 @@ PyObject *Matrix_copy(MatrixObject * self)
static PyObject *Matrix_repr(MatrixObject * self)
{
int x, y;
char buffer[48], str[1024];
char str[1024]="Matrix((", *str_p;
if(!BaseMath_ReadCallback(self))
return NULL;
BLI_strncpy(str,"",1024);
str_p= &str[8];
for(x = 0; x < self->colSize; x++){
sprintf(buffer, "[");
strcat(str,buffer);
for(y = 0; y < (self->rowSize - 1); y++) {
sprintf(buffer, "%.6f, ", self->matrix[y][x]);
strcat(str,buffer);
str_p += sprintf(str_p, "%f, ", self->matrix[y][x]);
}
if(x < (self->colSize-1)){
sprintf(buffer, "%.6f](matrix [row %d])\n", self->matrix[y][x], x);
strcat(str,buffer);
}else{
sprintf(buffer, "%.6f](matrix [row %d])", self->matrix[y][x], x);
strcat(str,buffer);
str_p += sprintf(str_p, "%f), (", self->matrix[y][x]);
}
else{
str_p += sprintf(str_p, "%f)", self->matrix[y][x]);
}
}
strcat(str_p, ")");
return PyUnicode_FromString(str);
}
@@ -1133,13 +1126,16 @@ static PyObject* Matrix_inv(MatrixObject *self)
/*-----------------PROTOCOL DECLARATIONS--------------------------*/
static PySequenceMethods Matrix_SeqMethods = {
(lenfunc) Matrix_len, /* sq_length */
(binaryfunc) 0, /* sq_concat */
(ssizeargfunc) 0, /* sq_repeat */
(ssizeargfunc) Matrix_item, /* sq_item */
(ssizessizeargfunc) Matrix_slice, /* sq_slice */
(ssizeobjargproc) Matrix_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) Matrix_ass_slice, /* sq_ass_slice */
(lenfunc) Matrix_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
(ssizeargfunc) NULL, /* sq_repeat */
(ssizeargfunc) Matrix_item, /* sq_item */
(ssizessizeargfunc) Matrix_slice, /* sq_slice, deprecated TODO, replace */
(ssizeobjargproc) Matrix_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) Matrix_ass_slice, /* sq_ass_slice, deprecated TODO, replace */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
@@ -1172,8 +1168,8 @@ static PyObject *Matrix_subscript(MatrixObject* self, PyObject* item)
}
else {
PyErr_Format(PyExc_TypeError,
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
return NULL;
}
}
@@ -1203,8 +1199,8 @@ static int Matrix_ass_subscript(MatrixObject* self, PyObject* item, PyObject* va
}
else {
PyErr_Format(PyExc_TypeError,
"matrix indices must be integers, not %.200s",
item->ob_type->tp_name);
"matrix indices must be integers, not %.200s",
item->ob_type->tp_name);
return -1;
}
}
@@ -1389,13 +1385,13 @@ PyTypeObject matrix_Type = {
/*------------------------newMatrixObject (internal)-------------
creates a new matrix object
self->matrix self->contiguous_ptr (reference to data.xxx)
[0]------------->[0]
[1]
[2]
[1]------------->[3]
[4]
[5]
....
[0]------------->[0]
[1]
[2]
[1]------------->[3]
[4]
[5]
....
self->matrix[1][1] = self->contigPtr[4] */
/*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
@@ -1425,12 +1421,6 @@ PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type, PyType
if(type == Py_WRAP){
self->contigPtr = mat;
/*create pointer array*/
self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
if(self->matrix == NULL) { /*allocation failure*/
PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
return NULL;
}
/*pointer array points to contigous memory*/
for(x = 0; x < rowSize; x++) {
self->matrix[x] = self->contigPtr + (x * colSize);
@@ -1442,13 +1432,6 @@ PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type, PyType
PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space\n");
return NULL;
}
/*create pointer array*/
self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
if(self->matrix == NULL) { /*allocation failure*/
PyMem_Free(self->contigPtr);
PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
return NULL;
}
/*pointer array points to contigous memory*/
for(x = 0; x < rowSize; x++) {
self->matrix[x] = self->contigPtr + (x * colSize);

View File

@@ -1,5 +1,5 @@
/*
* $Id: matrix.h 21254 2009-06-30 00:42:17Z campbellbarton $
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -34,21 +34,14 @@
extern PyTypeObject matrix_Type;
#define MatrixObject_Check(_v) PyObject_TypeCheck((_v), &matrix_Type)
#define MATRIX_MAX_DIM 4
typedef float **ptRow;
typedef struct _Matrix { /* keep aligned with BaseMathObject in Mathutils.h */
PyObject_VAR_HEAD
float *contigPtr; /*1D array of data (alias)*/
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
unsigned char wrapped; /*is wrapped data?*/
/* end BaseMathObject */
typedef struct {
BASE_MATH_MEMBERS(contigPtr)
unsigned char rowSize;
unsigned int colSize;
ptRow matrix; /*ptr to the contigPtr (accessor)*/
float *matrix[MATRIX_MAX_DIM]; /* ptr to the contigPtr (accessor) */
} MatrixObject;
/*struct data contains a pointer to the actual data that the

View File

@@ -1,5 +1,5 @@
/*
* $Id: quat.c 21462 2009-07-09 15:40:04Z ton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -26,13 +26,37 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "Mathutils.h"
#include "mathutils.h"
#include "BLI_math.h"
#include "BKE_utildefines.h"
#include "BLI_blenlib.h"
#define QUAT_SIZE 4
//-----------------------------METHODS------------------------------
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Quaternion_ToTupleExt(QuaternionObject *self, int ndigits)
{
PyObject *ret;
int i;
ret= PyTuple_New(QUAT_SIZE);
if(ndigits >= 0) {
for(i= 0; i < QUAT_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->quat[i], ndigits)));
}
}
else {
for(i= 0; i < QUAT_SIZE; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->quat[i]));
}
}
return ret;
}
static char Quaternion_ToEuler_doc[] =
".. method:: to_euler(order, euler_compat)\n"
"\n"
@@ -49,7 +73,7 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
{
float eul[3];
char *order_str= NULL;
short order= 0;
short order= EULER_ORDER_XYZ;
EulerObject *eul_compat = NULL;
if(!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
@@ -61,7 +85,7 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
if(order_str) {
order= euler_order_from_string(order_str, "Matrix.to_euler()");
if(order < 0)
if(order == -1)
return NULL;
}
@@ -73,12 +97,12 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
quat_to_mat3(mat, self->quat);
if(order == 0) mat3_to_compatible_eul(eul, eul_compat->eul, mat);
else mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
if(order == EULER_ORDER_XYZ) mat3_to_compatible_eul(eul, eul_compat->eul, mat);
else mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
}
else {
if(order == 0) quat_to_eul(eul, self->quat);
else quat_to_eulO(eul, order, self->quat);
if(order == EULER_ORDER_XYZ) quat_to_eul(eul, self->quat);
else quat_to_eulO(eul, order, self->quat);
}
return newEulerObject(eul, order, Py_NEW, NULL);
@@ -116,7 +140,7 @@ static char Quaternion_Cross_doc[] =
static PyObject *Quaternion_Cross(QuaternionObject * self, QuaternionObject * value)
{
float quat[4];
float quat[QUAT_SIZE];
if (!QuaternionObject_Check(value)) {
PyErr_SetString( PyExc_TypeError, "quat.cross(value): expected a quaternion argument" );
@@ -166,7 +190,7 @@ static char Quaternion_Difference_doc[] =
static PyObject *Quaternion_Difference(QuaternionObject * self, QuaternionObject * value)
{
float quat[4], tempQuat[4];
float quat[QUAT_SIZE], tempQuat[QUAT_SIZE];
double dot = 0.0f;
int x;
@@ -178,15 +202,11 @@ static PyObject *Quaternion_Difference(QuaternionObject * self, QuaternionObject
if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
return NULL;
tempQuat[0] = self->quat[0];
tempQuat[1] = - self->quat[1];
tempQuat[2] = - self->quat[2];
tempQuat[3] = - self->quat[3];
copy_qt_qt(tempQuat, self->quat);
conjugate_qt(tempQuat);
dot = sqrt(dot_qtqt(tempQuat, tempQuat));
dot = sqrt(tempQuat[0] * tempQuat[0] + tempQuat[1] * tempQuat[1] +
tempQuat[2] * tempQuat[2] + tempQuat[3] * tempQuat[3]);
for(x = 0; x < 4; x++) {
for(x = 0; x < QUAT_SIZE; x++) {
tempQuat[x] /= (float)(dot * dot);
}
mul_qt_qtqt(quat, tempQuat, value->quat);
@@ -208,7 +228,7 @@ static char Quaternion_Slerp_doc[] =
static PyObject *Quaternion_Slerp(QuaternionObject *self, PyObject *args)
{
QuaternionObject *value;
float quat[4], fac;
float quat[QUAT_SIZE], fac;
if(!PyArg_ParseTuple(args, "O!f:slerp", &quaternion_Type, &value, &fac)) {
PyErr_SetString(PyExc_TypeError, "quat.slerp(): expected Quaternion types and float");
@@ -352,14 +372,19 @@ static PyObject *Quaternion_copy(QuaternionObject * self)
//print the object to screen
static PyObject *Quaternion_repr(QuaternionObject * self)
{
char str[64];
PyObject *ret, *tuple;
if(!BaseMath_ReadCallback(self))
return NULL;
sprintf(str, "[%.6f, %.6f, %.6f, %.6f](quaternion)", self->quat[0], self->quat[1], self->quat[2], self->quat[3]);
return PyUnicode_FromString(str);
tuple= Quaternion_ToTupleExt(self, -1);
ret= PyUnicode_FromFormat("Quaternion(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
//------------------------tp_richcmpr
//returns -1 execption, 0 false, 1 true
static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
@@ -388,10 +413,10 @@ static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int c
switch (comparison_type){
case Py_EQ:
result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1);
break;
case Py_NE:
result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1);
if (result == 0){
result = 1;
}else{
@@ -414,15 +439,15 @@ static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int c
//sequence length
static int Quaternion_len(QuaternionObject * self)
{
return 4;
return QUAT_SIZE;
}
//----------------------------object[]---------------------------
//sequence accessor (get)
static PyObject *Quaternion_item(QuaternionObject * self, int i)
{
if(i<0) i= 4-i;
if(i<0) i= QUAT_SIZE-i;
if(i < 0 || i >= 4) {
if(i < 0 || i >= QUAT_SIZE) {
PyErr_SetString(PyExc_IndexError, "quaternion[attribute]: array index out of range\n");
return NULL;
}
@@ -443,9 +468,9 @@ static int Quaternion_ass_item(QuaternionObject * self, int i, PyObject * ob)
return -1;
}
if(i<0) i= 4-i;
if(i<0) i= QUAT_SIZE-i;
if(i < 0 || i >= 4){
if(i < 0 || i >= QUAT_SIZE){
PyErr_SetString(PyExc_IndexError, "quaternion[attribute] = x: array assignment index out of range\n");
return -1;
}
@@ -466,9 +491,9 @@ static PyObject *Quaternion_slice(QuaternionObject * self, int begin, int end)
if(!BaseMath_ReadCallback(self))
return NULL;
CLAMP(begin, 0, 4);
if (end<0) end= 5+end;
CLAMP(end, 0, 4);
CLAMP(begin, 0, QUAT_SIZE);
if (end<0) end= (QUAT_SIZE + 1) + end;
CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin,end);
list = PyList_New(end - begin);
@@ -483,52 +508,107 @@ static PyObject *Quaternion_slice(QuaternionObject * self, int begin, int end)
//sequence slice (set)
static int Quaternion_ass_slice(QuaternionObject * self, int begin, int end, PyObject * seq)
{
int i, y, size = 0;
float quat[4];
PyObject *q;
int i, size;
float quat[QUAT_SIZE];
if(!BaseMath_ReadCallback(self))
return -1;
CLAMP(begin, 0, 4);
if (end<0) end= 5+end;
CLAMP(end, 0, 4);
CLAMP(begin, 0, QUAT_SIZE);
if (end<0) end= (QUAT_SIZE + 1) + end;
CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin,end);
size = PySequence_Length(seq);
if((size=mathutils_array_parse(quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1)
return -1;
if(size != (end - begin)){
PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: size mismatch in slice assignment\n");
PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: size mismatch in slice assignment");
return -1;
}
for (i = 0; i < size; i++) {
q = PySequence_GetItem(seq, i);
if (q == NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "quaternion[begin:end] = []: unable to read sequence\n");
return -1;
}
quat[i]= (float)PyFloat_AsDouble(q);
Py_DECREF(q);
if(quat[i]==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: sequence argument not a number\n");
return -1;
}
}
//parsed well - now set in vector
for(y = 0; y < size; y++)
self->quat[begin + y] = quat[y];
/* parsed well - now set in vector */
for(i= 0; i < size; i++)
self->quat[begin + i] = quat[i];
BaseMath_WriteCallback(self);
return 0;
}
static PyObject *Quaternion_subscript(QuaternionObject *self, PyObject *item)
{
if (PyIndex_Check(item)) {
Py_ssize_t i;
i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
if (i < 0)
i += QUAT_SIZE;
return Quaternion_item(self, i);
} else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
return NULL;
if (slicelength <= 0) {
return PyList_New(0);
}
else if (step == 1) {
return Quaternion_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with quaternions");
return NULL;
}
}
else {
PyErr_Format(PyExc_TypeError,
"quaternion indices must be integers, not %.200s",
item->ob_type->tp_name);
return NULL;
}
}
static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyObject *value)
{
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return -1;
if (i < 0)
i += QUAT_SIZE;
return Quaternion_ass_item(self, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
return -1;
if (step == 1)
return Quaternion_ass_slice(self, start, stop, value);
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with quaternion");
return -1;
}
}
else {
PyErr_Format(PyExc_TypeError,
"quaternion indices must be integers, not %.200s",
item->ob_type->tp_name);
return -1;
}
}
//------------------------NUMERIC PROTOCOLS----------------------
//------------------------obj + obj------------------------------
//addition
static PyObject *Quaternion_add(PyObject * q1, PyObject * q2)
{
float quat[4];
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
@@ -549,7 +629,7 @@ static PyObject *Quaternion_add(PyObject * q1, PyObject * q2)
static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
{
int x;
float quat[4];
float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
@@ -563,7 +643,7 @@ static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
if(!BaseMath_ReadCallback(quat1) || !BaseMath_ReadCallback(quat2))
return NULL;
for(x = 0; x < 4; x++) {
for(x = 0; x < QUAT_SIZE; x++) {
quat[x] = quat1->quat[x] - quat2->quat[x];
}
@@ -573,7 +653,7 @@ static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
//mulplication
static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
{
float quat[4], scalar;
float quat[QUAT_SIZE], scalar;
QuaternionObject *quat1 = NULL, *quat2 = NULL;
VectorObject *vec = NULL;
@@ -627,50 +707,59 @@ static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
//-----------------PROTOCOL DECLARATIONS--------------------------
static PySequenceMethods Quaternion_SeqMethods = {
(lenfunc) Quaternion_len, /* sq_length */
(binaryfunc) 0, /* sq_concat */
(ssizeargfunc) 0, /* sq_repeat */
(ssizeargfunc) Quaternion_item, /* sq_item */
(ssizessizeargfunc) Quaternion_slice, /* sq_slice */
(ssizeobjargproc) Quaternion_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) Quaternion_ass_slice, /* sq_ass_slice */
(lenfunc) Quaternion_len, /* sq_length */
(binaryfunc) NULL, /* sq_concat */
(ssizeargfunc) NULL, /* sq_repeat */
(ssizeargfunc) Quaternion_item, /* sq_item */
(ssizessizeargfunc) NULL, /* sq_slice, deprecated */
(ssizeobjargproc) Quaternion_ass_item, /* sq_ass_item */
(ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyMappingMethods Quaternion_AsMapping = {
(lenfunc)Quaternion_len,
(binaryfunc)Quaternion_subscript,
(objobjargproc)Quaternion_ass_subscript
};
static PyNumberMethods Quaternion_NumMethods = {
(binaryfunc) Quaternion_add, /*nb_add*/
(binaryfunc) Quaternion_sub, /*nb_subtract*/
(binaryfunc) Quaternion_mul, /*nb_multiply*/
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
(unaryfunc) 0, /*nb_negative*/
(unaryfunc) 0, /*tp_positive*/
(unaryfunc) 0, /*tp_absolute*/
(inquiry) 0, /*tp_bool*/
(unaryfunc) 0, /*nb_invert*/
0, /*nb_lshift*/
(binaryfunc)0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
0, /*nb_int*/
0, /*nb_reserved*/
0, /*nb_float*/
0, /* nb_inplace_add */
0, /* nb_inplace_subtract */
0, /* nb_inplace_multiply */
0, /* nb_inplace_remainder */
0, /* nb_inplace_power */
0, /* nb_inplace_lshift */
0, /* nb_inplace_rshift */
0, /* nb_inplace_and */
0, /* nb_inplace_xor */
0, /* nb_inplace_or */
0, /* nb_floor_divide */
0, /* nb_true_divide */
0, /* nb_inplace_floor_divide */
0, /* nb_inplace_true_divide */
0, /* nb_index */
(binaryfunc) Quaternion_add, /*nb_add*/
(binaryfunc) Quaternion_sub, /*nb_subtract*/
(binaryfunc) Quaternion_mul, /*nb_multiply*/
0, /*nb_remainder*/
0, /*nb_divmod*/
0, /*nb_power*/
(unaryfunc) 0, /*nb_negative*/
(unaryfunc) 0, /*tp_positive*/
(unaryfunc) 0, /*tp_absolute*/
(inquiry) 0, /*tp_bool*/
(unaryfunc) 0, /*nb_invert*/
0, /*nb_lshift*/
(binaryfunc)0, /*nb_rshift*/
0, /*nb_and*/
0, /*nb_xor*/
0, /*nb_or*/
0, /*nb_int*/
0, /*nb_reserved*/
0, /*nb_float*/
0, /* nb_inplace_add */
0, /* nb_inplace_subtract */
0, /* nb_inplace_multiply */
0, /* nb_inplace_remainder */
0, /* nb_inplace_power */
0, /* nb_inplace_lshift */
0, /* nb_inplace_rshift */
0, /* nb_inplace_and */
0, /* nb_inplace_xor */
0, /* nb_inplace_or */
0, /* nb_floor_divide */
0, /* nb_true_divide */
0, /* nb_inplace_floor_divide */
0, /* nb_inplace_true_divide */
0, /* nb_index */
};
static PyObject *Quaternion_getAxis( QuaternionObject * self, void *type )
@@ -695,16 +784,11 @@ static PyObject *Quaternion_getAngle( QuaternionObject * self, void *type )
static PyObject *Quaternion_getAxisVec( QuaternionObject * self, void *type )
{
int i;
float vec[3];
double mag = self->quat[0] * (Py_PI / 180);
mag = 2 * (saacos(mag));
mag = sin(mag / 2);
for(i = 0; i < 3; i++)
vec[i] = (float)(self->quat[i + 1] / mag);
normalize_v3(vec);
//If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations
normalize_v3_v3(vec, self->quat+1);
/* If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations */
if( EXPP_FloatsAreEqual(vec[0], 0.0f, 10) &&
EXPP_FloatsAreEqual(vec[1], 0.0f, 10) &&
EXPP_FloatsAreEqual(vec[2], 0.0f, 10) ){
@@ -713,97 +797,31 @@ static PyObject *Quaternion_getAxisVec( QuaternionObject * self, void *type )
return (PyObject *) newVectorObject(vec, 3, Py_NEW, NULL);
}
//----------------------------------Mathutils.Quaternion() --------------
//----------------------------------mathutils.Quaternion() --------------
static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *listObject = NULL, *n, *q;
int size, i;
float quat[4];
double angle = 0.0f;
PyObject *seq= NULL;
float angle = 0.0f;
float quat[QUAT_SIZE]= {0.0f, 0.0f, 0.0f, 0.0f};
size = PyTuple_GET_SIZE(args);
if (size == 1 || size == 2) { //seq?
listObject = PyTuple_GET_ITEM(args, 0);
if (PySequence_Check(listObject)) {
size = PySequence_Length(listObject);
if ((size == 4 && PySequence_Length(args) !=1) ||
(size == 3 && PySequence_Length(args) !=2) || (size >4 || size < 3)) {
// invalid args/size
PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
if(size == 3){ //get angle in axis/angle
n = PySequence_GetItem(args, 1);
if(n == NULL) { // parsed item not a number or getItem fail
PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
if(!PyArg_ParseTuple(args, "|Of:mathutils.Quaternion", &seq, &angle))
return NULL;
angle = PyFloat_AsDouble(n);
Py_DECREF(n);
if (angle==-1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
}
}else{
listObject = PyTuple_GET_ITEM(args, 1);
if (size>1 && PySequence_Check(listObject)) {
size = PySequence_Length(listObject);
if (size != 3) {
// invalid args/size
PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
angle = PyFloat_AsDouble(PyTuple_GET_ITEM(args, 0));
if (angle==-1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
} else { // argument was not a sequence
PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
}
} else if (size == 0) { //returns a new empty quat
return newQuaternionObject(NULL, Py_NEW, NULL);
} else {
listObject = args;
}
if (size == 3) { // invalid quat size
if(PySequence_Length(args) != 2){
PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
switch(PyTuple_GET_SIZE(args)) {
case 0:
break;
case 1:
if (mathutils_array_parse(quat, QUAT_SIZE, QUAT_SIZE, seq, "mathutils.Quaternion()") == -1)
return NULL;
}
}else{
if(size != 4){
PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
break;
case 2:
if (mathutils_array_parse(quat, 3, 3, seq, "mathutils.Quaternion()") == -1)
return NULL;
}
}
for (i=0; i<size; i++) { //parse
q = PySequence_GetItem(listObject, i);
if (q == NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
quat[i] = PyFloat_AsDouble(q);
Py_DECREF(q);
if (quat[i]==-1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
return NULL;
}
}
if(size == 3) //calculate the quat based on axis/angle
axis_angle_to_quat(quat, quat, angle);
break;
/* PyArg_ParseTuple assures no more then 2 */
}
return newQuaternionObject(quat, Py_NEW, NULL);
}
@@ -856,10 +874,10 @@ PyTypeObject quaternion_Type = {
0, //tp_getattr
0, //tp_setattr
0, //tp_compare
(reprfunc) Quaternion_repr, //tp_repr
&Quaternion_NumMethods, //tp_as_number
&Quaternion_SeqMethods, //tp_as_sequence
0, //tp_as_mapping
(reprfunc) Quaternion_repr, //tp_repr
&Quaternion_NumMethods, //tp_as_number
&Quaternion_SeqMethods, //tp_as_sequence
&Quaternion_AsMapping, //tp_as_mapping
0, //tp_hash
0, //tp_call
0, //tp_str
@@ -915,7 +933,7 @@ PyObject *newQuaternionObject(float *quat, int type, PyTypeObject *base_type)
self->quat = quat;
self->wrapped = Py_WRAP;
}else if (type == Py_NEW){
self->quat = PyMem_Malloc(4 * sizeof(float));
self->quat = PyMem_Malloc(QUAT_SIZE * sizeof(float));
if(!quat) { //new empty
unit_qt(self->quat);
}else{

View File

@@ -1,5 +1,5 @@
/*
* $Id: quat.h 21254 2009-06-30 00:42:17Z campbellbarton $
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -36,15 +36,8 @@
extern PyTypeObject quaternion_Type;
#define QuaternionObject_Check(_v) PyObject_TypeCheck((_v), &quaternion_Type)
typedef struct { /* keep aligned with BaseMathObject in Mathutils.h */
PyObject_VAR_HEAD
float *quat; /* 1D array of data (alias) */
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
unsigned char wrapped; /* wrapped data type? */
/* end BaseMathObject */
typedef struct {
BASE_MATH_MEMBERS(quat)
} QuaternionObject;
/*struct data contains a pointer to the actual data that the

View File

@@ -1,5 +1,5 @@
/*
* $Id: vector.c 21462 2009-07-09 15:40:04Z ton $
* $Id$
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "Mathutils.h"
#include "mathutils.h"
#include "BLI_blenlib.h"
#include "BKE_utildefines.h"
@@ -40,55 +40,27 @@
#define SWIZZLE_AXIS 0x3
static PyObject *row_vector_multiplication(VectorObject* vec, MatrixObject * mat); /* utility func */
static PyObject *Vector_ToTupleExt(VectorObject *self, int ndigits);
//----------------------------------Mathutils.Vector() ------------------
//----------------------------------mathutils.Vector() ------------------
// Supports 2D, 3D, and 4D vector objects both int and float values
// accepted. Mixed float and int values accepted. Ints are parsed to float
static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyObject *listObject = NULL;
int size, i;
float vec[4], f;
PyObject *v;
float vec[4]= {0.0f, 0.0f, 0.0f, 0.0f};
int size= 3; /* default to a 3D vector */
size = PyTuple_GET_SIZE(args); /* we know its a tuple because its an arg */
if (size == 1) {
listObject = PyTuple_GET_ITEM(args, 0);
if (PySequence_Check(listObject)) {
size = PySequence_Length(listObject);
} else { // Single argument was not a sequence
PyErr_SetString(PyExc_TypeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
switch(PyTuple_GET_SIZE(args)) {
case 0:
break;
case 1:
if((size=mathutils_array_parse(vec, 2, 4, PyTuple_GET_ITEM(args, 0), "mathutils.Vector()")) == -1)
return NULL;
}
} else if (size == 0) {
//returns a new empty 3d vector
return newVectorObject(NULL, 3, Py_NEW, type);
} else {
listObject = args;
}
if (size<2 || size>4) { // Invalid vector size
PyErr_SetString(PyExc_AttributeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
break;
default:
PyErr_SetString(PyExc_TypeError, "mathutils.Vector(): more then a single arg given");
return NULL;
}
for (i=0; i<size; i++) {
v=PySequence_GetItem(listObject, i);
if (v==NULL) { // Failed to read sequence
PyErr_SetString(PyExc_RuntimeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
return NULL;
}
f= PyFloat_AsDouble(v);
if(f==-1 && PyErr_Occurred()) { // parsed item not a number
Py_DECREF(v);
PyErr_SetString(PyExc_TypeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
return NULL;
}
vec[i]= f;
Py_DECREF(v);
}
return newVectorObject(vec, size, Py_NEW, type);
}
@@ -101,7 +73,7 @@ static char Vector_Zero_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Zero(VectorObject * self)
static PyObject *Vector_Zero(VectorObject *self)
{
int i;
for(i = 0; i < self->size; i++) {
@@ -125,7 +97,7 @@ static char Vector_Normalize_doc[] =
"\n"
" .. note:: Normalize works for vectors of all sizes, however 4D Vectors w axis is left untouched.\n";
static PyObject *Vector_Normalize(VectorObject * self)
static PyObject *Vector_Normalize(VectorObject *self)
{
int i;
float norm = 0.0f;
@@ -156,7 +128,7 @@ static char Vector_Resize2D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Resize2D(VectorObject * self)
static PyObject *Vector_Resize2D(VectorObject *self)
{
if(self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize2D(): cannot resize wrapped data - only python vectors\n");
@@ -186,7 +158,7 @@ static char Vector_Resize3D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Resize3D(VectorObject * self)
static PyObject *Vector_Resize3D(VectorObject *self)
{
if (self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize3D(): cannot resize wrapped data - only python vectors\n");
@@ -219,7 +191,7 @@ static char Vector_Resize4D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Resize4D(VectorObject * self)
static PyObject *Vector_Resize4D(VectorObject *self)
{
if(self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize4D(): cannot resize wrapped data - only python vectors");
@@ -248,37 +220,56 @@ static PyObject *Vector_Resize4D(VectorObject * self)
/*----------------------------Vector.toTuple() ------------------ */
static char Vector_ToTuple_doc[] =
".. method:: to_tuple(precision)\n"
".. method:: to_tuple(precision=-1)\n"
"\n"
" Return this vector as a tuple with.\n"
"\n"
" :arg precision: The number to round the value to in [0, 21].\n"
" :arg precision: The number to round the value to in [-1, 21].\n"
" :type precision: int\n"
" :return: the values of the vector rounded by *precision*\n"
" :rtype: tuple\n";
static PyObject *Vector_ToTuple(VectorObject * self, PyObject *value)
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Vector_ToTupleExt(VectorObject *self, int ndigits)
{
int ndigits= PyLong_AsSsize_t(value);
int x;
PyObject *ret;
int i;
if(ndigits > 22 || ndigits < 0) { /* accounts for non ints */
PyErr_SetString(PyExc_TypeError, "vector.to_tuple(ndigits): ndigits must be between 0 and 21");
ret= PyTuple_New(self->size);
if(ndigits >= 0) {
for(i = 0; i < self->size; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->vec[i], ndigits)));
}
}
else {
for(i = 0; i < self->size; i++) {
PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->vec[i]));
}
}
return ret;
}
static PyObject *Vector_ToTuple(VectorObject *self, PyObject *args)
{
int ndigits= 0;
if(!PyArg_ParseTuple(args, "|i:to_tuple", &ndigits))
return NULL;
if(ndigits > 22 || ndigits < 0) {
PyErr_SetString(PyExc_ValueError, "vector.to_tuple(ndigits): ndigits must be between 0 and 21");
return NULL;
}
if(PyTuple_GET_SIZE(args)==0)
ndigits= -1;
if(!BaseMath_ReadCallback(self))
return NULL;
ret= PyTuple_New(self->size);
for(x = 0; x < self->size; x++) {
PyTuple_SET_ITEM(ret, x, PyFloat_FromDouble(double_round((double)self->vec[x], ndigits)));
}
return ret;
return Vector_ToTupleExt(self, ndigits);
}
/*----------------------------Vector.toTrackQuat(track, up) ---------------------- */
@@ -291,19 +282,18 @@ static char Vector_ToTrackQuat_doc[] =
" :type track: string\n"
" :arg up: Up axis in ['X', 'Y', 'Z'].\n"
" :type up: string\n"
" :return: rotation from the vector and the track and up axis."
" :return: rotation from the vector and the track and up axis.\n"
" :rtype: :class:`Quaternion`\n";
static PyObject *Vector_ToTrackQuat( VectorObject * self, PyObject * args )
static PyObject *Vector_ToTrackQuat(VectorObject *self, PyObject *args )
{
float vec[3], quat[4];
char *strack, *sup;
short track = 2, up = 1;
if(!PyArg_ParseTuple( args, "|ss:to_track_quat", &strack, &sup)) {
PyErr_SetString( PyExc_TypeError, "expected optional two strings\n" );
if(!PyArg_ParseTuple( args, "|ss:to_track_quat", &strack, &sup))
return NULL;
}
if (self->size != 3) {
PyErr_SetString( PyExc_TypeError, "only for 3D vectors\n" );
return NULL;
@@ -413,7 +403,7 @@ static char Vector_Reflect_doc[] =
" :return: The reflected vector matching the size of this vector.\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Reflect( VectorObject * self, VectorObject * value )
static PyObject *Vector_Reflect(VectorObject *self, VectorObject *value )
{
float mirror[3], vec[3];
float reflect[3] = {0.0f, 0.0f, 0.0f};
@@ -454,7 +444,7 @@ static char Vector_Cross_doc[] =
"\n"
" .. note:: both vectors must be 3D\n";
static PyObject *Vector_Cross( VectorObject * self, VectorObject * value )
static PyObject *Vector_Cross(VectorObject *self, VectorObject *value )
{
VectorObject *vecCross = NULL;
@@ -486,7 +476,7 @@ static char Vector_Dot_doc[] =
" :return: The dot product.\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Dot( VectorObject * self, VectorObject * value )
static PyObject *Vector_Dot(VectorObject *self, VectorObject *value )
{
double dot = 0.0;
int x;
@@ -510,21 +500,28 @@ static PyObject *Vector_Dot( VectorObject * self, VectorObject * value )
return PyFloat_FromDouble(dot);
}
static char Vector_Angle_doc[] =
".. function:: angle(other)\n"
static char Vector_angle_doc[] =
".. function:: angle(other, fallback)\n"
"\n"
" Return the angle between two vectors.\n"
"\n"
" :arg other: another vector to compare the angle with\n"
" :type other: :class:`Vector`\n"
" :return angle: angle in radians\n"
" :arg fallback: return this value when the angle cant be calculated (zero length vector)\n"
" :return angle: angle in radians or fallback when given\n"
" :rtype: float\n"
"\n"
" .. note:: Zero length vectors raise an :exc:`AttributeError`.\n";
static PyObject *Vector_Angle(VectorObject * self, VectorObject * value)
static PyObject *Vector_angle(VectorObject *self, PyObject *args)
{
double dot = 0.0f, angleRads, test_v1 = 0.0f, test_v2 = 0.0f;
VectorObject *value;
double dot = 0.0f, angleRads, test_v1 = 0.0f, test_v2 = 0.0f;
int x, size;
PyObject *fallback= NULL;
if(!PyArg_ParseTuple(args, "O!|O:angle", &vector_Type, &value, &fallback))
return NULL;
if (!VectorObject_Check(value)) {
PyErr_SetString( PyExc_TypeError, "vec.angle(value): expected a vector argument" );
return NULL;
@@ -546,8 +543,15 @@ static PyObject *Vector_Angle(VectorObject * self, VectorObject * value)
test_v2 += value->vec[x] * value->vec[x];
}
if (!test_v1 || !test_v2){
PyErr_SetString(PyExc_AttributeError, "vector.angle(other): zero length vectors are not acceptable arguments\n");
return NULL;
/* avoid exception */
if(fallback) {
Py_INCREF(fallback);
return fallback;
}
else {
PyErr_SetString(PyExc_ValueError, "vector.angle(other): zero length vectors have no valid angle\n");
return NULL;
}
}
//dot product
@@ -573,7 +577,7 @@ static char Vector_Difference_doc[] =
"\n"
" .. note:: 2D vectors raise an :exc:`AttributeError`.\n";;
static PyObject *Vector_Difference( VectorObject * self, VectorObject * value )
static PyObject *Vector_Difference(VectorObject *self, VectorObject *value )
{
float quat[4], vec_a[3], vec_b[3];
@@ -607,7 +611,7 @@ static char Vector_Project_doc[] =
" :return projection: the parallel projection vector\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Project(VectorObject * self, VectorObject * value)
static PyObject *Vector_Project(VectorObject *self, VectorObject *value)
{
float vec[4];
double dot = 0.0f, dot2 = 0.0f;
@@ -643,7 +647,6 @@ static PyObject *Vector_Project(VectorObject * self, VectorObject * value)
return newVectorObject(vec, size, Py_NEW, NULL);
}
//----------------------------------Mathutils.MidpointVecs() -------------
static char Vector_Lerp_doc[] =
".. function:: lerp(other, factor)\n"
"\n"
@@ -656,16 +659,15 @@ static char Vector_Lerp_doc[] =
" :return: The interpolated rotation.\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Lerp(VectorObject * self, PyObject * args)
static PyObject *Vector_Lerp(VectorObject *self, PyObject *args)
{
VectorObject *vec2 = NULL;
float fac, ifac, vec[4];
int x;
if(!PyArg_ParseTuple(args, "O!f:lerp", &vector_Type, &vec2, &fac)) {
PyErr_SetString(PyExc_TypeError, "vector.lerp(): expects a vector of the same size and float");
if(!PyArg_ParseTuple(args, "O!f:lerp", &vector_Type, &vec2, &fac))
return NULL;
}
if(self->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError, "vector.lerp(): expects (2) vector objects of the same size");
return NULL;
@@ -693,7 +695,7 @@ static char Vector_copy_doc[] =
"\n"
" .. note:: use this to get a copy of a wrapped vector with no reference to the original data.\n";
static PyObject *Vector_copy(VectorObject * self)
static PyObject *Vector_copy(VectorObject *self)
{
if(!BaseMath_ReadCallback(self))
return NULL;
@@ -703,38 +705,29 @@ static PyObject *Vector_copy(VectorObject * self)
/*----------------------------print object (internal)-------------
print the object to screen */
static PyObject *Vector_repr(VectorObject * self)
static PyObject *Vector_repr(VectorObject *self)
{
int i;
char buffer[48], str[1024];
PyObject *ret, *tuple;
if(!BaseMath_ReadCallback(self))
return NULL;
BLI_strncpy(str,"[",1024);
for(i = 0; i < self->size; i++){
if(i < (self->size - 1)){
sprintf(buffer, "%.6f, ", self->vec[i]);
strcat(str,buffer);
}else{
sprintf(buffer, "%.6f", self->vec[i]);
strcat(str,buffer);
}
}
strcat(str, "](vector)");
return PyUnicode_FromString(str);
tuple= Vector_ToTupleExt(self, -1);
ret= PyUnicode_FromFormat("Vector(%R)", tuple);
Py_DECREF(tuple);
return ret;
}
/*---------------------SEQUENCE PROTOCOLS------------------------
----------------------------len(object)------------------------
sequence length*/
static int Vector_len(VectorObject * self)
static int Vector_len(VectorObject *self)
{
return self->size;
}
/*----------------------------object[]---------------------------
sequence accessor (get)*/
static PyObject *Vector_item(VectorObject * self, int i)
static PyObject *Vector_item(VectorObject *self, int i)
{
if(i<0) i= self->size-i;
@@ -751,10 +744,10 @@ static PyObject *Vector_item(VectorObject * self, int i)
}
/*----------------------------object[]-------------------------
sequence accessor (set)*/
static int Vector_ass_item(VectorObject * self, int i, PyObject * ob)
static int Vector_ass_item(VectorObject *self, int i, PyObject * ob)
{
float scalar= (float)PyFloat_AsDouble(ob);
if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
float scalar;
if((scalar=PyFloat_AsDouble(ob))==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "vector[index] = x: index argument not a number\n");
return -1;
}
@@ -774,7 +767,7 @@ static int Vector_ass_item(VectorObject * self, int i, PyObject * ob)
/*----------------------------object[z:y]------------------------
sequence slice (get) */
static PyObject *Vector_slice(VectorObject * self, int begin, int end)
static PyObject *Vector_slice(VectorObject *self, int begin, int end)
{
PyObject *list = NULL;
int count;
@@ -796,8 +789,8 @@ static PyObject *Vector_slice(VectorObject * self, int begin, int end)
}
/*----------------------------object[z:y]------------------------
sequence slice (set) */
static int Vector_ass_slice(VectorObject * self, int begin, int end,
PyObject * seq)
static int Vector_ass_slice(VectorObject *self, int begin, int end,
PyObject * seq)
{
int i, y, size = 0;
float vec[4], scalar;
@@ -824,8 +817,7 @@ static int Vector_ass_slice(VectorObject * self, int begin, int end,
return -1;
}
scalar= (float)PyFloat_AsDouble(v);
if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
if((scalar=PyFloat_AsDouble(v)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
Py_DECREF(v);
PyErr_SetString(PyExc_TypeError, "vector[begin:end] = []: sequence argument not a number\n");
return -1;
@@ -1118,14 +1110,13 @@ static PyObject *Vector_div(PyObject * v1, PyObject * v2)
if(!BaseMath_ReadCallback(vec1))
return NULL;
scalar = (float)PyFloat_AsDouble(v2);
if(scalar== -1.0f && PyErr_Occurred()) { /* parsed item not a number */
if((scalar=PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "Vector division: Vector must be divided by a float\n");
return NULL;
}
if(scalar==0.0) { /* not a vector */
if(scalar==0.0) {
PyErr_SetString(PyExc_ZeroDivisionError, "Vector division: divide by zero error.\n");
return NULL;
}
@@ -1147,13 +1138,12 @@ static PyObject *Vector_idiv(PyObject * v1, PyObject * v2)
if(!BaseMath_ReadCallback(vec1))
return NULL;
scalar = (float)PyFloat_AsDouble(v2);
if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
if((scalar=PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "Vector division: Vector must be divided by a float\n");
return NULL;
}
if(scalar==0.0) { /* not a vector */
if(scalar==0.0) {
PyErr_SetString(PyExc_ZeroDivisionError, "Vector division: divide by zero error.\n");
return NULL;
}
@@ -1283,13 +1273,16 @@ static PyObject* Vector_richcmpr(PyObject *objectA, PyObject *objectB, int compa
/*-----------------PROTCOL DECLARATIONS--------------------------*/
static PySequenceMethods Vector_SeqMethods = {
(lenfunc) Vector_len, /* sq_length */
(binaryfunc) 0, /* sq_concat */
(ssizeargfunc) 0, /* sq_repeat */
(ssizeargfunc) Vector_item, /* sq_item */
NULL, /* py3 deprecated slice func */
(ssizeobjargproc) Vector_ass_item, /* sq_ass_item */
NULL, /* py3 deprecated slice assign func */
(lenfunc) Vector_len, /* sq_length */
(binaryfunc) 0, /* sq_concat */
(ssizeargfunc) 0, /* sq_repeat */
(ssizeargfunc) Vector_item, /* sq_item */
NULL, /* py3 deprecated slice func */
(ssizeobjargproc) Vector_ass_item, /* sq_ass_item */
NULL, /* py3 deprecated slice assign func */
(objobjproc) NULL, /* sq_contains */
(binaryfunc) NULL, /* sq_inplace_concat */
(ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyObject *Vector_subscript(VectorObject* self, PyObject* item)
@@ -1321,8 +1314,8 @@ static PyObject *Vector_subscript(VectorObject* self, PyObject* item)
}
else {
PyErr_Format(PyExc_TypeError,
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
return NULL;
}
}
@@ -1352,8 +1345,8 @@ static int Vector_ass_subscript(VectorObject* self, PyObject* item, PyObject* va
}
else {
PyErr_Format(PyExc_TypeError,
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
"vector indices must be integers, not %.200s",
item->ob_type->tp_name);
return -1;
}
}
@@ -1408,18 +1401,18 @@ static PyNumberMethods Vector_NumMethods = {
* vector axis, vector.x/y/z/w
*/
static PyObject *Vector_getAxis( VectorObject * self, void *type )
static PyObject *Vector_getAxis(VectorObject *self, void *type )
{
return Vector_item(self, GET_INT_FROM_POINTER(type));
}
static int Vector_setAxis( VectorObject * self, PyObject * value, void * type )
static int Vector_setAxis(VectorObject *self, PyObject * value, void * type )
{
return Vector_ass_item(self, GET_INT_FROM_POINTER(type), value);
}
/* vector.length */
static PyObject *Vector_getLength( VectorObject * self, void *type )
static PyObject *Vector_getLength(VectorObject *self, void *type )
{
double dot = 0.0f;
int i;
@@ -1433,25 +1426,24 @@ static PyObject *Vector_getLength( VectorObject * self, void *type )
return PyFloat_FromDouble(sqrt(dot));
}
static int Vector_setLength( VectorObject * self, PyObject * value )
static int Vector_setLength(VectorObject *self, PyObject * value )
{
double dot = 0.0f, param;
int i;
if(!BaseMath_ReadCallback(self))
return -1;
param= PyFloat_AsDouble( value );
if(param==-1.0 && PyErr_Occurred()) {
if((param=PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "length must be set to a number");
return -1;
}
if (param < 0) {
if (param < 0.0f) {
PyErr_SetString( PyExc_TypeError, "cannot set a vectors length to a negative value" );
return -1;
}
if (param==0) {
if (param == 0.0f) {
for(i = 0; i < self->size; i++){
self->vec[i]= 0;
}
@@ -1484,10 +1476,10 @@ static int Vector_setLength( VectorObject * self, PyObject * value )
/* Get a new Vector according to the provided swizzle. This function has little
error checking, as we are in control of the inputs: the closure is set by us
in Vector_createSwizzleGetSeter. */
static PyObject *Vector_getSwizzle(VectorObject * self, void *closure)
static PyObject *Vector_getSwizzle(VectorObject *self, void *closure)
{
size_t axisA;
size_t axisB;
size_t axis_to;
size_t axis_from;
float vec[MAX_DIMENSIONS];
unsigned int swizzleClosure;
@@ -1495,46 +1487,46 @@ static PyObject *Vector_getSwizzle(VectorObject * self, void *closure)
return NULL;
/* Unpack the axes from the closure into an array. */
axisA = 0;
axis_to = 0;
swizzleClosure = GET_INT_FROM_POINTER(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
axisB = swizzleClosure & SWIZZLE_AXIS;
if(axisB >= self->size) {
axis_from = swizzleClosure & SWIZZLE_AXIS;
if(axis_from >= self->size) {
PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.");
return NULL;
}
vec[axisA] = self->vec[axisB];
vec[axis_to] = self->vec[axis_from];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axisA++;
axis_to++;
}
return newVectorObject(vec, axisA, Py_NEW, Py_TYPE(self));
return newVectorObject(vec, axis_to, Py_NEW, Py_TYPE(self));
}
/* Set the items of this vector using a swizzle.
- If value is a vector or list this operates like an array copy, except that
the destination is effectively re-ordered as defined by the swizzle. At
most min(len(source), len(dest)) values will be copied.
the destination is effectively re-ordered as defined by the swizzle. At
most min(len(source), len(dest)) values will be copied.
- If the value is scalar, it is copied to all axes listed in the swizzle.
- If an axis appears more than once in the swizzle, the final occurrence is
the one that determines its value.
the one that determines its value.
Returns 0 on success and -1 on failure. On failure, the vector will be
unchanged. */
static int Vector_setSwizzle(VectorObject * self, PyObject * value, void *closure)
static int Vector_setSwizzle(VectorObject *self, PyObject * value, void *closure)
{
VectorObject *vecVal = NULL;
PyObject *item;
size_t listLen;
size_t size_from;
float scalarVal;
size_t axisB;
size_t axisA;
size_t axis_from;
size_t axis_to;
unsigned int swizzleClosure;
float vecTemp[MAX_DIMENSIONS];
float tvec[MAX_DIMENSIONS];
float vec_assign[MAX_DIMENSIONS];
if(!BaseMath_ReadCallback(self))
return -1;
@@ -1542,95 +1534,48 @@ static int Vector_setSwizzle(VectorObject * self, PyObject * value, void *closur
/* Check that the closure can be used with this vector: even 2D vectors have
swizzles defined for axes z and w, but they would be invalid. */
swizzleClosure = GET_INT_FROM_POINTER(closure);
axis_from= 0;
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
axisA = swizzleClosure & SWIZZLE_AXIS;
if (axisA >= self->size)
axis_to = swizzleClosure & SWIZZLE_AXIS;
if (axis_to >= self->size)
{
PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.\n");
return -1;
}
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axis_from++;
}
if (VectorObject_Check(value))
{
/* Copy vector contents onto swizzled axes. */
vecVal = (VectorObject*) value;
axisB = 0;
swizzleClosure = GET_INT_FROM_POINTER(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS && axisB < vecVal->size)
{
axisA = swizzleClosure & SWIZZLE_AXIS;
if(axisB >= vecVal->size) {
PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.");
return -1;
}
if (((scalarVal=PyFloat_AsDouble(value)) == -1 && PyErr_Occurred())==0) {
int i;
for(i=0; i < MAX_DIMENSIONS; i++)
vec_assign[i]= scalarVal;
vecTemp[axisA] = vecVal->vec[axisB];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axisB++;
}
if(axisB != vecVal->size) {
PyErr_SetString(PyExc_AttributeError, "Error: vector size does not match swizzle.\n");
return -1;
}
memcpy(self->vec, vecTemp, axisB * sizeof(float));
/* continue with BaseMathObject_WriteCallback at the end */
size_from= axis_from;
}
else if (PyList_Check(value))
{
/* Copy list contents onto swizzled axes. */
listLen = PyList_Size(value);
swizzleClosure = GET_INT_FROM_POINTER(closure);
axisB = 0;
while (swizzleClosure & SWIZZLE_VALID_AXIS && axisB < listLen)
{
item = PyList_GetItem(value, axisB);
scalarVal = (float)PyFloat_AsDouble(item);
if (scalarVal==-1.0 && PyErr_Occurred()) {
PyErr_SetString(PyExc_AttributeError, "Error: list item could not be used as a float.\n");
return -1;
}
axisA = swizzleClosure & SWIZZLE_AXIS;
vecTemp[axisA] = scalarVal;
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axisB++;
}
if(axisB != listLen) {
PyErr_SetString(PyExc_AttributeError, "Error: list size does not match swizzle.\n");
return -1;
}
memcpy(self->vec, vecTemp, axisB * sizeof(float));
/* continue with BaseMathObject_WriteCallback at the end */
}
else if (((scalarVal = (float)PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred())==0)
{
/* Assign the same value to each axis. */
swizzleClosure = GET_INT_FROM_POINTER(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
axisA = swizzleClosure & SWIZZLE_AXIS;
self->vec[axisA] = scalarVal;
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
}
/* continue with BaseMathObject_WriteCallback at the end */
}
else {
PyErr_SetString( PyExc_TypeError, "Expected a Vector, list or scalar value." );
else if((size_from=mathutils_array_parse(vec_assign, 2, 4, value, "mathutils.Vector.**** = swizzle assignment")) == -1) {
return -1;
}
if(axis_from != size_from) {
PyErr_SetString(PyExc_AttributeError, "Error: vector size does not match swizzle.\n");
return -1;
}
/* Copy vector contents onto swizzled axes. */
axis_from = 0;
swizzleClosure = GET_INT_FROM_POINTER(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
axis_to = swizzleClosure & SWIZZLE_AXIS;
tvec[axis_to] = vec_assign[axis_from];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
axis_from++;
}
memcpy(self->vec, tvec, axis_from * sizeof(float));
/* continue with BaseMathObject_WriteCallback at the end */
if(!BaseMath_WriteCallback(self))
return -1;
@@ -2080,7 +2025,7 @@ static char Vector_Negate_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
static PyObject *Vector_Negate(VectorObject * self)
static PyObject *Vector_Negate(VectorObject *self)
{
int i;
if(!BaseMath_ReadCallback(self))
@@ -2102,12 +2047,12 @@ static struct PyMethodDef Vector_methods[] = {
{"resize2D", (PyCFunction) Vector_Resize2D, METH_NOARGS, Vector_Resize2D_doc},
{"resize3D", (PyCFunction) Vector_Resize3D, METH_NOARGS, Vector_Resize3D_doc},
{"resize4D", (PyCFunction) Vector_Resize4D, METH_NOARGS, Vector_Resize4D_doc},
{"to_tuple", (PyCFunction) Vector_ToTuple, METH_O, Vector_ToTuple_doc},
{"to_tuple", (PyCFunction) Vector_ToTuple, METH_VARARGS, Vector_ToTuple_doc},
{"to_track_quat", ( PyCFunction ) Vector_ToTrackQuat, METH_VARARGS, Vector_ToTrackQuat_doc},
{"reflect", ( PyCFunction ) Vector_Reflect, METH_O, Vector_Reflect_doc},
{"cross", ( PyCFunction ) Vector_Cross, METH_O, Vector_Cross_doc},
{"dot", ( PyCFunction ) Vector_Dot, METH_O, Vector_Dot_doc},
{"angle", ( PyCFunction ) Vector_Angle, METH_O, Vector_Angle_doc},
{"angle", ( PyCFunction ) Vector_angle, METH_VARARGS, Vector_angle_doc},
{"difference", ( PyCFunction ) Vector_Difference, METH_O, Vector_Difference_doc},
{"project", ( PyCFunction ) Vector_Project, METH_O, Vector_Project_doc},
{"lerp", ( PyCFunction ) Vector_Lerp, METH_VARARGS, Vector_Lerp_doc},
@@ -2130,7 +2075,7 @@ PyTypeObject vector_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* For printing, in format "<module>.<name>" */
"vector", /* char *tp_name; */
sizeof( VectorObject ), /* int tp_basicsize; */
sizeof(VectorObject), /* int tp_basicsize; */
0, /* tp_itemsize; For allocation */
/* Methods to implement standard operations */

View File

@@ -1,4 +1,5 @@
/* $Id: vector.h 21254 2009-06-30 00:42:17Z campbellbarton $
/*
* $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -35,14 +36,8 @@
extern PyTypeObject vector_Type;
#define VectorObject_Check(_v) PyObject_TypeCheck((_v), &vector_Type)
typedef struct { /* keep aligned with BaseMathObject in Mathutils.h */
PyObject_VAR_HEAD
float *vec; /*1D array of data (alias), wrapped status depends on wrapped status */
PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
unsigned char wrapped; /* wrapped data type? */
/* end BaseMathObject */
typedef struct {
BASE_MATH_MEMBERS(vec)
unsigned char size; /* vec size 2,3 or 4 */
} VectorObject;