Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCampbell Barton <ideasman42@gmail.com>2019-04-17 07:17:24 +0300
committerCampbell Barton <ideasman42@gmail.com>2019-04-17 07:21:24 +0300
commite12c08e8d170b7ca40f204a5b0423c23a9fbc2c1 (patch)
tree8cf3453d12edb177a218ef8009357518ec6cab6a /source/blender/python
parentb3dabc200a4b0399ec6b81f2ff2730d07b44fcaa (diff)
ClangFormat: apply to source, most of intern
Apply clang format as proposed in T53211. For details on usage and instructions for migrating branches without conflicts, see: https://wiki.blender.org/wiki/Tools/ClangFormat
Diffstat (limited to 'source/blender/python')
-rw-r--r--source/blender/python/BPY_extern.h120
-rw-r--r--source/blender/python/BPY_extern_clog.h3
-rw-r--r--source/blender/python/bmesh/CMakeLists.txt60
-rw-r--r--source/blender/python/bmesh/bmesh_py_api.c249
-rw-r--r--source/blender/python/bmesh/bmesh_py_geometry.c88
-rw-r--r--source/blender/python/bmesh/bmesh_py_ops.c533
-rw-r--r--source/blender/python/bmesh/bmesh_py_ops_call.c1476
-rw-r--r--source/blender/python/bmesh/bmesh_py_ops_call.h5
-rw-r--r--source/blender/python/bmesh/bmesh_py_types.c6227
-rw-r--r--source/blender/python/bmesh/bmesh_py_types.h194
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_customdata.c1736
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_customdata.h30
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_meshdata.c766
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_meshdata.h14
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_select.c572
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_select.h14
-rw-r--r--source/blender/python/bmesh/bmesh_py_utils.c1422
-rw-r--r--source/blender/python/generic/CMakeLists.txt54
-rw-r--r--source/blender/python/generic/bgl.c4355
-rw-r--r--source/blender/python/generic/bgl.h31
-rw-r--r--source/blender/python/generic/blf_py_api.c664
-rw-r--r--source/blender/python/generic/blf_py_api.h2
-rw-r--r--source/blender/python/generic/bpy_internal_import.c500
-rw-r--r--source/blender/python/generic/bpy_internal_import.h17
-rw-r--r--source/blender/python/generic/bpy_threads.c18
-rw-r--r--source/blender/python/generic/idprop_py_api.c2671
-rw-r--r--source/blender/python/generic/idprop_py_api.h39
-rw-r--r--source/blender/python/generic/imbuf_py_api.c563
-rw-r--r--source/blender/python/generic/imbuf_py_api.h2
-rw-r--r--source/blender/python/generic/py_capi_utils.c2020
-rw-r--r--source/blender/python/generic/py_capi_utils.h120
-rw-r--r--source/blender/python/generic/python_utildefines.h29
-rw-r--r--source/blender/python/gpu/CMakeLists.txt58
-rw-r--r--source/blender/python/gpu/gpu_py_api.c133
-rw-r--r--source/blender/python/gpu/gpu_py_api.h15
-rw-r--r--source/blender/python/gpu/gpu_py_batch.c423
-rw-r--r--source/blender/python/gpu/gpu_py_batch.h12
-rw-r--r--source/blender/python/gpu/gpu_py_element.c322
-rw-r--r--source/blender/python/gpu/gpu_py_element.h5
-rw-r--r--source/blender/python/gpu/gpu_py_matrix.c681
-rw-r--r--source/blender/python/gpu/gpu_py_matrix.h2
-rw-r--r--source/blender/python/gpu/gpu_py_offscreen.c455
-rw-r--r--source/blender/python/gpu/gpu_py_offscreen.h7
-rw-r--r--source/blender/python/gpu/gpu_py_select.c49
-rw-r--r--source/blender/python/gpu/gpu_py_select.h2
-rw-r--r--source/blender/python/gpu/gpu_py_shader.c1218
-rw-r--r--source/blender/python/gpu/gpu_py_shader.h7
-rw-r--r--source/blender/python/gpu/gpu_py_types.c66
-rw-r--r--source/blender/python/gpu/gpu_py_vertex_buffer.c478
-rw-r--r--source/blender/python/gpu/gpu_py_vertex_buffer.h8
-rw-r--r--source/blender/python/gpu/gpu_py_vertex_format.c316
-rw-r--r--source/blender/python/gpu/gpu_py_vertex_format.h5
-rw-r--r--source/blender/python/intern/CMakeLists.txt322
-rw-r--r--source/blender/python/intern/bpy.c565
-rw-r--r--source/blender/python/intern/bpy.h2
-rw-r--r--source/blender/python/intern/bpy_app.c684
-rw-r--r--source/blender/python/intern/bpy_app.h2
-rw-r--r--source/blender/python/intern/bpy_app_alembic.c79
-rw-r--r--source/blender/python/intern/bpy_app_alembic.h2
-rw-r--r--source/blender/python/intern/bpy_app_build_options.c232
-rw-r--r--source/blender/python/intern/bpy_app_build_options.h2
-rw-r--r--source/blender/python/intern/bpy_app_ffmpeg.c131
-rw-r--r--source/blender/python/intern/bpy_app_ffmpeg.h2
-rw-r--r--source/blender/python/intern/bpy_app_handlers.c475
-rw-r--r--source/blender/python/intern/bpy_app_icons.c244
-rw-r--r--source/blender/python/intern/bpy_app_ocio.c82
-rw-r--r--source/blender/python/intern/bpy_app_ocio.h2
-rw-r--r--source/blender/python/intern/bpy_app_oiio.c81
-rw-r--r--source/blender/python/intern/bpy_app_oiio.h2
-rw-r--r--source/blender/python/intern/bpy_app_opensubdiv.c80
-rw-r--r--source/blender/python/intern/bpy_app_opensubdiv.h2
-rw-r--r--source/blender/python/intern/bpy_app_openvdb.c80
-rw-r--r--source/blender/python/intern/bpy_app_openvdb.h2
-rw-r--r--source/blender/python/intern/bpy_app_sdl.c130
-rw-r--r--source/blender/python/intern/bpy_app_sdl.h2
-rw-r--r--source/blender/python/intern/bpy_app_timers.c238
-rw-r--r--source/blender/python/intern/bpy_app_translations.c1247
-rw-r--r--source/blender/python/intern/bpy_app_translations.h2
-rw-r--r--source/blender/python/intern/bpy_capi_utils.c172
-rw-r--r--source/blender/python/intern/bpy_capi_utils.h11
-rw-r--r--source/blender/python/intern/bpy_driver.c924
-rw-r--r--source/blender/python/intern/bpy_driver.h2
-rw-r--r--source/blender/python/intern/bpy_gizmo_wrap.c266
-rw-r--r--source/blender/python/intern/bpy_gizmo_wrap.h2
-rw-r--r--source/blender/python/intern/bpy_interface.c1299
-rw-r--r--source/blender/python/intern/bpy_interface_atexit.c73
-rw-r--r--source/blender/python/intern/bpy_intern_string.c49
-rw-r--r--source/blender/python/intern/bpy_intern_string.h2
-rw-r--r--source/blender/python/intern/bpy_library.h2
-rw-r--r--source/blender/python/intern/bpy_library_load.c740
-rw-r--r--source/blender/python/intern/bpy_library_write.c309
-rw-r--r--source/blender/python/intern/bpy_msgbus.c589
-rw-r--r--source/blender/python/intern/bpy_msgbus.h2
-rw-r--r--source/blender/python/intern/bpy_operator.c676
-rw-r--r--source/blender/python/intern/bpy_operator.h4
-rw-r--r--source/blender/python/intern/bpy_operator_wrap.c283
-rw-r--r--source/blender/python/intern/bpy_path.c30
-rw-r--r--source/blender/python/intern/bpy_path.h1
-rw-r--r--source/blender/python/intern/bpy_props.c5644
-rw-r--r--source/blender/python/intern/bpy_props.h1
-rw-r--r--source/blender/python/intern/bpy_rna.c14186
-rw-r--r--source/blender/python/intern/bpy_rna.h170
-rw-r--r--source/blender/python/intern/bpy_rna_anim.c1050
-rw-r--r--source/blender/python/intern/bpy_rna_anim.h2
-rw-r--r--source/blender/python/intern/bpy_rna_array.c1650
-rw-r--r--source/blender/python/intern/bpy_rna_callback.c706
-rw-r--r--source/blender/python/intern/bpy_rna_callback.h2
-rw-r--r--source/blender/python/intern/bpy_rna_driver.c102
-rw-r--r--source/blender/python/intern/bpy_rna_driver.h5
-rw-r--r--source/blender/python/intern/bpy_rna_gizmo.c864
-rw-r--r--source/blender/python/intern/bpy_rna_gizmo.h2
-rw-r--r--source/blender/python/intern/bpy_rna_id_collection.c577
-rw-r--r--source/blender/python/intern/bpy_rna_id_collection.h2
-rw-r--r--source/blender/python/intern/bpy_traceback.c279
-rw-r--r--source/blender/python/intern/bpy_traceback.h3
-rw-r--r--source/blender/python/intern/bpy_utils_previews.c207
-rw-r--r--source/blender/python/intern/bpy_utils_units.c481
-rw-r--r--source/blender/python/intern/bpy_utils_units.h2
-rw-r--r--source/blender/python/intern/stubs.c19
-rw-r--r--source/blender/python/mathutils/CMakeLists.txt64
-rw-r--r--source/blender/python/mathutils/mathutils.c941
-rw-r--r--source/blender/python/mathutils/mathutils.h121
-rw-r--r--source/blender/python/mathutils/mathutils_Color.c1520
-rw-r--r--source/blender/python/mathutils/mathutils_Color.h22
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.c1224
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.h28
-rw-r--r--source/blender/python/mathutils/mathutils_Matrix.c5371
-rw-r--r--source/blender/python/mathutils/mathutils_Matrix.h48
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.c2382
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.h22
-rw-r--r--source/blender/python/mathutils/mathutils_Vector.c5250
-rw-r--r--source/blender/python/mathutils/mathutils_Vector.h40
-rw-r--r--source/blender/python/mathutils/mathutils_bvhtree.c2117
-rw-r--r--source/blender/python/mathutils/mathutils_bvhtree.h5
-rw-r--r--source/blender/python/mathutils/mathutils_geometry.c2702
-rw-r--r--source/blender/python/mathutils/mathutils_interpolate.c152
-rw-r--r--source/blender/python/mathutils/mathutils_kdtree.c668
-rw-r--r--source/blender/python/mathutils/mathutils_kdtree.h1
-rw-r--r--source/blender/python/mathutils/mathutils_noise.c1687
139 files changed, 45457 insertions, 43846 deletions
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index d04f4bd9025..11c06f6191e 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -18,20 +18,18 @@
* \ingroup python
*/
-
-
#ifndef __BPY_EXTERN_H__
#define __BPY_EXTERN_H__
struct ChannelDriver; /* DNA_anim_types.h */
-struct ID; /* DNA_ID.h */
-struct ListBase; /* DNA_listBase.h */
-struct Object; /* DNA_object_types.h */
+struct ID; /* DNA_ID.h */
+struct ListBase; /* DNA_listBase.h */
+struct Object; /* DNA_object_types.h */
struct PathResolvedRNA;
struct ReportList;
-struct Text; /* defined in DNA_text_types.h */
-struct bConstraint; /* DNA_constraint_types.h */
-struct bConstraintOb; /* DNA_constraint_types.h */
+struct Text; /* defined in DNA_text_types.h */
+struct bConstraint; /* DNA_constraint_types.h */
+struct bConstraintOb; /* DNA_constraint_types.h */
struct bConstraintTarget; /* DNA_constraint_types.h*/
struct bContext;
struct bContextDataResult;
@@ -41,18 +39,19 @@ struct bPythonConstraint; /* DNA_constraint_types.h */
extern "C" {
#endif
-void BPY_pyconstraint_exec(struct bPythonConstraint *con, struct bConstraintOb *cob, struct ListBase *targets);
-// void BPY_pyconstraint_settings(void *arg1, void *arg2);
+void BPY_pyconstraint_exec(struct bPythonConstraint *con,
+ struct bConstraintOb *cob,
+ struct ListBase *targets);
+// void BPY_pyconstraint_settings(void *arg1, void *arg2);
void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct);
void BPY_pyconstraint_update(struct Object *owner, struct bConstraint *con);
int BPY_is_pyconstraint(struct Text *text);
-// void BPY_free_pyconstraint_links(struct Text *text);
+// void BPY_free_pyconstraint_links(struct Text *text);
void BPY_python_start(int argc, const char **argv);
void BPY_python_end(void);
void BPY_python_reset(struct bContext *C);
-
/* global interpreter lock */
typedef void *BPy_ThreadStatePtr;
@@ -61,38 +60,67 @@ BPy_ThreadStatePtr BPY_thread_save(void);
void BPY_thread_restore(BPy_ThreadStatePtr tstate);
/* our own wrappers to Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS */
-#define BPy_BEGIN_ALLOW_THREADS { BPy_ThreadStatePtr _bpy_saved_tstate = BPY_thread_save(); (void)0
-#define BPy_END_ALLOW_THREADS BPY_thread_restore(_bpy_saved_tstate); } (void)0
-
-bool BPY_execute_filepath(struct bContext *C, const char *filepath, struct ReportList *reports);
-bool BPY_execute_text(struct bContext *C, struct Text *text, struct ReportList *reports, const bool do_jump);
-
-bool BPY_execute_string_as_number(struct bContext *C, const char *imports[], const char *expr, const bool verbose, double *r_value);
-bool BPY_execute_string_as_intptr(struct bContext *C, const char *imports[], const char *expr, const bool verbose, intptr_t *r_value);
-bool BPY_execute_string_as_string(struct bContext *C, const char *imports[], const char *expr, const bool verbose, char **r_value);
-
-bool BPY_execute_string_ex(struct bContext *C, const char *imports[], const char *expr, bool use_eval);
-bool BPY_execute_string(struct bContext *C, const char *imports[], const char *expr);
-
-void BPY_text_free_code(struct Text *text);
-void BPY_modules_update(struct bContext *C); // XXX - annoying, need this for pointers that get out of date
-void BPY_modules_load_user(struct bContext *C);
-
-void BPY_app_handlers_reset(const short do_all);
-
-void BPY_driver_reset(void);
-float BPY_driver_exec(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver,
- struct ChannelDriver *driver_orig, const float evaltime);
-
-void BPY_DECREF(void *pyob_ptr); /* Py_DECREF() */
-void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr);
-int BPY_context_member_get(struct bContext *C, const char *member, struct bContextDataResult *result);
-void BPY_context_set(struct bContext *C);
-void BPY_context_update(struct bContext *C);
-
-void BPY_id_release(struct ID *id);
-
-bool BPY_string_is_keyword(const char *str);
+#define BPy_BEGIN_ALLOW_THREADS \
+ { \
+ BPy_ThreadStatePtr _bpy_saved_tstate = BPY_thread_save(); \
+ (void)0
+#define BPy_END_ALLOW_THREADS \
+ BPY_thread_restore(_bpy_saved_tstate); \
+ } \
+ (void)0
+
+bool BPY_execute_filepath(struct bContext *C, const char *filepath, struct ReportList *reports);
+bool BPY_execute_text(struct bContext *C,
+ struct Text *text,
+ struct ReportList *reports,
+ const bool do_jump);
+
+bool BPY_execute_string_as_number(struct bContext *C,
+ const char *imports[],
+ const char *expr,
+ const bool verbose,
+ double *r_value);
+bool BPY_execute_string_as_intptr(struct bContext *C,
+ const char *imports[],
+ const char *expr,
+ const bool verbose,
+ intptr_t *r_value);
+bool BPY_execute_string_as_string(struct bContext *C,
+ const char *imports[],
+ const char *expr,
+ const bool verbose,
+ char **r_value);
+
+bool BPY_execute_string_ex(struct bContext *C,
+ const char *imports[],
+ const char *expr,
+ bool use_eval);
+bool BPY_execute_string(struct bContext *C, const char *imports[], const char *expr);
+
+void BPY_text_free_code(struct Text *text);
+void BPY_modules_update(
+ struct bContext *C); // XXX - annoying, need this for pointers that get out of date
+void BPY_modules_load_user(struct bContext *C);
+
+void BPY_app_handlers_reset(const short do_all);
+
+void BPY_driver_reset(void);
+float BPY_driver_exec(struct PathResolvedRNA *anim_rna,
+ struct ChannelDriver *driver,
+ struct ChannelDriver *driver_orig,
+ const float evaltime);
+
+void BPY_DECREF(void *pyob_ptr); /* Py_DECREF() */
+void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr);
+int BPY_context_member_get(struct bContext *C,
+ const char *member,
+ struct bContextDataResult *result);
+void BPY_context_set(struct bContext *C);
+void BPY_context_update(struct bContext *C);
+
+void BPY_id_release(struct ID *id);
+
+bool BPY_string_is_keyword(const char *str);
/* I18n for addons */
#ifdef WITH_INTERNATIONAL
@@ -100,7 +128,7 @@ const char *BPY_app_translations_py_pgettext(const char *msgctxt, const char *ms
#endif
#ifdef __cplusplus
-} /* extern "C" */
+} /* extern "C" */
#endif
-#endif /* __BPY_EXTERN_H__ */
+#endif /* __BPY_EXTERN_H__ */
diff --git a/source/blender/python/BPY_extern_clog.h b/source/blender/python/BPY_extern_clog.h
index c5ff8461888..d610dc1c7ba 100644
--- a/source/blender/python/BPY_extern_clog.h
+++ b/source/blender/python/BPY_extern_clog.h
@@ -23,9 +23,8 @@
#ifndef __BPY_EXTERN_CLOG_H__
#define __BPY_EXTERN_CLOG_H__
-
/* bpy_interface.c */
extern struct CLG_LogRef *BPY_LOG_RNA;
extern struct CLG_LogRef *BPY_LOG_CONTEXT;
-#endif /* __BPY_EXTERN_CLOG_H__ */
+#endif /* __BPY_EXTERN_CLOG_H__ */
diff --git a/source/blender/python/bmesh/CMakeLists.txt b/source/blender/python/bmesh/CMakeLists.txt
index 23ecdf4aa75..14baa08abc1 100644
--- a/source/blender/python/bmesh/CMakeLists.txt
+++ b/source/blender/python/bmesh/CMakeLists.txt
@@ -16,49 +16,49 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- .
- ../../bmesh
- ../../blenkernel
- ../../blenlib
- ../../depsgraph
- ../../makesdna
- ../../../../intern/guardedalloc
+ .
+ ../../bmesh
+ ../../blenkernel
+ ../../blenlib
+ ../../depsgraph
+ ../../makesdna
+ ../../../../intern/guardedalloc
)
set(INC_SYS
- ${PYTHON_INCLUDE_DIRS}
+ ${PYTHON_INCLUDE_DIRS}
)
set(SRC
- bmesh_py_api.c
- bmesh_py_geometry.c
- bmesh_py_ops.c
- bmesh_py_ops_call.c
- bmesh_py_types.c
- bmesh_py_types_customdata.c
- bmesh_py_types_meshdata.c
- bmesh_py_types_select.c
- bmesh_py_utils.c
+ bmesh_py_api.c
+ bmesh_py_geometry.c
+ bmesh_py_ops.c
+ bmesh_py_ops_call.c
+ bmesh_py_types.c
+ bmesh_py_types_customdata.c
+ bmesh_py_types_meshdata.c
+ bmesh_py_types_select.c
+ bmesh_py_utils.c
- bmesh_py_api.h
- bmesh_py_geometry.h
- bmesh_py_ops.h
- bmesh_py_ops_call.h
- bmesh_py_types.h
- bmesh_py_types_customdata.h
- bmesh_py_types_meshdata.h
- bmesh_py_types_select.h
- bmesh_py_utils.h
+ bmesh_py_api.h
+ bmesh_py_geometry.h
+ bmesh_py_ops.h
+ bmesh_py_ops_call.h
+ bmesh_py_types.h
+ bmesh_py_types_customdata.h
+ bmesh_py_types_meshdata.h
+ bmesh_py_types_select.h
+ bmesh_py_utils.h
)
set(LIB
- bf_blenkernel
- bf_blenlib
- bf_python_mathutils
+ bf_blenkernel
+ bf_blenlib
+ bf_python_mathutils
)
if(WITH_FREESTYLE)
- add_definitions(-DWITH_FREESTYLE)
+ add_definitions(-DWITH_FREESTYLE)
endif()
blender_add_lib(bf_python_bmesh "${SRC}" "${INC}" "${INC_SYS}" "${LIB}")
diff --git a/source/blender/python/bmesh/bmesh_py_api.c b/source/blender/python/bmesh/bmesh_py_api.c
index ef3e72bfbad..8ab5e7adea7 100644
--- a/source/blender/python/bmesh/bmesh_py_api.c
+++ b/source/blender/python/bmesh/bmesh_py_api.c
@@ -47,167 +47,168 @@
#include "bmesh_py_api.h" /* own include */
PyDoc_STRVAR(bpy_bm_new_doc,
-".. method:: new(use_operators=True)\n"
-"\n"
-" :arg use_operators: Support calling operators in :mod:`bmesh.ops` (uses some extra memory per vert/edge/face).\n"
-" :type use_operators: bool\n"
-" :return: Return a new, empty BMesh.\n"
-" :rtype: :class:`bmesh.types.BMesh`\n"
-);
+ ".. method:: new(use_operators=True)\n"
+ "\n"
+ " :arg use_operators: Support calling operators in :mod:`bmesh.ops` (uses some "
+ "extra memory per vert/edge/face).\n"
+ " :type use_operators: bool\n"
+ " :return: Return a new, empty BMesh.\n"
+ " :rtype: :class:`bmesh.types.BMesh`\n");
static PyObject *bpy_bm_new(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"use_operators", NULL};
- BMesh *bm;
+ static const char *kwlist[] = {"use_operators", NULL};
+ BMesh *bm;
- bool use_operators = true;
+ bool use_operators = true;
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "|$O&:new", (char **)kwlist,
- PyC_ParseBool, &use_operators))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "|$O&:new", (char **)kwlist, PyC_ParseBool, &use_operators)) {
+ return NULL;
+ }
- bm = BM_mesh_create(
- &bm_mesh_allocsize_default,
- &((struct BMeshCreateParams){.use_toolflags = use_operators,}));
+ bm = BM_mesh_create(&bm_mesh_allocsize_default,
+ &((struct BMeshCreateParams){
+ .use_toolflags = use_operators,
+ }));
- return BPy_BMesh_CreatePyObject(bm, BPY_BMFLAG_NOP);
+ return BPy_BMesh_CreatePyObject(bm, BPY_BMFLAG_NOP);
}
PyDoc_STRVAR(bpy_bm_from_edit_mesh_doc,
-".. method:: from_edit_mesh(mesh)\n"
-"\n"
-" Return a BMesh from this mesh, currently the mesh must already be in editmode.\n"
-"\n"
-" :arg mesh: The editmode mesh.\n"
-" :type mesh: :class:`bpy.types.Mesh`\n"
-" :return: the BMesh associated with this mesh.\n"
-" :rtype: :class:`bmesh.types.BMesh`\n"
-);
+ ".. method:: from_edit_mesh(mesh)\n"
+ "\n"
+ " Return a BMesh from this mesh, currently the mesh must already be in editmode.\n"
+ "\n"
+ " :arg mesh: The editmode mesh.\n"
+ " :type mesh: :class:`bpy.types.Mesh`\n"
+ " :return: the BMesh associated with this mesh.\n"
+ " :rtype: :class:`bmesh.types.BMesh`\n");
static PyObject *bpy_bm_from_edit_mesh(PyObject *UNUSED(self), PyObject *value)
{
- BMesh *bm;
- Mesh *me = PyC_RNA_AsPointer(value, "Mesh");
+ BMesh *bm;
+ Mesh *me = PyC_RNA_AsPointer(value, "Mesh");
- if (me == NULL) {
- return NULL;
- }
+ if (me == NULL) {
+ return NULL;
+ }
- if (me->edit_mesh == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "The mesh must be in editmode");
- return NULL;
- }
+ if (me->edit_mesh == NULL) {
+ PyErr_SetString(PyExc_ValueError, "The mesh must be in editmode");
+ return NULL;
+ }
- bm = me->edit_mesh->bm;
+ bm = me->edit_mesh->bm;
- return BPy_BMesh_CreatePyObject(bm, BPY_BMFLAG_IS_WRAPPED);
+ return BPy_BMesh_CreatePyObject(bm, BPY_BMFLAG_IS_WRAPPED);
}
PyDoc_STRVAR(bpy_bm_update_edit_mesh_doc,
-".. method:: update_edit_mesh(mesh, loop_triangles=True, destructive=True)\n"
-"\n"
-" Update the mesh after changes to the BMesh in editmode,\n"
-" optionally recalculating n-gon tessellation.\n"
-"\n"
-" :arg mesh: The editmode mesh.\n"
-" :type mesh: :class:`bpy.types.Mesh`\n"
-" :arg loop_triangles: Option to recalculate n-gon tessellation.\n"
-" :type loop_triangles: boolean\n"
-" :arg destructive: Use when geometry has been added or removed.\n"
-" :type destructive: boolean\n"
-);
+ ".. method:: update_edit_mesh(mesh, loop_triangles=True, destructive=True)\n"
+ "\n"
+ " Update the mesh after changes to the BMesh in editmode,\n"
+ " optionally recalculating n-gon tessellation.\n"
+ "\n"
+ " :arg mesh: The editmode mesh.\n"
+ " :type mesh: :class:`bpy.types.Mesh`\n"
+ " :arg loop_triangles: Option to recalculate n-gon tessellation.\n"
+ " :type loop_triangles: boolean\n"
+ " :arg destructive: Use when geometry has been added or removed.\n"
+ " :type destructive: boolean\n");
static PyObject *bpy_bm_update_edit_mesh(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"mesh", "loop_triangles", "destructive", NULL};
- PyObject *py_me;
- Mesh *me;
- bool do_loop_triangles = true;
- bool is_destructive = true;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "O|O&O&:update_edit_mesh", (char **)kwlist,
- &py_me,
- PyC_ParseBool, &do_loop_triangles,
- PyC_ParseBool, &is_destructive))
- {
- return NULL;
- }
-
- me = PyC_RNA_AsPointer(py_me, "Mesh");
-
- if (me == NULL) {
- return NULL;
- }
-
- if (me->edit_mesh == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "The mesh must be in editmode");
- return NULL;
- }
-
- {
- extern void EDBM_update_generic(BMEditMesh *em, const bool do_tessface, const bool is_destructive);
-
- EDBM_update_generic(me->edit_mesh, do_loop_triangles, is_destructive);
- }
-
- Py_RETURN_NONE;
+ static const char *kwlist[] = {"mesh", "loop_triangles", "destructive", NULL};
+ PyObject *py_me;
+ Mesh *me;
+ bool do_loop_triangles = true;
+ bool is_destructive = true;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O|O&O&:update_edit_mesh",
+ (char **)kwlist,
+ &py_me,
+ PyC_ParseBool,
+ &do_loop_triangles,
+ PyC_ParseBool,
+ &is_destructive)) {
+ return NULL;
+ }
+
+ me = PyC_RNA_AsPointer(py_me, "Mesh");
+
+ if (me == NULL) {
+ return NULL;
+ }
+
+ if (me->edit_mesh == NULL) {
+ PyErr_SetString(PyExc_ValueError, "The mesh must be in editmode");
+ return NULL;
+ }
+
+ {
+ extern void EDBM_update_generic(
+ BMEditMesh * em, const bool do_tessface, const bool is_destructive);
+
+ EDBM_update_generic(me->edit_mesh, do_loop_triangles, is_destructive);
+ }
+
+ Py_RETURN_NONE;
}
static struct PyMethodDef BPy_BM_methods[] = {
- {"new", (PyCFunction)bpy_bm_new, METH_VARARGS | METH_KEYWORDS, bpy_bm_new_doc},
- {"from_edit_mesh", (PyCFunction)bpy_bm_from_edit_mesh, METH_O, bpy_bm_from_edit_mesh_doc},
- {"update_edit_mesh", (PyCFunction)bpy_bm_update_edit_mesh, METH_VARARGS | METH_KEYWORDS, bpy_bm_update_edit_mesh_doc},
- {NULL, NULL, 0, NULL},
+ {"new", (PyCFunction)bpy_bm_new, METH_VARARGS | METH_KEYWORDS, bpy_bm_new_doc},
+ {"from_edit_mesh", (PyCFunction)bpy_bm_from_edit_mesh, METH_O, bpy_bm_from_edit_mesh_doc},
+ {"update_edit_mesh",
+ (PyCFunction)bpy_bm_update_edit_mesh,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bm_update_edit_mesh_doc},
+ {NULL, NULL, 0, NULL},
};
PyDoc_STRVAR(BPy_BM_doc,
-"This module provides access to blenders bmesh data structures.\n"
-"\n"
-".. include:: include__bmesh.rst\n"
-);
+ "This module provides access to blenders bmesh data structures.\n"
+ "\n"
+ ".. include:: include__bmesh.rst\n");
static struct PyModuleDef BPy_BM_module_def = {
- PyModuleDef_HEAD_INIT,
- "bmesh", /* m_name */
- BPy_BM_doc, /* m_doc */
- 0, /* m_size */
- BPy_BM_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bmesh", /* m_name */
+ BPy_BM_doc, /* m_doc */
+ 0, /* m_size */
+ BPy_BM_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit_bmesh(void)
{
- PyObject *mod;
- PyObject *submodule;
- PyObject *sys_modules = PyImport_GetModuleDict();
+ PyObject *mod;
+ PyObject *submodule;
+ PyObject *sys_modules = PyImport_GetModuleDict();
- BPy_BM_init_types();
- BPy_BM_init_types_select();
- BPy_BM_init_types_customdata();
- BPy_BM_init_types_meshdata();
+ BPy_BM_init_types();
+ BPy_BM_init_types_select();
+ BPy_BM_init_types_customdata();
+ BPy_BM_init_types_meshdata();
- mod = PyModule_Create(&BPy_BM_module_def);
+ mod = PyModule_Create(&BPy_BM_module_def);
- /* bmesh.types */
- PyModule_AddObject(mod, "types", (submodule = BPyInit_bmesh_types()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ /* bmesh.types */
+ PyModule_AddObject(mod, "types", (submodule = BPyInit_bmesh_types()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- /* bmesh.ops (not a real module, exposes module like access). */
- PyModule_AddObject(mod, "ops", (submodule = BPyInit_bmesh_ops()));
- /* PyDict_SetItemString(sys_modules, PyModule_GetNameObject(submodule), submodule); */
- PyDict_SetItemString(sys_modules, "bmesh.ops", submodule); /* fake module */
+ /* bmesh.ops (not a real module, exposes module like access). */
+ PyModule_AddObject(mod, "ops", (submodule = BPyInit_bmesh_ops()));
+ /* PyDict_SetItemString(sys_modules, PyModule_GetNameObject(submodule), submodule); */
+ PyDict_SetItemString(sys_modules, "bmesh.ops", submodule); /* fake module */
- PyModule_AddObject(mod, "utils", (submodule = BPyInit_bmesh_utils()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "utils", (submodule = BPyInit_bmesh_utils()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- PyModule_AddObject(mod, "geometry", (submodule = BPyInit_bmesh_geometry()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "geometry", (submodule = BPyInit_bmesh_geometry()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- return mod;
+ return mod;
}
diff --git a/source/blender/python/bmesh/bmesh_py_geometry.c b/source/blender/python/bmesh/bmesh_py_geometry.c
index 30265af1e9f..2429d2a4888 100644
--- a/source/blender/python/bmesh/bmesh_py_geometry.c
+++ b/source/blender/python/bmesh/bmesh_py_geometry.c
@@ -35,70 +35,64 @@
#include "bmesh_py_geometry.h" /* own include */
PyDoc_STRVAR(bpy_bm_geometry_intersect_face_point_doc,
-".. method:: intersect_face_point(face, point)\n"
-"\n"
-" Tests if the projection of a point is inside a face (using the face's normal).\n"
-"\n"
-" :arg face: The face to test.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-" :arg point: The point to test.\n"
-" :type point: float triplet\n"
-" :return: True when the projection of the point is in the face.\n"
-" :rtype: bool\n"
-);
+ ".. method:: intersect_face_point(face, point)\n"
+ "\n"
+ " Tests if the projection of a point is inside a face (using the face's normal).\n"
+ "\n"
+ " :arg face: The face to test.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n"
+ " :arg point: The point to test.\n"
+ " :type point: float triplet\n"
+ " :return: True when the projection of the point is in the face.\n"
+ " :rtype: bool\n");
static PyObject *bpy_bm_geometry_intersect_face_point(BPy_BMFace *UNUSED(self), PyObject *args)
{
- BPy_BMFace *py_face;
- PyObject *py_point;
- float point[3];
- bool ret;
+ BPy_BMFace *py_face;
+ PyObject *py_point;
+ float point[3];
+ bool ret;
- if (!PyArg_ParseTuple(args,
- "O!O:intersect_face_point",
- &BPy_BMFace_Type, &py_face,
- &py_point))
- {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O!O:intersect_face_point", &BPy_BMFace_Type, &py_face, &py_point)) {
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(py_face);
- if (mathutils_array_parse(point, 3, 3, py_point, "intersect_face_point") == -1) {
- return NULL;
- }
+ BPY_BM_CHECK_OBJ(py_face);
+ if (mathutils_array_parse(point, 3, 3, py_point, "intersect_face_point") == -1) {
+ return NULL;
+ }
- ret = BM_face_point_inside_test(py_face->f, point);
+ ret = BM_face_point_inside_test(py_face->f, point);
- return PyBool_FromLong(ret);
+ return PyBool_FromLong(ret);
}
-
static struct PyMethodDef BPy_BM_geometry_methods[] = {
- {"intersect_face_point", (PyCFunction)bpy_bm_geometry_intersect_face_point, METH_VARARGS, bpy_bm_geometry_intersect_face_point_doc},
- {NULL, NULL, 0, NULL},
+ {"intersect_face_point",
+ (PyCFunction)bpy_bm_geometry_intersect_face_point,
+ METH_VARARGS,
+ bpy_bm_geometry_intersect_face_point_doc},
+ {NULL, NULL, 0, NULL},
};
-
PyDoc_STRVAR(BPy_BM_utils_doc,
-"This module provides access to bmesh geometry evaluation functions."
-);
+ "This module provides access to bmesh geometry evaluation functions.");
static struct PyModuleDef BPy_BM_geometry_module_def = {
- PyModuleDef_HEAD_INIT,
- "bmesh.geometry", /* m_name */
- BPy_BM_utils_doc, /* m_doc */
- 0, /* m_size */
- BPy_BM_geometry_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bmesh.geometry", /* m_name */
+ BPy_BM_utils_doc, /* m_doc */
+ 0, /* m_size */
+ BPy_BM_geometry_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
-
PyObject *BPyInit_bmesh_geometry(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPy_BM_geometry_module_def);
+ submodule = PyModule_Create(&BPy_BM_geometry_module_def);
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/bmesh/bmesh_py_ops.c b/source/blender/python/bmesh/bmesh_py_ops.c
index fe82f22ec8c..fd37c8521c1 100644
--- a/source/blender/python/bmesh/bmesh_py_ops.c
+++ b/source/blender/python/bmesh/bmesh_py_ops.c
@@ -31,11 +31,10 @@
#include "MEM_guardedalloc.h"
-
#include "bmesh.h"
#include "bmesh_py_ops_call.h"
-#include "bmesh_py_ops.h" /* own include */
+#include "bmesh_py_ops.h" /* own include */
/* bmesh operator 'bmesh.ops.*' callable types
* ******************************************* */
@@ -43,327 +42,337 @@ static PyTypeObject bmesh_op_Type;
static PyObject *bpy_bmesh_op_CreatePyObject(const char *opname)
{
- BPy_BMeshOpFunc *self = PyObject_New(BPy_BMeshOpFunc, &bmesh_op_Type);
+ BPy_BMeshOpFunc *self = PyObject_New(BPy_BMeshOpFunc, &bmesh_op_Type);
- self->opname = opname;
+ self->opname = opname;
- return (PyObject *)self;
+ return (PyObject *)self;
}
static PyObject *bpy_bmesh_op_repr(BPy_BMeshOpFunc *self)
{
- return PyUnicode_FromFormat("<%.200s bmesh.ops.%.200s()>",
- Py_TYPE(self)->tp_name,
- self->opname);
+ return PyUnicode_FromFormat("<%.200s bmesh.ops.%.200s()>", Py_TYPE(self)->tp_name, self->opname);
}
-
/* methods
* ======= */
-
/* __doc__
* ------- */
static char *bmp_slots_as_args(const BMOSlotType slot_types[BMO_OP_MAX_SLOTS], const bool is_out)
{
- DynStr *dyn_str = BLI_dynstr_new();
- char *ret;
- bool quoted;
- bool set;
-
- int i = 0;
-
- while (*slot_types[i].name) {
- quoted = false;
- set = false;
- /* cut off '.out' by using a string size arg */
- const int name_len = is_out ?
- (strchr(slot_types[i].name, '.') - slot_types[i].name) :
- sizeof(slot_types[i].name);
- const char *value = "<Unknown>";
- switch (slot_types[i].type) {
- case BMO_OP_SLOT_BOOL: value = "False"; break;
- case BMO_OP_SLOT_INT:
- if (slot_types[i].subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_ENUM) {
- value = slot_types[i].enum_flags[0].identifier;
- quoted = true;
- }
- else if (slot_types[i].subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_FLAG) {
- value = "";
- set = true;
- }
- else {
- value = "0";
- }
- break;
- case BMO_OP_SLOT_FLT: value = "0.0"; break;
- case BMO_OP_SLOT_PTR: value = "None"; break;
- case BMO_OP_SLOT_MAT: value = "Matrix()"; break;
- case BMO_OP_SLOT_VEC: value = "Vector()"; break;
- case BMO_OP_SLOT_ELEMENT_BUF: value =
- (slot_types[i].subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) ? "None" : "[]"; break;
- case BMO_OP_SLOT_MAPPING: value = "{}"; break;
- }
- BLI_dynstr_appendf(
- dyn_str, i ? ", %.*s=%s%s%s%s%s" : "%.*s=%s%s%s%s%s",
- name_len, slot_types[i].name,
- set ? "{" : "", quoted ? "'" : "",
- value,
- quoted ? "'" : "", set ? "}" : "");
- i++;
- }
-
- ret = BLI_dynstr_get_cstring(dyn_str);
- BLI_dynstr_free(dyn_str);
- return ret;
+ DynStr *dyn_str = BLI_dynstr_new();
+ char *ret;
+ bool quoted;
+ bool set;
+
+ int i = 0;
+
+ while (*slot_types[i].name) {
+ quoted = false;
+ set = false;
+ /* cut off '.out' by using a string size arg */
+ const int name_len = is_out ? (strchr(slot_types[i].name, '.') - slot_types[i].name) :
+ sizeof(slot_types[i].name);
+ const char *value = "<Unknown>";
+ switch (slot_types[i].type) {
+ case BMO_OP_SLOT_BOOL:
+ value = "False";
+ break;
+ case BMO_OP_SLOT_INT:
+ if (slot_types[i].subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_ENUM) {
+ value = slot_types[i].enum_flags[0].identifier;
+ quoted = true;
+ }
+ else if (slot_types[i].subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_FLAG) {
+ value = "";
+ set = true;
+ }
+ else {
+ value = "0";
+ }
+ break;
+ case BMO_OP_SLOT_FLT:
+ value = "0.0";
+ break;
+ case BMO_OP_SLOT_PTR:
+ value = "None";
+ break;
+ case BMO_OP_SLOT_MAT:
+ value = "Matrix()";
+ break;
+ case BMO_OP_SLOT_VEC:
+ value = "Vector()";
+ break;
+ case BMO_OP_SLOT_ELEMENT_BUF:
+ value = (slot_types[i].subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) ? "None" : "[]";
+ break;
+ case BMO_OP_SLOT_MAPPING:
+ value = "{}";
+ break;
+ }
+ BLI_dynstr_appendf(dyn_str,
+ i ? ", %.*s=%s%s%s%s%s" : "%.*s=%s%s%s%s%s",
+ name_len,
+ slot_types[i].name,
+ set ? "{" : "",
+ quoted ? "'" : "",
+ value,
+ quoted ? "'" : "",
+ set ? "}" : "");
+ i++;
+ }
+
+ ret = BLI_dynstr_get_cstring(dyn_str);
+ BLI_dynstr_free(dyn_str);
+ return ret;
}
static PyObject *bpy_bmesh_op_doc_get(BPy_BMeshOpFunc *self, void *UNUSED(closure))
{
- PyObject *ret;
- char *slot_in;
- char *slot_out;
- int i;
+ PyObject *ret;
+ char *slot_in;
+ char *slot_out;
+ int i;
- i = BMO_opcode_from_opname(self->opname);
+ i = BMO_opcode_from_opname(self->opname);
- slot_in = bmp_slots_as_args(bmo_opdefines[i]->slot_types_in, false);
- slot_out = bmp_slots_as_args(bmo_opdefines[i]->slot_types_out, true);
+ slot_in = bmp_slots_as_args(bmo_opdefines[i]->slot_types_in, false);
+ slot_out = bmp_slots_as_args(bmo_opdefines[i]->slot_types_out, true);
- ret = PyUnicode_FromFormat("%.200s bmesh.ops.%.200s(bmesh, %s)\n -> dict(%s)",
- Py_TYPE(self)->tp_name,
- self->opname, slot_in, slot_out);
+ ret = PyUnicode_FromFormat("%.200s bmesh.ops.%.200s(bmesh, %s)\n -> dict(%s)",
+ Py_TYPE(self)->tp_name,
+ self->opname,
+ slot_in,
+ slot_out);
- MEM_freeN(slot_in);
- MEM_freeN(slot_out);
+ MEM_freeN(slot_in);
+ MEM_freeN(slot_out);
- return ret;
+ return ret;
}
static PyGetSetDef bpy_bmesh_op_getseters[] = {
- {(char *)"__doc__", (getter)bpy_bmesh_op_doc_get, (setter)NULL, NULL, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"__doc__", (getter)bpy_bmesh_op_doc_get, (setter)NULL, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
/* Types
* ===== */
static PyTypeObject bmesh_op_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BMeshOpFunc", /* tp_name */
- sizeof(BPy_BMeshOpFunc), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- (reprfunc) bpy_bmesh_op_repr, /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- (ternaryfunc)BPy_BMO_call, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0,
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- NULL, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- bpy_bmesh_op_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0) "BMeshOpFunc", /* tp_name */
+ sizeof(BPy_BMeshOpFunc), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ NULL, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ (reprfunc)bpy_bmesh_op_repr, /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ (ternaryfunc)BPy_BMO_call, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+ /* will only use these if this is a subtype of a py class */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ NULL, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ bpy_bmesh_op_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
-
/* bmesh fake module 'bmesh.ops'
* ***************************** */
static PyObject *bpy_bmesh_ops_fakemod_getattro(PyObject *UNUSED(self), PyObject *pyname)
{
- const char *opname = _PyUnicode_AsString(pyname);
-
- if (BMO_opcode_from_opname(opname) != -1) {
- return bpy_bmesh_op_CreatePyObject(opname);
- }
- else {
- PyErr_Format(PyExc_AttributeError,
- "BMeshOpsModule: operator \"%.200s\" doesn't exist",
- opname);
- return NULL;
- }
+ const char *opname = _PyUnicode_AsString(pyname);
+
+ if (BMO_opcode_from_opname(opname) != -1) {
+ return bpy_bmesh_op_CreatePyObject(opname);
+ }
+ else {
+ PyErr_Format(
+ PyExc_AttributeError, "BMeshOpsModule: operator \"%.200s\" doesn't exist", opname);
+ return NULL;
+ }
}
static PyObject *bpy_bmesh_ops_fakemod_dir(PyObject *UNUSED(self))
{
- const unsigned int tot = bmo_opdefines_total;
- unsigned int i;
- PyObject *ret;
+ const unsigned int tot = bmo_opdefines_total;
+ unsigned int i;
+ PyObject *ret;
- ret = PyList_New(bmo_opdefines_total);
+ ret = PyList_New(bmo_opdefines_total);
- for (i = 0; i < tot; i++) {
- PyList_SET_ITEM(ret, i, PyUnicode_FromString(bmo_opdefines[i]->opname));
- }
+ for (i = 0; i < tot; i++) {
+ PyList_SET_ITEM(ret, i, PyUnicode_FromString(bmo_opdefines[i]->opname));
+ }
- return ret;
+ return ret;
}
static struct PyMethodDef bpy_bmesh_ops_fakemod_methods[] = {
- {"__dir__", (PyCFunction)bpy_bmesh_ops_fakemod_dir, METH_NOARGS, NULL},
- {NULL, NULL, 0, NULL},
+ {"__dir__", (PyCFunction)bpy_bmesh_ops_fakemod_dir, METH_NOARGS, NULL},
+ {NULL, NULL, 0, NULL},
};
static PyTypeObject bmesh_ops_fakemod_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BMeshOpsModule", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
- bpy_bmesh_ops_fakemod_getattro, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0,
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- bpy_bmesh_ops_fakemod_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0) "BMeshOpsModule", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ NULL, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL, /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+ /* will only use these if this is a subtype of a py class */
+ bpy_bmesh_ops_fakemod_getattro, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ bpy_bmesh_ops_fakemod_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
PyObject *BPyInit_bmesh_ops(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- if (PyType_Ready(&bmesh_ops_fakemod_Type) < 0) {
- return NULL;
- }
+ if (PyType_Ready(&bmesh_ops_fakemod_Type) < 0) {
+ return NULL;
+ }
- if (PyType_Ready(&bmesh_op_Type) < 0) {
- return NULL;
- }
+ if (PyType_Ready(&bmesh_op_Type) < 0) {
+ return NULL;
+ }
- submodule = PyObject_New(PyObject, &bmesh_ops_fakemod_Type);
+ submodule = PyObject_New(PyObject, &bmesh_ops_fakemod_Type);
- /* prevent further creation of instances */
- bmesh_ops_fakemod_Type.tp_init = NULL;
- bmesh_ops_fakemod_Type.tp_new = NULL;
+ /* prevent further creation of instances */
+ bmesh_ops_fakemod_Type.tp_init = NULL;
+ bmesh_ops_fakemod_Type.tp_new = NULL;
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/bmesh/bmesh_py_ops_call.c b/source/blender/python/bmesh/bmesh_py_ops_call.c
index b9d506c4c41..401dded5188 100644
--- a/source/blender/python/bmesh/bmesh_py_ops_call.c
+++ b/source/blender/python/bmesh/bmesh_py_ops_call.c
@@ -33,7 +33,7 @@
#include "bmesh.h"
-#include "bmesh_py_ops_call.h" /* own include */
+#include "bmesh_py_ops_call.h" /* own include */
#include "bmesh_py_types.h"
@@ -44,18 +44,16 @@ BLI_STATIC_ASSERT(sizeof(PyC_FlagSet) == sizeof(BMO_FlagSet), "size mismatch");
static int bpy_bm_op_as_py_error(BMesh *bm)
{
- if (BMO_error_occurred(bm)) {
- /* note: we could have multiple errors */
- const char *errmsg;
- if (BMO_error_get(bm, &errmsg, NULL)) {
- PyErr_Format(PyExc_RuntimeError,
- "bmesh operator: %.200s",
- errmsg);
- BMO_error_clear(bm);
- return -1;
- }
- }
- return 0;
+ if (BMO_error_occurred(bm)) {
+ /* note: we could have multiple errors */
+ const char *errmsg;
+ if (BMO_error_get(bm, &errmsg, NULL)) {
+ PyErr_Format(PyExc_RuntimeError, "bmesh operator: %.200s", errmsg);
+ BMO_error_clear(bm);
+ return -1;
+ }
+ }
+ return 0;
}
/**
@@ -66,34 +64,41 @@ static int bpy_bm_op_as_py_error(BMesh *bm)
* \param htype: Test \a value matches this type.
* \param descr: Description text.
*/
-static int bpy_slot_from_py_elem_check(
- BPy_BMElem *value, BMesh *bm, const char htype,
- /* for error messages */
- const char *opname, const char *slot_name, const char *descr)
+static int bpy_slot_from_py_elem_check(BPy_BMElem *value,
+ BMesh *bm,
+ const char htype,
+ /* for error messages */
+ const char *opname,
+ const char *slot_name,
+ const char *descr)
{
- if (!BPy_BMElem_Check(value) ||
- !(value->ele->head.htype & htype))
- {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s, expected a %.200s not *.200s",
- opname, slot_name, descr,
- BPy_BMElem_StringFromHType(htype),
- Py_TYPE(value)->tp_name);
- return -1;
- }
- else if (value->bm == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s invalidated element",
- opname, slot_name, descr);
- return -1;
- }
- else if (value->bm != bm) { /* we may want to make this check optional by setting 'bm' to NULL */
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s invalidated element",
- opname, slot_name, descr);
- return -1;
- }
- return 0;
+ if (!BPy_BMElem_Check(value) || !(value->ele->head.htype & htype)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s, expected a %.200s not *.200s",
+ opname,
+ slot_name,
+ descr,
+ BPy_BMElem_StringFromHType(htype),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else if (value->bm == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s invalidated element",
+ opname,
+ slot_name,
+ descr);
+ return -1;
+ }
+ else if (value->bm != bm) { /* we may want to make this check optional by setting 'bm' to NULL */
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s invalidated element",
+ opname,
+ slot_name,
+ descr);
+ return -1;
+ }
+ return 0;
}
/**
@@ -105,434 +110,493 @@ static int bpy_slot_from_py_elem_check(
* \param htype_bmo: The type(s) supported by the target slot.
* \param descr: Description text.
*/
-static int bpy_slot_from_py_elemseq_check(
- BPy_BMGeneric *value, BMesh *bm,
- const char htype_py, const char htype_bmo,
- /* for error messages */
- const char *opname, const char *slot_name, const char *descr)
+static int bpy_slot_from_py_elemseq_check(BPy_BMGeneric *value,
+ BMesh *bm,
+ const char htype_py,
+ const char htype_bmo,
+ /* for error messages */
+ const char *opname,
+ const char *slot_name,
+ const char *descr)
{
- if (value->bm == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s, invalidated sequence",
- opname, slot_name, descr);
- return -1;
- }
- else if (value->bm != bm) { /* we may want to make this check optional by setting 'bm' to NULL */
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s, invalidated sequence",
- opname, slot_name, descr);
- return -1;
- }
- else if ((htype_py & htype_bmo) == 0) {
- char str_bmo[32];
- char str_py[32];
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" %.200s, expected "
- "a sequence of %.200s not %.200s",
- opname, slot_name, descr,
- BPy_BMElem_StringFromHType_ex(htype_bmo, str_bmo),
- BPy_BMElem_StringFromHType_ex(htype_py, str_py));
- return -1;
- }
-
- return 0;
+ if (value->bm == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s, invalidated sequence",
+ opname,
+ slot_name,
+ descr);
+ return -1;
+ }
+ else if (value->bm != bm) { /* we may want to make this check optional by setting 'bm' to NULL */
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s, invalidated sequence",
+ opname,
+ slot_name,
+ descr);
+ return -1;
+ }
+ else if ((htype_py & htype_bmo) == 0) {
+ char str_bmo[32];
+ char str_py[32];
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" %.200s, expected "
+ "a sequence of %.200s not %.200s",
+ opname,
+ slot_name,
+ descr,
+ BPy_BMElem_StringFromHType_ex(htype_bmo, str_bmo),
+ BPy_BMElem_StringFromHType_ex(htype_py, str_py));
+ return -1;
+ }
+
+ return 0;
}
/**
* Use for giving py args to an operator.
*/
-static int bpy_slot_from_py(
- BMesh *bm, BMOperator *bmop, BMOpSlot *slot, PyObject *value,
- /* the are just for exception messages */
- const char *opname, const char *slot_name)
+static int bpy_slot_from_py(BMesh *bm,
+ BMOperator *bmop,
+ BMOpSlot *slot,
+ PyObject *value,
+ /* the are just for exception messages */
+ const char *opname,
+ const char *slot_name)
{
- switch (slot->slot_type) {
- case BMO_OP_SLOT_BOOL:
- {
- const int param = PyC_Long_AsBool(value);
-
- if (param == -1) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected True/False or 0/1, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- BMO_SLOT_AS_BOOL(slot) = param;
- }
-
- break;
- }
- case BMO_OP_SLOT_INT:
- {
- if (slot->slot_subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_ENUM) {
- int enum_val = -1;
- PyC_FlagSet *items = (PyC_FlagSet *)slot->data.enum_data.flags;
- const char *enum_str = _PyUnicode_AsString(value);
-
- if (enum_str == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected a string, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
-
- if (PyC_FlagSet_ValueFromID(items, enum_str, &enum_val, slot_name) == -1) {
- return -1;
- }
-
- BMO_SLOT_AS_INT(slot) = enum_val;
- }
- else if (slot->slot_subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_FLAG) {
- int flag = 0;
- PyC_FlagSet *items = (PyC_FlagSet *)slot->data.enum_data.flags;
-
- if (PyC_FlagSet_ToBitfield(items, value, &flag, slot_name) == -1) {
- return -1;
- }
-
- BMO_SLOT_AS_INT(slot) = flag;
- }
- else {
- const int param = PyC_Long_AsI32(value);
-
- if (param == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected an int, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- BMO_SLOT_AS_INT(slot) = param;
- }
- }
- break;
- }
- case BMO_OP_SLOT_FLT:
- {
- float param = PyFloat_AsDouble(value);
- if (param == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected a float, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- BMO_SLOT_AS_FLOAT(slot) = param;
- }
- break;
- }
- case BMO_OP_SLOT_MAT:
- {
- /* XXX - BMesh operator design is crappy here, operator slot should define matrix size,
- * not the caller! */
- MatrixObject *pymat;
- if (!Matrix_ParseAny(value, &pymat)) {
- return -1;
- }
- const ushort size = pymat->num_col;
- if ((size != pymat->num_row) || (!ELEM(size, 3, 4))) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected a 3x3 or 4x4 matrix Matrix",
- opname, slot_name);
- return -1;
- }
-
- BMO_slot_mat_set(bmop, bmop->slots_in, slot_name, pymat->matrix, size);
- break;
- }
- case BMO_OP_SLOT_VEC:
- {
- /* passing slot name here is a bit non-descriptive */
- if (mathutils_array_parse(BMO_SLOT_AS_VECTOR(slot), 3, 3, value, slot_name) == -1) {
- return -1;
- }
- break;
- }
- case BMO_OP_SLOT_ELEMENT_BUF:
- {
- if (slot->slot_subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) {
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)value, bm, (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- opname, slot_name, "single element") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- BMO_slot_buffer_from_single(bmop, slot, &((BPy_BMElem *)value)->ele->head);
- }
- else {
- /* there are many ways we could interpret arguments, for now...
- * - verts/edges/faces from the mesh direct,
- * this way the operator takes every item.
- * - `TODO` a plain python sequence (list) of elements.
- * - `TODO` an iterator. eg.
- * face.verts
- * - `TODO` (type, flag) pair, eg.
- * ('VERT', {'TAG'})
- */
-
- if (BPy_BMVertSeq_Check(value)) {
- if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value, bm,
- BM_VERT, (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- opname, slot_name, "element buffer") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_VERT);
- }
- else if (BPy_BMEdgeSeq_Check(value)) {
- if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value, bm,
- BM_EDGE, (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- opname, slot_name, "element buffer") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_EDGE);
- }
- else if (BPy_BMFaceSeq_Check(value)) {
- if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value, bm,
- BM_FACE, (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- opname, slot_name, "element buffer") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
- BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_FACE);
- }
-
- else if (BPy_BMElemSeq_Check(value)) {
- BMIter iter;
- BMHeader *ele;
- int tot;
- unsigned int i;
-
- if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value, bm,
- bm_iter_itype_htype_map[((BPy_BMElemSeq *)value)->itype],
- (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- opname, slot_name, "element buffer") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- /* this will loop over all elements which is a shame but
- * we need to know this before alloc */
- /* calls bpy_bmelemseq_length() */
- tot = Py_TYPE(value)->tp_as_sequence->sq_length(value);
-
- BMO_slot_buffer_alloc(bmop, bmop->slots_in, slot_name, tot);
-
- i = 0;
- BM_ITER_BPY_BM_SEQ (ele, &iter, ((BPy_BMElemSeq *)value)) {
- slot->data.buf[i] = ele;
- i++;
- }
- }
- /* keep this last */
- else if (PySequence_Check(value)) {
- BMElem **elem_array = NULL;
- Py_ssize_t elem_array_len;
-
- elem_array = BPy_BMElem_PySeq_As_Array(&bm, value, 0, PY_SSIZE_T_MAX,
- &elem_array_len, (slot->slot_subtype.elem & BM_ALL_NOLOOP),
- true, true, slot_name);
-
- /* error is set above */
- if (elem_array == NULL) {
- return -1;
- }
-
- BMO_slot_buffer_alloc(bmop, bmop->slots_in, slot_name, elem_array_len);
- memcpy(slot->data.buf, elem_array, sizeof(void *) * elem_array_len);
- PyMem_FREE(elem_array);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a bmesh sequence, list, (htype, flag) pair, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- }
- break;
- }
- case BMO_OP_SLOT_MAPPING:
- {
- /* first check types */
- if (slot->slot_subtype.map != BMO_OP_SLOT_SUBTYPE_MAP_EMPTY) {
- if (!PyDict_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a dict, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- }
- else {
- if (!PySet_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a set, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- }
-
- switch (slot->slot_subtype.map) {
- case BMO_OP_SLOT_SUBTYPE_MAP_ELEM:
- {
- if (PyDict_Size(value) > 0) {
- PyObject *arg_key, *arg_value;
- Py_ssize_t arg_pos = 0;
- while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid key in dict") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_value, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid value in dict") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- BMO_slot_map_elem_insert(bmop, slot,
- ((BPy_BMElem *)arg_key)->ele, ((BPy_BMElem *)arg_value)->ele);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_FLT:
- {
- if (PyDict_Size(value) > 0) {
- PyObject *arg_key, *arg_value;
- Py_ssize_t arg_pos = 0;
- while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
- float value_f;
-
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid key in dict") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- value_f = PyFloat_AsDouble(arg_value);
-
- if (value_f == -1.0f && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a dict with float values, not %.200s",
- opname, slot_name, Py_TYPE(arg_value)->tp_name);
- return -1;
- }
-
- BMO_slot_map_float_insert(bmop, slot,
- ((BPy_BMElem *)arg_key)->ele, value_f);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_INT:
- {
- if (PyDict_Size(value) > 0) {
- PyObject *arg_key, *arg_value;
- Py_ssize_t arg_pos = 0;
- while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
- int value_i;
-
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid key in dict") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- value_i = PyC_Long_AsI32(arg_value);
-
- if (value_i == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a dict with int values, not %.200s",
- opname, slot_name, Py_TYPE(arg_value)->tp_name);
- return -1;
- }
-
- BMO_slot_map_int_insert(bmop, slot,
- ((BPy_BMElem *)arg_key)->ele, value_i);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_BOOL:
- {
- if (PyDict_Size(value) > 0) {
- PyObject *arg_key, *arg_value;
- Py_ssize_t arg_pos = 0;
- while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
- int value_i;
-
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid key in dict") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- value_i = PyC_Long_AsI32(arg_value);
-
- if (value_i == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected "
- "a dict with bool values, not %.200s",
- opname, slot_name, Py_TYPE(arg_value)->tp_name);
- return -1;
- }
-
- BMO_slot_map_bool_insert(bmop, slot,
- ((BPy_BMElem *)arg_key)->ele, value_i != 0);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_EMPTY:
- {
- if (PySet_Size(value) > 0) {
- PyObject *arg_key;
- Py_ssize_t arg_pos = 0;
- Py_ssize_t arg_hash = 0;
- while (_PySet_NextEntry(value, &arg_pos, &arg_key, &arg_hash)) {
-
- if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key, bm, BM_ALL_NOLOOP,
- opname, slot_name, "invalid key in set") == -1)
- {
- return -1; /* error is set in bpy_slot_from_py_elem_check() */
- }
-
- BMO_slot_map_empty_insert(bmop, slot,
- ((BPy_BMElem *)arg_key)->ele);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_INTERNAL:
- {
- /* can't convert from these */
- PyErr_Format(PyExc_NotImplementedError,
- "This arguments mapping subtype %d is not supported", slot->slot_subtype.map);
- return -1;
- }
- }
- break;
- }
- default:
- /* TODO --- many others */
- PyErr_Format(PyExc_NotImplementedError,
- "%.200s: keyword \"%.200s\" type %d not working yet!",
- opname, slot_name, slot->slot_type);
- return -1;
- }
-
- /* all is well */
- return 0;
+ switch (slot->slot_type) {
+ case BMO_OP_SLOT_BOOL: {
+ const int param = PyC_Long_AsBool(value);
+
+ if (param == -1) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected True/False or 0/1, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ BMO_SLOT_AS_BOOL(slot) = param;
+ }
+
+ break;
+ }
+ case BMO_OP_SLOT_INT: {
+ if (slot->slot_subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_ENUM) {
+ int enum_val = -1;
+ PyC_FlagSet *items = (PyC_FlagSet *)slot->data.enum_data.flags;
+ const char *enum_str = _PyUnicode_AsString(value);
+
+ if (enum_str == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected a string, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ if (PyC_FlagSet_ValueFromID(items, enum_str, &enum_val, slot_name) == -1) {
+ return -1;
+ }
+
+ BMO_SLOT_AS_INT(slot) = enum_val;
+ }
+ else if (slot->slot_subtype.intg == BMO_OP_SLOT_SUBTYPE_INT_FLAG) {
+ int flag = 0;
+ PyC_FlagSet *items = (PyC_FlagSet *)slot->data.enum_data.flags;
+
+ if (PyC_FlagSet_ToBitfield(items, value, &flag, slot_name) == -1) {
+ return -1;
+ }
+
+ BMO_SLOT_AS_INT(slot) = flag;
+ }
+ else {
+ const int param = PyC_Long_AsI32(value);
+
+ if (param == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected an int, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ BMO_SLOT_AS_INT(slot) = param;
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_FLT: {
+ float param = PyFloat_AsDouble(value);
+ if (param == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected a float, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ BMO_SLOT_AS_FLOAT(slot) = param;
+ }
+ break;
+ }
+ case BMO_OP_SLOT_MAT: {
+ /* XXX - BMesh operator design is crappy here, operator slot should define matrix size,
+ * not the caller! */
+ MatrixObject *pymat;
+ if (!Matrix_ParseAny(value, &pymat)) {
+ return -1;
+ }
+ const ushort size = pymat->num_col;
+ if ((size != pymat->num_row) || (!ELEM(size, 3, 4))) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected a 3x3 or 4x4 matrix Matrix",
+ opname,
+ slot_name);
+ return -1;
+ }
+
+ BMO_slot_mat_set(bmop, bmop->slots_in, slot_name, pymat->matrix, size);
+ break;
+ }
+ case BMO_OP_SLOT_VEC: {
+ /* passing slot name here is a bit non-descriptive */
+ if (mathutils_array_parse(BMO_SLOT_AS_VECTOR(slot), 3, 3, value, slot_name) == -1) {
+ return -1;
+ }
+ break;
+ }
+ case BMO_OP_SLOT_ELEMENT_BUF: {
+ if (slot->slot_subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) {
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)value,
+ bm,
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ opname,
+ slot_name,
+ "single element") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ BMO_slot_buffer_from_single(bmop, slot, &((BPy_BMElem *)value)->ele->head);
+ }
+ else {
+ /* there are many ways we could interpret arguments, for now...
+ * - verts/edges/faces from the mesh direct,
+ * this way the operator takes every item.
+ * - `TODO` a plain python sequence (list) of elements.
+ * - `TODO` an iterator. eg.
+ * face.verts
+ * - `TODO` (type, flag) pair, eg.
+ * ('VERT', {'TAG'})
+ */
+
+ if (BPy_BMVertSeq_Check(value)) {
+ if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value,
+ bm,
+ BM_VERT,
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ opname,
+ slot_name,
+ "element buffer") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_VERT);
+ }
+ else if (BPy_BMEdgeSeq_Check(value)) {
+ if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value,
+ bm,
+ BM_EDGE,
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ opname,
+ slot_name,
+ "element buffer") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_EDGE);
+ }
+ else if (BPy_BMFaceSeq_Check(value)) {
+ if (bpy_slot_from_py_elemseq_check((BPy_BMGeneric *)value,
+ bm,
+ BM_FACE,
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ opname,
+ slot_name,
+ "element buffer") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+ BMO_slot_buffer_from_all(bm, bmop, bmop->slots_in, slot_name, BM_FACE);
+ }
+
+ else if (BPy_BMElemSeq_Check(value)) {
+ BMIter iter;
+ BMHeader *ele;
+ int tot;
+ unsigned int i;
+
+ if (bpy_slot_from_py_elemseq_check(
+ (BPy_BMGeneric *)value,
+ bm,
+ bm_iter_itype_htype_map[((BPy_BMElemSeq *)value)->itype],
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ opname,
+ slot_name,
+ "element buffer") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ /* this will loop over all elements which is a shame but
+ * we need to know this before alloc */
+ /* calls bpy_bmelemseq_length() */
+ tot = Py_TYPE(value)->tp_as_sequence->sq_length(value);
+
+ BMO_slot_buffer_alloc(bmop, bmop->slots_in, slot_name, tot);
+
+ i = 0;
+ BM_ITER_BPY_BM_SEQ(ele, &iter, ((BPy_BMElemSeq *)value))
+ {
+ slot->data.buf[i] = ele;
+ i++;
+ }
+ }
+ /* keep this last */
+ else if (PySequence_Check(value)) {
+ BMElem **elem_array = NULL;
+ Py_ssize_t elem_array_len;
+
+ elem_array = BPy_BMElem_PySeq_As_Array(&bm,
+ value,
+ 0,
+ PY_SSIZE_T_MAX,
+ &elem_array_len,
+ (slot->slot_subtype.elem & BM_ALL_NOLOOP),
+ true,
+ true,
+ slot_name);
+
+ /* error is set above */
+ if (elem_array == NULL) {
+ return -1;
+ }
+
+ BMO_slot_buffer_alloc(bmop, bmop->slots_in, slot_name, elem_array_len);
+ memcpy(slot->data.buf, elem_array, sizeof(void *) * elem_array_len);
+ PyMem_FREE(elem_array);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a bmesh sequence, list, (htype, flag) pair, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_MAPPING: {
+ /* first check types */
+ if (slot->slot_subtype.map != BMO_OP_SLOT_SUBTYPE_MAP_EMPTY) {
+ if (!PyDict_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a dict, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ }
+ else {
+ if (!PySet_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a set, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ }
+
+ switch (slot->slot_subtype.map) {
+ case BMO_OP_SLOT_SUBTYPE_MAP_ELEM: {
+ if (PyDict_Size(value) > 0) {
+ PyObject *arg_key, *arg_value;
+ Py_ssize_t arg_pos = 0;
+ while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid key in dict") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_value,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid value in dict") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ BMO_slot_map_elem_insert(
+ bmop, slot, ((BPy_BMElem *)arg_key)->ele, ((BPy_BMElem *)arg_value)->ele);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_FLT: {
+ if (PyDict_Size(value) > 0) {
+ PyObject *arg_key, *arg_value;
+ Py_ssize_t arg_pos = 0;
+ while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
+ float value_f;
+
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid key in dict") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ value_f = PyFloat_AsDouble(arg_value);
+
+ if (value_f == -1.0f && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a dict with float values, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(arg_value)->tp_name);
+ return -1;
+ }
+
+ BMO_slot_map_float_insert(bmop, slot, ((BPy_BMElem *)arg_key)->ele, value_f);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_INT: {
+ if (PyDict_Size(value) > 0) {
+ PyObject *arg_key, *arg_value;
+ Py_ssize_t arg_pos = 0;
+ while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
+ int value_i;
+
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid key in dict") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ value_i = PyC_Long_AsI32(arg_value);
+
+ if (value_i == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a dict with int values, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(arg_value)->tp_name);
+ return -1;
+ }
+
+ BMO_slot_map_int_insert(bmop, slot, ((BPy_BMElem *)arg_key)->ele, value_i);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_BOOL: {
+ if (PyDict_Size(value) > 0) {
+ PyObject *arg_key, *arg_value;
+ Py_ssize_t arg_pos = 0;
+ while (PyDict_Next(value, &arg_pos, &arg_key, &arg_value)) {
+ int value_i;
+
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid key in dict") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ value_i = PyC_Long_AsI32(arg_value);
+
+ if (value_i == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" expected "
+ "a dict with bool values, not %.200s",
+ opname,
+ slot_name,
+ Py_TYPE(arg_value)->tp_name);
+ return -1;
+ }
+
+ BMO_slot_map_bool_insert(bmop, slot, ((BPy_BMElem *)arg_key)->ele, value_i != 0);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_EMPTY: {
+ if (PySet_Size(value) > 0) {
+ PyObject *arg_key;
+ Py_ssize_t arg_pos = 0;
+ Py_ssize_t arg_hash = 0;
+ while (_PySet_NextEntry(value, &arg_pos, &arg_key, &arg_hash)) {
+
+ if (bpy_slot_from_py_elem_check((BPy_BMElem *)arg_key,
+ bm,
+ BM_ALL_NOLOOP,
+ opname,
+ slot_name,
+ "invalid key in set") == -1) {
+ return -1; /* error is set in bpy_slot_from_py_elem_check() */
+ }
+
+ BMO_slot_map_empty_insert(bmop, slot, ((BPy_BMElem *)arg_key)->ele);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_INTERNAL: {
+ /* can't convert from these */
+ PyErr_Format(PyExc_NotImplementedError,
+ "This arguments mapping subtype %d is not supported",
+ slot->slot_subtype.map);
+ return -1;
+ }
+ }
+ break;
+ }
+ default:
+ /* TODO --- many others */
+ PyErr_Format(PyExc_NotImplementedError,
+ "%.200s: keyword \"%.200s\" type %d not working yet!",
+ opname,
+ slot_name,
+ slot->slot_type);
+ return -1;
+ }
+
+ /* all is well */
+ return 0;
}
/**
@@ -542,153 +606,146 @@ static int bpy_slot_from_py(
*/
static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
{
- PyObject *item = NULL;
-
- /* keep switch in same order as above */
- switch (slot->slot_type) {
- case BMO_OP_SLOT_BOOL:
- item = PyBool_FromLong((BMO_SLOT_AS_BOOL(slot)));
- break;
- case BMO_OP_SLOT_INT:
- item = PyLong_FromLong(BMO_SLOT_AS_INT(slot));
- break;
- case BMO_OP_SLOT_FLT:
- item = PyFloat_FromDouble((double)BMO_SLOT_AS_FLOAT(slot));
- break;
- case BMO_OP_SLOT_MAT:
- item = Matrix_CreatePyObject((float *)BMO_SLOT_AS_MATRIX(slot), 4, 4, NULL);
- break;
- case BMO_OP_SLOT_VEC:
- item = Vector_CreatePyObject(BMO_SLOT_AS_VECTOR(slot), slot->len, NULL);
- break;
- case BMO_OP_SLOT_PTR:
- BLI_assert(0); /* currently we don't have any pointer return values in use */
- item = Py_INCREF_RET(Py_None);
- break;
- case BMO_OP_SLOT_ELEMENT_BUF:
- {
- if (slot->slot_subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) {
- BMHeader *ele = BMO_slot_buffer_get_single(slot);
- item = ele ? BPy_BMElem_CreatePyObject(bm, ele) : Py_INCREF_RET(Py_None);
- }
- else {
- const int size = slot->len;
- void **buffer = BMO_SLOT_AS_BUFFER(slot);
- int j;
-
- item = PyList_New(size);
- for (j = 0; j < size; j++) {
- BMHeader *ele = buffer[j];
- PyList_SET_ITEM(item, j, BPy_BMElem_CreatePyObject(bm, ele));
- }
- }
- break;
- }
- case BMO_OP_SLOT_MAPPING:
- {
- GHash *slot_hash = BMO_SLOT_AS_GHASH(slot);
- GHashIterator hash_iter;
-
- switch (slot->slot_subtype.map) {
- case BMO_OP_SLOT_SUBTYPE_MAP_ELEM:
- {
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
- if (slot_hash) {
- GHASH_ITER (hash_iter, slot_hash) {
- BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
- void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
-
- PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
- PyObject *py_val = BPy_BMElem_CreatePyObject(bm, ele_val);
-
- PyDict_SetItem(item, py_key, py_val);
- Py_DECREF(py_key);
- Py_DECREF(py_val);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_FLT:
- {
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
- if (slot_hash) {
- GHASH_ITER (hash_iter, slot_hash) {
- BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
- void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
-
- PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
- PyObject *py_val = PyFloat_FromDouble(*(float *)&ele_val);
-
- PyDict_SetItem(item, py_key, py_val);
- Py_DECREF(py_key);
- Py_DECREF(py_val);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_INT:
- {
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
- if (slot_hash) {
- GHASH_ITER (hash_iter, slot_hash) {
- BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
- void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
-
- PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
- PyObject *py_val = PyLong_FromLong(*(int *)&ele_val);
-
- PyDict_SetItem(item, py_key, py_val);
- Py_DECREF(py_key);
- Py_DECREF(py_val);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_BOOL:
- {
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
- if (slot_hash) {
- GHASH_ITER (hash_iter, slot_hash) {
- BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
- void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
-
- PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
- PyObject *py_val = PyBool_FromLong(*(bool *)&ele_val);
-
- PyDict_SetItem(item, py_key, py_val);
- Py_DECREF(py_key);
- Py_DECREF(py_val);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_EMPTY:
- {
- item = PySet_New(NULL);
- if (slot_hash) {
- GHASH_ITER (hash_iter, slot_hash) {
- BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
-
- PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
-
- PySet_Add(item, py_key);
-
- Py_DECREF(py_key);
- }
- }
- break;
- }
- case BMO_OP_SLOT_SUBTYPE_MAP_INTERNAL:
- /* can't convert from these */
- item = Py_INCREF_RET(Py_None);
- break;
- }
- break;
- }
- }
- BLI_assert(item != NULL);
-
- return item;
+ PyObject *item = NULL;
+
+ /* keep switch in same order as above */
+ switch (slot->slot_type) {
+ case BMO_OP_SLOT_BOOL:
+ item = PyBool_FromLong((BMO_SLOT_AS_BOOL(slot)));
+ break;
+ case BMO_OP_SLOT_INT:
+ item = PyLong_FromLong(BMO_SLOT_AS_INT(slot));
+ break;
+ case BMO_OP_SLOT_FLT:
+ item = PyFloat_FromDouble((double)BMO_SLOT_AS_FLOAT(slot));
+ break;
+ case BMO_OP_SLOT_MAT:
+ item = Matrix_CreatePyObject((float *)BMO_SLOT_AS_MATRIX(slot), 4, 4, NULL);
+ break;
+ case BMO_OP_SLOT_VEC:
+ item = Vector_CreatePyObject(BMO_SLOT_AS_VECTOR(slot), slot->len, NULL);
+ break;
+ case BMO_OP_SLOT_PTR:
+ BLI_assert(0); /* currently we don't have any pointer return values in use */
+ item = Py_INCREF_RET(Py_None);
+ break;
+ case BMO_OP_SLOT_ELEMENT_BUF: {
+ if (slot->slot_subtype.elem & BMO_OP_SLOT_SUBTYPE_ELEM_IS_SINGLE) {
+ BMHeader *ele = BMO_slot_buffer_get_single(slot);
+ item = ele ? BPy_BMElem_CreatePyObject(bm, ele) : Py_INCREF_RET(Py_None);
+ }
+ else {
+ const int size = slot->len;
+ void **buffer = BMO_SLOT_AS_BUFFER(slot);
+ int j;
+
+ item = PyList_New(size);
+ for (j = 0; j < size; j++) {
+ BMHeader *ele = buffer[j];
+ PyList_SET_ITEM(item, j, BPy_BMElem_CreatePyObject(bm, ele));
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_MAPPING: {
+ GHash *slot_hash = BMO_SLOT_AS_GHASH(slot);
+ GHashIterator hash_iter;
+
+ switch (slot->slot_subtype.map) {
+ case BMO_OP_SLOT_SUBTYPE_MAP_ELEM: {
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
+ if (slot_hash) {
+ GHASH_ITER (hash_iter, slot_hash) {
+ BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
+ void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
+
+ PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
+ PyObject *py_val = BPy_BMElem_CreatePyObject(bm, ele_val);
+
+ PyDict_SetItem(item, py_key, py_val);
+ Py_DECREF(py_key);
+ Py_DECREF(py_val);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_FLT: {
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
+ if (slot_hash) {
+ GHASH_ITER (hash_iter, slot_hash) {
+ BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
+ void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
+
+ PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
+ PyObject *py_val = PyFloat_FromDouble(*(float *)&ele_val);
+
+ PyDict_SetItem(item, py_key, py_val);
+ Py_DECREF(py_key);
+ Py_DECREF(py_val);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_INT: {
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
+ if (slot_hash) {
+ GHASH_ITER (hash_iter, slot_hash) {
+ BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
+ void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
+
+ PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
+ PyObject *py_val = PyLong_FromLong(*(int *)&ele_val);
+
+ PyDict_SetItem(item, py_key, py_val);
+ Py_DECREF(py_key);
+ Py_DECREF(py_val);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_BOOL: {
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
+ if (slot_hash) {
+ GHASH_ITER (hash_iter, slot_hash) {
+ BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
+ void *ele_val = BLI_ghashIterator_getValue(&hash_iter);
+
+ PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
+ PyObject *py_val = PyBool_FromLong(*(bool *)&ele_val);
+
+ PyDict_SetItem(item, py_key, py_val);
+ Py_DECREF(py_key);
+ Py_DECREF(py_val);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_EMPTY: {
+ item = PySet_New(NULL);
+ if (slot_hash) {
+ GHASH_ITER (hash_iter, slot_hash) {
+ BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
+
+ PyObject *py_key = BPy_BMElem_CreatePyObject(bm, ele_key);
+
+ PySet_Add(item, py_key);
+
+ Py_DECREF(py_key);
+ }
+ }
+ break;
+ }
+ case BMO_OP_SLOT_SUBTYPE_MAP_INTERNAL:
+ /* can't convert from these */
+ item = Py_INCREF_RET(Py_None);
+ break;
+ }
+ break;
+ }
+ }
+ BLI_assert(item != NULL);
+
+ return item;
}
/**
@@ -696,112 +753,109 @@ static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
*/
PyObject *BPy_BMO_call(BPy_BMeshOpFunc *self, PyObject *args, PyObject *kw)
{
- PyObject *ret;
- BPy_BMesh *py_bm;
- BMesh *bm;
-
- BMOperator bmop;
-
- if ((PyTuple_GET_SIZE(args) == 1) &&
- (py_bm = (BPy_BMesh *)PyTuple_GET_ITEM(args, 0)) &&
- (BPy_BMesh_Check(py_bm)))
- {
- BPY_BM_CHECK_OBJ(py_bm);
- bm = py_bm->bm;
-
- if (bm->use_toolflags == false) {
- PyErr_SetString(PyExc_ValueError,
- "bmesh created with 'use_operators=False'");
- return NULL;
- }
-
- /* could complain about entering with exceptions... */
- BMO_error_clear(bm);
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "bmesh operators expect a single BMesh positional argument, all other args must be keywords");
- return NULL;
- }
-
- /* TODO - error check this!, though we do the error check on attribute access */
- /* TODO - make flags optional */
- BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, self->opname);
-
- if (kw && PyDict_Size(kw) > 0) {
- /* setup properties, see bpy_rna.c: pyrna_py_to_prop()
- * which shares this logic for parsing properties */
-
- PyObject *key, *value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(kw, &pos, &key, &value)) {
- const char *slot_name = _PyUnicode_AsString(key);
- BMOpSlot *slot;
-
- if (!BMO_slot_exists(bmop.slots_in, slot_name)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" is invalid for this operator",
- self->opname, slot_name);
- BMO_op_finish(bm, &bmop);
- return NULL;
- }
-
- slot = BMO_slot_get(bmop.slots_in, slot_name);
-
- /* now assign the value */
- if (bpy_slot_from_py(bm, &bmop, slot, value,
- self->opname, slot_name) == -1)
- {
- BMO_op_finish(bm, &bmop);
- return NULL;
- }
- }
- }
-
- BMO_op_exec(bm, &bmop);
-
- /* from here until the end of the function, no returns, just set 'ret' */
- if (UNLIKELY(bpy_bm_op_as_py_error(bm) == -1)) {
- ret = NULL; /* exception raised above */
- }
- else if (bmop.slots_out[0].slot_name == NULL) {
- ret = Py_INCREF_RET(Py_None);
- }
- else {
- /* build return value */
- int i;
- ret = PyDict_New();
-
- for (i = 0; bmop.slots_out[i].slot_name; i++) {
- // BMOpDefine *op_def = opdefines[bmop.type];
- // BMOSlotType *slot_type = op_def->slot_types_out[i];
- BMOpSlot *slot = &bmop.slots_out[i];
- PyObject *item;
-
- /* this function doesn't throw exceptions */
- item = bpy_slot_to_py(bm, slot);
- if (item == NULL) {
- item = Py_INCREF_RET(Py_None);
- }
+ PyObject *ret;
+ BPy_BMesh *py_bm;
+ BMesh *bm;
+
+ BMOperator bmop;
+
+ if ((PyTuple_GET_SIZE(args) == 1) && (py_bm = (BPy_BMesh *)PyTuple_GET_ITEM(args, 0)) &&
+ (BPy_BMesh_Check(py_bm))) {
+ BPY_BM_CHECK_OBJ(py_bm);
+ bm = py_bm->bm;
+
+ if (bm->use_toolflags == false) {
+ PyErr_SetString(PyExc_ValueError, "bmesh created with 'use_operators=False'");
+ return NULL;
+ }
+
+ /* could complain about entering with exceptions... */
+ BMO_error_clear(bm);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "bmesh operators expect a single BMesh positional argument, all other args "
+ "must be keywords");
+ return NULL;
+ }
+
+ /* TODO - error check this!, though we do the error check on attribute access */
+ /* TODO - make flags optional */
+ BMO_op_init(bm, &bmop, BMO_FLAG_DEFAULTS, self->opname);
+
+ if (kw && PyDict_Size(kw) > 0) {
+ /* setup properties, see bpy_rna.c: pyrna_py_to_prop()
+ * which shares this logic for parsing properties */
+
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+ while (PyDict_Next(kw, &pos, &key, &value)) {
+ const char *slot_name = _PyUnicode_AsString(key);
+ BMOpSlot *slot;
+
+ if (!BMO_slot_exists(bmop.slots_in, slot_name)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" is invalid for this operator",
+ self->opname,
+ slot_name);
+ BMO_op_finish(bm, &bmop);
+ return NULL;
+ }
+
+ slot = BMO_slot_get(bmop.slots_in, slot_name);
+
+ /* now assign the value */
+ if (bpy_slot_from_py(bm, &bmop, slot, value, self->opname, slot_name) == -1) {
+ BMO_op_finish(bm, &bmop);
+ return NULL;
+ }
+ }
+ }
+
+ BMO_op_exec(bm, &bmop);
+
+ /* from here until the end of the function, no returns, just set 'ret' */
+ if (UNLIKELY(bpy_bm_op_as_py_error(bm) == -1)) {
+ ret = NULL; /* exception raised above */
+ }
+ else if (bmop.slots_out[0].slot_name == NULL) {
+ ret = Py_INCREF_RET(Py_None);
+ }
+ else {
+ /* build return value */
+ int i;
+ ret = PyDict_New();
+
+ for (i = 0; bmop.slots_out[i].slot_name; i++) {
+ // BMOpDefine *op_def = opdefines[bmop.type];
+ // BMOSlotType *slot_type = op_def->slot_types_out[i];
+ BMOpSlot *slot = &bmop.slots_out[i];
+ PyObject *item;
+
+ /* this function doesn't throw exceptions */
+ item = bpy_slot_to_py(bm, slot);
+ if (item == NULL) {
+ item = Py_INCREF_RET(Py_None);
+ }
#if 1
- /* temp code, strip off '.out' while we keep this convention */
- {
- char slot_name_strip[MAX_SLOTNAME];
- const char *ch = strchr(slot->slot_name, '.'); /* can't fail! */
- int tot = ch - slot->slot_name;
- BLI_assert(ch != NULL);
- memcpy(slot_name_strip, slot->slot_name, tot);
- slot_name_strip[tot] = '\0';
- PyDict_SetItemString(ret, slot_name_strip, item);
- }
+ /* temp code, strip off '.out' while we keep this convention */
+ {
+ char slot_name_strip[MAX_SLOTNAME];
+ const char *ch = strchr(slot->slot_name, '.'); /* can't fail! */
+ int tot = ch - slot->slot_name;
+ BLI_assert(ch != NULL);
+ memcpy(slot_name_strip, slot->slot_name, tot);
+ slot_name_strip[tot] = '\0';
+ PyDict_SetItemString(ret, slot_name_strip, item);
+ }
#else
- PyDict_SetItemString(ret, slot->slot_name, item);
+ PyDict_SetItemString(ret, slot->slot_name, item);
#endif
- Py_DECREF(item);
- }
- }
+ Py_DECREF(item);
+ }
+ }
- BMO_op_finish(bm, &bmop);
- return ret;
+ BMO_op_finish(bm, &bmop);
+ return ret;
}
diff --git a/source/blender/python/bmesh/bmesh_py_ops_call.h b/source/blender/python/bmesh/bmesh_py_ops_call.h
index 986c4e3e296..7b6611cd61d 100644
--- a/source/blender/python/bmesh/bmesh_py_ops_call.h
+++ b/source/blender/python/bmesh/bmesh_py_ops_call.h
@@ -25,11 +25,10 @@
#define __BMESH_PY_OPS_CALL_H__
typedef struct {
- PyObject_HEAD /* required python macro */
- const char *opname;
+ PyObject_HEAD /* required python macro */
+ const char *opname;
} BPy_BMeshOpFunc;
-
PyObject *BPy_BMO_call(BPy_BMeshOpFunc *self, PyObject *args, PyObject *kw);
#endif /* __BMESH_PY_OPS_CALL_H__ */
diff --git a/source/blender/python/bmesh/bmesh_py_types.c b/source/blender/python/bmesh/bmesh_py_types.c
index 366f0b4b3f7..522927f56e2 100644
--- a/source/blender/python/bmesh/bmesh_py_types.c
+++ b/source/blender/python/bmesh/bmesh_py_types.c
@@ -57,36 +57,36 @@ static void bm_dealloc_editmode_warn(BPy_BMesh *self);
/* scene does not use BM_* flags. */
PyC_FlagSet bpy_bm_scene_vert_edge_face_flags[] = {
- {1, "VERT"},
- {2, "EDGE"},
- {4, "FACE"},
- {0, NULL},
+ {1, "VERT"},
+ {2, "EDGE"},
+ {4, "FACE"},
+ {0, NULL},
};
PyC_FlagSet bpy_bm_htype_vert_edge_face_flags[] = {
- {BM_VERT, "VERT"},
- {BM_EDGE, "EDGE"},
- {BM_FACE, "FACE"},
- {0, NULL},
+ {BM_VERT, "VERT"},
+ {BM_EDGE, "EDGE"},
+ {BM_FACE, "FACE"},
+ {0, NULL},
};
PyC_FlagSet bpy_bm_htype_all_flags[] = {
- {BM_VERT, "VERT"},
- {BM_LOOP, "EDGE"},
- {BM_FACE, "FACE"},
- {BM_LOOP, "LOOP"},
- {0, NULL},
+ {BM_VERT, "VERT"},
+ {BM_LOOP, "EDGE"},
+ {BM_FACE, "FACE"},
+ {BM_LOOP, "LOOP"},
+ {0, NULL},
};
#define BPY_BM_HFLAG_ALL_STR "('SELECT', 'HIDE', 'SEAM', 'SMOOTH', 'TAG')"
PyC_FlagSet bpy_bm_hflag_all_flags[] = {
- {BM_ELEM_SELECT, "SELECT"},
- {BM_ELEM_HIDDEN, "HIDE"},
- {BM_ELEM_SEAM, "SEAM"},
- {BM_ELEM_SMOOTH, "SMOOTH"},
- {BM_ELEM_TAG, "TAG"},
- {0, NULL},
+ {BM_ELEM_SELECT, "SELECT"},
+ {BM_ELEM_HIDDEN, "HIDE"},
+ {BM_ELEM_SEAM, "SEAM"},
+ {BM_ELEM_SMOOTH, "SMOOTH"},
+ {BM_ELEM_TAG, "TAG"},
+ {0, NULL},
};
/* py-type definitions
@@ -95,498 +95,463 @@ PyC_FlagSet bpy_bm_hflag_all_flags[] = {
/* getseters
* ========= */
-
/* bmesh elems
* ----------- */
-PyDoc_STRVAR(bpy_bm_elem_select_doc, "Selected state of this element.\n\n:type: boolean");
-PyDoc_STRVAR(bpy_bm_elem_hide_doc, "Hidden state of this element.\n\n:type: boolean");
-PyDoc_STRVAR(bpy_bm_elem_tag_doc, "Generic attribute scripts can use for own logic\n\n:type: boolean");
-PyDoc_STRVAR(bpy_bm_elem_smooth_doc, "Smooth state of this element.\n\n:type: boolean");
-PyDoc_STRVAR(bpy_bm_elem_seam_doc, "Seam for UV unwrapping.\n\n:type: boolean");
-
+PyDoc_STRVAR(bpy_bm_elem_select_doc, "Selected state of this element.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bm_elem_hide_doc, "Hidden state of this element.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bm_elem_tag_doc,
+ "Generic attribute scripts can use for own logic\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bm_elem_smooth_doc, "Smooth state of this element.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bm_elem_seam_doc, "Seam for UV unwrapping.\n\n:type: boolean");
static PyObject *bpy_bm_elem_hflag_get(BPy_BMElem *self, void *flag)
{
- const char hflag = (char)POINTER_AS_INT(flag);
+ const char hflag = (char)POINTER_AS_INT(flag);
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_elem_flag_test(self->ele, hflag));
+ return PyBool_FromLong(BM_elem_flag_test(self->ele, hflag));
}
static int bpy_bm_elem_hflag_set(BPy_BMElem *self, PyObject *value, void *flag)
{
- const char hflag = (char)POINTER_AS_INT(flag);
- int param;
-
- BPY_BM_CHECK_INT(self);
-
- if ((param = PyC_Long_AsBool(value)) == -1) {
- return -1;
- }
-
- if (hflag == BM_ELEM_SELECT) {
- BM_elem_select_set(self->bm, self->ele, param);
- }
- else {
- BM_elem_flag_set(self->ele, hflag, param);
- }
- return 0;
-}
-
-PyDoc_STRVAR(bpy_bm_elem_index_doc,
-"Index of this element.\n"
-"\n"
-":type: int\n"
-"\n"
-".. note::\n"
-"\n"
-" This value is not necessarily valid, while editing the mesh it can become *dirty*.\n"
-"\n"
-" It's also possible to assign any number to this attribute for a scripts internal logic.\n"
-"\n"
-" To ensure the value is up to date - see :class:`BMElemSeq.index_update`.\n"
-);
+ const char hflag = (char)POINTER_AS_INT(flag);
+ int param;
+
+ BPY_BM_CHECK_INT(self);
+
+ if ((param = PyC_Long_AsBool(value)) == -1) {
+ return -1;
+ }
+
+ if (hflag == BM_ELEM_SELECT) {
+ BM_elem_select_set(self->bm, self->ele, param);
+ }
+ else {
+ BM_elem_flag_set(self->ele, hflag, param);
+ }
+ return 0;
+}
+
+PyDoc_STRVAR(
+ bpy_bm_elem_index_doc,
+ "Index of this element.\n"
+ "\n"
+ ":type: int\n"
+ "\n"
+ ".. note::\n"
+ "\n"
+ " This value is not necessarily valid, while editing the mesh it can become *dirty*.\n"
+ "\n"
+ " It's also possible to assign any number to this attribute for a scripts internal logic.\n"
+ "\n"
+ " To ensure the value is up to date - see :class:`BMElemSeq.index_update`.\n");
static PyObject *bpy_bm_elem_index_get(BPy_BMElem *self, void *UNUSED(flag))
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return PyLong_FromLong(BM_elem_index_get(self->ele));
+ return PyLong_FromLong(BM_elem_index_get(self->ele));
}
static int bpy_bm_elem_index_set(BPy_BMElem *self, PyObject *value, void *UNUSED(flag))
{
- int param;
+ int param;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
- /* error is set */
- return -1;
- }
+ if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
+ /* error is set */
+ return -1;
+ }
- BM_elem_index_set(self->ele, param); /* set_dirty! */
+ BM_elem_index_set(self->ele, param); /* set_dirty! */
- /* when setting the index assume its set invalid */
- self->bm->elem_index_dirty |= self->ele->head.htype;
+ /* when setting the index assume its set invalid */
+ self->bm->elem_index_dirty |= self->ele->head.htype;
- return 0;
+ return 0;
}
/* type specific get/sets
* ---------------------- */
-
/* Mesh
* ^^^^ */
/* doc-strings for all uses of this function */
PyDoc_STRVAR(bpy_bmvertseq_doc,
-"This meshes vert sequence (read-only).\n\n:type: :class:`BMVertSeq`"
-);
+ "This meshes vert sequence (read-only).\n\n:type: :class:`BMVertSeq`");
static PyObject *bpy_bmvertseq_get(BPy_BMesh *self, void *UNUSED(closure))
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMVertSeq_CreatePyObject(self->bm);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMVertSeq_CreatePyObject(self->bm);
}
PyDoc_STRVAR(bpy_bmedgeseq_doc,
-"This meshes edge sequence (read-only).\n\n:type: :class:`BMEdgeSeq`"
-);
+ "This meshes edge sequence (read-only).\n\n:type: :class:`BMEdgeSeq`");
static PyObject *bpy_bmedgeseq_get(BPy_BMesh *self, void *UNUSED(closure))
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMEdgeSeq_CreatePyObject(self->bm);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMEdgeSeq_CreatePyObject(self->bm);
}
PyDoc_STRVAR(bpy_bmfaceseq_doc,
-"This meshes face sequence (read-only).\n\n:type: :class:`BMFaceSeq`"
-);
+ "This meshes face sequence (read-only).\n\n:type: :class:`BMFaceSeq`");
static PyObject *bpy_bmfaceseq_get(BPy_BMesh *self, void *UNUSED(closure))
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMFaceSeq_CreatePyObject(self->bm);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMFaceSeq_CreatePyObject(self->bm);
}
PyDoc_STRVAR(bpy_bmloopseq_doc,
-"This meshes loops (read-only).\n\n:type: :class:`BMLoopSeq`\n"
-"\n"
-".. note::\n"
-"\n"
-" Loops must be accessed via faces, this is only exposed for layer access.\n"
-);
+ "This meshes loops (read-only).\n\n:type: :class:`BMLoopSeq`\n"
+ "\n"
+ ".. note::\n"
+ "\n"
+ " Loops must be accessed via faces, this is only exposed for layer access.\n");
static PyObject *bpy_bmloopseq_get(BPy_BMesh *self, void *UNUSED(closure))
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMLoopSeq_CreatePyObject(self->bm);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMLoopSeq_CreatePyObject(self->bm);
}
/* vert */
-PyDoc_STRVAR(bpy_bmvert_link_edges_doc,
-"Edges connected to this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMEdge`"
-);
-PyDoc_STRVAR(bpy_bmvert_link_faces_doc,
-"Faces connected to this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMFace`"
-);
-PyDoc_STRVAR(bpy_bmvert_link_loops_doc,
-"Loops that use this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`"
-);
+PyDoc_STRVAR(
+ bpy_bmvert_link_edges_doc,
+ "Edges connected to this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMEdge`");
+PyDoc_STRVAR(
+ bpy_bmvert_link_faces_doc,
+ "Faces connected to this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMFace`");
+PyDoc_STRVAR(
+ bpy_bmvert_link_loops_doc,
+ "Loops that use this vertex (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`");
/* edge */
PyDoc_STRVAR(bpy_bmedge_verts_doc,
-"Verts this edge uses (always 2), (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMVert`"
-);
-PyDoc_STRVAR(bpy_bmedge_link_faces_doc,
-"Faces connected to this edge, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMFace`"
-);
-PyDoc_STRVAR(bpy_bmedge_link_loops_doc,
-"Loops connected to this edge, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`"
-);
+ "Verts this edge uses (always 2), (read-only).\n\n:type: :class:`BMElemSeq` of "
+ ":class:`BMVert`");
+PyDoc_STRVAR(
+ bpy_bmedge_link_faces_doc,
+ "Faces connected to this edge, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMFace`");
+PyDoc_STRVAR(
+ bpy_bmedge_link_loops_doc,
+ "Loops connected to this edge, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`");
/* face */
PyDoc_STRVAR(bpy_bmface_verts_doc,
-"Verts of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMVert`"
-);
+ "Verts of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMVert`");
PyDoc_STRVAR(bpy_bmface_edges_doc,
-"Edges of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMEdge`"
-);
+ "Edges of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMEdge`");
PyDoc_STRVAR(bpy_bmface_loops_doc,
-"Loops of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`"
-);
+ "Loops of this face, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`");
/* loop */
-PyDoc_STRVAR(bpy_bmloops_link_loops_doc,
-"Loops connected to this loop, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`"
-);
+PyDoc_STRVAR(
+ bpy_bmloops_link_loops_doc,
+ "Loops connected to this loop, (read-only).\n\n:type: :class:`BMElemSeq` of :class:`BMLoop`");
static PyObject *bpy_bmelemseq_elem_get(BPy_BMElem *self, void *itype)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMElemSeq_CreatePyObject(self->bm, self, POINTER_AS_INT(itype));
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMElemSeq_CreatePyObject(self->bm, self, POINTER_AS_INT(itype));
}
-
PyDoc_STRVAR(bpy_bm_is_valid_doc,
-"True when this element is valid (hasn't been removed).\n\n:type: boolean"
-);
+ "True when this element is valid (hasn't been removed).\n\n:type: boolean");
static PyObject *bpy_bm_is_valid_get(BPy_BMGeneric *self)
{
- return PyBool_FromLong(BPY_BM_IS_VALID(self));
+ return PyBool_FromLong(BPY_BM_IS_VALID(self));
}
-PyDoc_STRVAR(bpy_bmesh_is_wrapped_doc,
-"True when this mesh is owned by blender (typically the editmode BMesh).\n\n:type: boolean"
-);
+PyDoc_STRVAR(
+ bpy_bmesh_is_wrapped_doc,
+ "True when this mesh is owned by blender (typically the editmode BMesh).\n\n:type: boolean");
static PyObject *bpy_bmesh_is_wrapped_get(BPy_BMesh *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(self->flag & BPY_BMFLAG_IS_WRAPPED);
+ return PyBool_FromLong(self->flag & BPY_BMFLAG_IS_WRAPPED);
}
PyDoc_STRVAR(bpy_bmesh_select_mode_doc,
-"The selection mode, values can be {'VERT', 'EDGE', 'FACE'}, can't be assigned an empty set.\n\n:type: set"
-);
+ "The selection mode, values can be {'VERT', 'EDGE', 'FACE'}, can't be assigned an "
+ "empty set.\n\n:type: set");
static PyObject *bpy_bmesh_select_mode_get(BPy_BMesh *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return PyC_FlagSet_FromBitfield(bpy_bm_scene_vert_edge_face_flags, self->bm->selectmode);
+ return PyC_FlagSet_FromBitfield(bpy_bm_scene_vert_edge_face_flags, self->bm->selectmode);
}
static int bpy_bmesh_select_mode_set(BPy_BMesh *self, PyObject *value)
{
- int flag = 0;
- BPY_BM_CHECK_INT(self);
+ int flag = 0;
+ BPY_BM_CHECK_INT(self);
- if (PyC_FlagSet_ToBitfield(bpy_bm_scene_vert_edge_face_flags, value, &flag, "bm.select_mode") == -1) {
- return -1;
- }
- else if (flag == 0) {
- PyErr_SetString(PyExc_TypeError,
- "bm.select_mode: cant assignt an empty value");
- return -1;
- }
- else {
- self->bm->selectmode = flag;
- return 0;
- }
+ if (PyC_FlagSet_ToBitfield(bpy_bm_scene_vert_edge_face_flags, value, &flag, "bm.select_mode") ==
+ -1) {
+ return -1;
+ }
+ else if (flag == 0) {
+ PyErr_SetString(PyExc_TypeError, "bm.select_mode: cant assignt an empty value");
+ return -1;
+ }
+ else {
+ self->bm->selectmode = flag;
+ return 0;
+ }
}
PyDoc_STRVAR(bpy_bmesh_select_history_doc,
-"Sequence of selected items (the last is displayed as active).\n\n:type: :class:`BMEditSelSeq`"
-);
+ "Sequence of selected items (the last is displayed as active).\n\n:type: "
+ ":class:`BMEditSelSeq`");
static PyObject *bpy_bmesh_select_history_get(BPy_BMesh *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return BPy_BMEditSel_CreatePyObject(self->bm);
+ return BPy_BMEditSel_CreatePyObject(self->bm);
}
static int bpy_bmesh_select_history_set(BPy_BMesh *self, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- return BPy_BMEditSel_Assign(self, value);
+ return BPy_BMEditSel_Assign(self, value);
}
/* Vert
* ^^^^ */
PyDoc_STRVAR(bpy_bmvert_co_doc,
-"The coordinates for this vertex as a 3D, wrapped vector.\n\n:type: :class:`mathutils.Vector`"
-);
+ "The coordinates for this vertex as a 3D, wrapped vector.\n\n:type: "
+ ":class:`mathutils.Vector`");
static PyObject *bpy_bmvert_co_get(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return Vector_CreatePyObject_wrap(self->v->co, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ return Vector_CreatePyObject_wrap(self->v->co, 3, NULL);
}
static int bpy_bmvert_co_set(BPy_BMVert *self, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (mathutils_array_parse(self->v->co, 3, 3, value, "BMVert.co") != -1) {
- return 0;
- }
- else {
- return -1;
- }
+ if (mathutils_array_parse(self->v->co, 3, 3, value, "BMVert.co") != -1) {
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
-
-PyDoc_STRVAR(bpy_bmvert_normal_doc,
-"The normal for this vertex as a 3D, wrapped vector.\n\n:type: :class:`mathutils.Vector`"
-);
+PyDoc_STRVAR(
+ bpy_bmvert_normal_doc,
+ "The normal for this vertex as a 3D, wrapped vector.\n\n:type: :class:`mathutils.Vector`");
static PyObject *bpy_bmvert_normal_get(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return Vector_CreatePyObject_wrap(self->v->no, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ return Vector_CreatePyObject_wrap(self->v->no, 3, NULL);
}
static int bpy_bmvert_normal_set(BPy_BMVert *self, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (mathutils_array_parse(self->v->no, 3, 3, value, "BMVert.normal") != -1) {
- return 0;
- }
- else {
- return -1;
- }
+ if (mathutils_array_parse(self->v->no, 3, 3, value, "BMVert.normal") != -1) {
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
-
PyDoc_STRVAR(bpy_bmvert_is_manifold_doc,
-"True when this vertex is manifold (read-only).\n\n:type: boolean"
-);
+ "True when this vertex is manifold (read-only).\n\n:type: boolean");
static PyObject *bpy_bmvert_is_manifold_get(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_vert_is_manifold(self->v));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_vert_is_manifold(self->v));
}
-
PyDoc_STRVAR(bpy_bmvert_is_wire_doc,
-"True when this vertex is not connected to any faces (read-only).\n\n:type: boolean"
-);
+ "True when this vertex is not connected to any faces (read-only).\n\n:type: boolean");
static PyObject *bpy_bmvert_is_wire_get(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_vert_is_wire(self->v));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_vert_is_wire(self->v));
}
-PyDoc_STRVAR(bpy_bmvert_is_boundary_doc,
-"True when this vertex is connected to boundary edges (read-only).\n\n:type: boolean"
-);
+PyDoc_STRVAR(
+ bpy_bmvert_is_boundary_doc,
+ "True when this vertex is connected to boundary edges (read-only).\n\n:type: boolean");
static PyObject *bpy_bmvert_is_boundary_get(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_vert_is_boundary(self->v));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_vert_is_boundary(self->v));
}
-
/* Edge
* ^^^^ */
PyDoc_STRVAR(bpy_bmedge_is_manifold_doc,
-"True when this edge is manifold (read-only).\n\n:type: boolean"
-);
+ "True when this edge is manifold (read-only).\n\n:type: boolean");
static PyObject *bpy_bmedge_is_manifold_get(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_edge_is_manifold(self->e));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_edge_is_manifold(self->e));
}
PyDoc_STRVAR(bpy_bmedge_is_contiguous_doc,
-"True when this edge is manifold, between two faces with the same winding (read-only).\n\n:type: boolean"
-);
+ "True when this edge is manifold, between two faces with the same winding "
+ "(read-only).\n\n:type: boolean");
static PyObject *bpy_bmedge_is_contiguous_get(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_edge_is_contiguous(self->e));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_edge_is_contiguous(self->e));
}
PyDoc_STRVAR(bpy_bmedge_is_convex_doc,
-"True when this edge joins two convex faces, depends on a valid face normal (read-only).\n\n:type: boolean"
-);
+ "True when this edge joins two convex faces, depends on a valid face normal "
+ "(read-only).\n\n:type: boolean");
static PyObject *bpy_bmedge_is_convex_get(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_edge_is_convex(self->e));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_edge_is_convex(self->e));
}
PyDoc_STRVAR(bpy_bmedge_is_wire_doc,
-"True when this edge is not connected to any faces (read-only).\n\n:type: boolean"
-);
+ "True when this edge is not connected to any faces (read-only).\n\n:type: boolean");
static PyObject *bpy_bmedge_is_wire_get(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_edge_is_wire(self->e));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_edge_is_wire(self->e));
}
-
PyDoc_STRVAR(bpy_bmedge_is_boundary_doc,
-"True when this edge is at the boundary of a face (read-only).\n\n:type: boolean"
-);
+ "True when this edge is at the boundary of a face (read-only).\n\n:type: boolean");
static PyObject *bpy_bmedge_is_boundary_get(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_edge_is_boundary(self->e));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_edge_is_boundary(self->e));
}
-
/* Face
* ^^^^ */
-PyDoc_STRVAR(bpy_bmface_normal_doc,
-"The normal for this face as a 3D, wrapped vector.\n\n:type: :class:`mathutils.Vector`"
-);
+PyDoc_STRVAR(
+ bpy_bmface_normal_doc,
+ "The normal for this face as a 3D, wrapped vector.\n\n:type: :class:`mathutils.Vector`");
static PyObject *bpy_bmface_normal_get(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
- return Vector_CreatePyObject_wrap(self->f->no, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ return Vector_CreatePyObject_wrap(self->f->no, 3, NULL);
}
static int bpy_bmface_normal_set(BPy_BMFace *self, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (mathutils_array_parse(self->f->no, 3, 3, value, "BMFace.normal") != -1) {
- return 0;
- }
- else {
- return -1;
- }
+ if (mathutils_array_parse(self->f->no, 3, 3, value, "BMFace.normal") != -1) {
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
-PyDoc_STRVAR(bpy_bmface_material_index_doc,
-"The face's material index.\n\n:type: int"
-);
+PyDoc_STRVAR(bpy_bmface_material_index_doc, "The face's material index.\n\n:type: int");
static PyObject *bpy_bmface_material_index_get(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyLong_FromLong(self->f->mat_nr);
+ BPY_BM_CHECK_OBJ(self);
+ return PyLong_FromLong(self->f->mat_nr);
}
static int bpy_bmface_material_index_set(BPy_BMFace *self, PyObject *value)
{
- int param;
+ int param;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
- /* error is set */
- return -1;
- }
+ if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
+ /* error is set */
+ return -1;
+ }
- if ((param < 0) || (param > MAXMAT)) {
- /* normally we clamp but in this case raise an error */
- PyErr_SetString(PyExc_ValueError,
- "material index outside of usable range (0 - 32766)");
- return -1;
- }
- else {
- self->f->mat_nr = (short)param;
- return 0;
- }
+ if ((param < 0) || (param > MAXMAT)) {
+ /* normally we clamp but in this case raise an error */
+ PyErr_SetString(PyExc_ValueError, "material index outside of usable range (0 - 32766)");
+ return -1;
+ }
+ else {
+ self->f->mat_nr = (short)param;
+ return 0;
+ }
}
-
/* Loop
* ^^^^ */
-PyDoc_STRVAR(bpy_bmloop_vert_doc,
-"The loop's vertex (read-only).\n\n:type: :class:`BMVert`"
-);
+PyDoc_STRVAR(bpy_bmloop_vert_doc, "The loop's vertex (read-only).\n\n:type: :class:`BMVert`");
static PyObject *bpy_bmloop_vert_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMVert_CreatePyObject(self->bm, self->l->v);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMVert_CreatePyObject(self->bm, self->l->v);
}
-
-PyDoc_STRVAR(bpy_bmloop_edge_doc,
-"The loop's edge (between this loop and the next), (read-only).\n\n:type: :class:`BMEdge`"
-);
+PyDoc_STRVAR(
+ bpy_bmloop_edge_doc,
+ "The loop's edge (between this loop and the next), (read-only).\n\n:type: :class:`BMEdge`");
static PyObject *bpy_bmloop_edge_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMEdge_CreatePyObject(self->bm, self->l->e);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMEdge_CreatePyObject(self->bm, self->l->e);
}
-
PyDoc_STRVAR(bpy_bmloop_face_doc,
-"The face this loop makes (read-only).\n\n:type: :class:`BMFace`"
-);
+ "The face this loop makes (read-only).\n\n:type: :class:`BMFace`");
static PyObject *bpy_bmloop_face_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMFace_CreatePyObject(self->bm, self->l->f);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMFace_CreatePyObject(self->bm, self->l->f);
}
PyDoc_STRVAR(bpy_bmloop_link_loop_next_doc,
-"The next face corner (read-only).\n\n:type: :class:`BMLoop`"
-);
+ "The next face corner (read-only).\n\n:type: :class:`BMLoop`");
static PyObject *bpy_bmloop_link_loop_next_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMLoop_CreatePyObject(self->bm, self->l->next);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMLoop_CreatePyObject(self->bm, self->l->next);
}
PyDoc_STRVAR(bpy_bmloop_link_loop_prev_doc,
-"The previous face corner (read-only).\n\n:type: :class:`BMLoop`"
-);
+ "The previous face corner (read-only).\n\n:type: :class:`BMLoop`");
static PyObject *bpy_bmloop_link_loop_prev_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMLoop_CreatePyObject(self->bm, self->l->prev);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMLoop_CreatePyObject(self->bm, self->l->prev);
}
PyDoc_STRVAR(bpy_bmloop_link_loop_radial_next_doc,
-"The next loop around the edge (read-only).\n\n:type: :class:`BMLoop`"
-);
+ "The next loop around the edge (read-only).\n\n:type: :class:`BMLoop`");
static PyObject *bpy_bmloop_link_loop_radial_next_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMLoop_CreatePyObject(self->bm, self->l->radial_next);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMLoop_CreatePyObject(self->bm, self->l->radial_next);
}
PyDoc_STRVAR(bpy_bmloop_link_loop_radial_prev_doc,
-"The previous loop around the edge (read-only).\n\n:type: :class:`BMLoop`"
-);
+ "The previous loop around the edge (read-only).\n\n:type: :class:`BMLoop`");
static PyObject *bpy_bmloop_link_loop_radial_prev_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return BPy_BMLoop_CreatePyObject(self->bm, self->l->radial_prev);
+ BPY_BM_CHECK_OBJ(self);
+ return BPy_BMLoop_CreatePyObject(self->bm, self->l->radial_prev);
}
PyDoc_STRVAR(bpy_bmloop_is_convex_doc,
-"True when this loop is at the convex corner of a face, depends on a valid face normal (read-only).\n\n:type: boolean"
-);
+ "True when this loop is at the convex corner of a face, depends on a valid face "
+ "normal (read-only).\n\n:type: boolean");
static PyObject *bpy_bmloop_is_convex_get(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(BM_loop_is_convex(self->l));
+ BPY_BM_CHECK_OBJ(self);
+ return PyBool_FromLong(BM_loop_is_convex(self->l));
}
/* ElemSeq
@@ -594,1935 +559,2096 @@ static PyObject *bpy_bmloop_is_convex_get(BPy_BMLoop *self)
/* note: use for bmvert/edge/face/loop seq's use these, not bmelemseq directly */
PyDoc_STRVAR(bpy_bmelemseq_layers_vert_doc,
-"custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessVert`"
-);
+ "custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessVert`");
PyDoc_STRVAR(bpy_bmelemseq_layers_edge_doc,
-"custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessEdge`"
-);
+ "custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessEdge`");
PyDoc_STRVAR(bpy_bmelemseq_layers_face_doc,
-"custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessFace`"
-);
+ "custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessFace`");
PyDoc_STRVAR(bpy_bmelemseq_layers_loop_doc,
-"custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessLoop`"
-);
+ "custom-data layers (read-only).\n\n:type: :class:`BMLayerAccessLoop`");
static PyObject *bpy_bmelemseq_layers_get(BPy_BMElemSeq *self, void *htype)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return BPy_BMLayerAccess_CreatePyObject(self->bm, POINTER_AS_INT(htype));
+ return BPy_BMLayerAccess_CreatePyObject(self->bm, POINTER_AS_INT(htype));
}
/* FaceSeq
* ^^^^^^^ */
-PyDoc_STRVAR(bpy_bmfaceseq_active_doc,
-"active face.\n\n:type: :class:`BMFace` or None"
-);
+PyDoc_STRVAR(bpy_bmfaceseq_active_doc, "active face.\n\n:type: :class:`BMFace` or None");
static PyObject *bpy_bmfaceseq_active_get(BPy_BMElemSeq *self, void *UNUSED(closure))
{
- BMesh *bm = self->bm;
- BPY_BM_CHECK_OBJ(self);
+ BMesh *bm = self->bm;
+ BPY_BM_CHECK_OBJ(self);
- if (bm->act_face) {
- return BPy_BMElem_CreatePyObject(bm, (BMHeader *)bm->act_face);
- }
- else {
- Py_RETURN_NONE;
- }
+ if (bm->act_face) {
+ return BPy_BMElem_CreatePyObject(bm, (BMHeader *)bm->act_face);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
static int bpy_bmfaceseq_active_set(BPy_BMElem *self, PyObject *value, void *UNUSED(closure))
{
- BMesh *bm = self->bm;
- if (value == Py_None) {
- bm->act_face = NULL;
- return 0;
- }
- else if (BPy_BMFace_Check(value)) {
- BPY_BM_CHECK_SOURCE_INT(bm, "faces.active = f", value);
-
- bm->act_face = ((BPy_BMFace *)value)->f;
- return 0;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "faces.active = f: expected BMFace or None, not %.200s",
- Py_TYPE(value)->tp_name);
- return -1;
- }
+ BMesh *bm = self->bm;
+ if (value == Py_None) {
+ bm->act_face = NULL;
+ return 0;
+ }
+ else if (BPy_BMFace_Check(value)) {
+ BPY_BM_CHECK_SOURCE_INT(bm, "faces.active = f", value);
+
+ bm->act_face = ((BPy_BMFace *)value)->f;
+ return 0;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "faces.active = f: expected BMFace or None, not %.200s",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
}
static PyGetSetDef bpy_bmesh_getseters[] = {
- {(char *)"verts", (getter)bpy_bmvertseq_get, (setter)NULL, (char *)bpy_bmvertseq_doc, NULL},
- {(char *)"edges", (getter)bpy_bmedgeseq_get, (setter)NULL, (char *)bpy_bmedgeseq_doc, NULL},
- {(char *)"faces", (getter)bpy_bmfaceseq_get, (setter)NULL, (char *)bpy_bmfaceseq_doc, NULL},
- {(char *)"loops", (getter)bpy_bmloopseq_get, (setter)NULL, (char *)bpy_bmloopseq_doc, NULL},
- {(char *)"select_mode", (getter)bpy_bmesh_select_mode_get, (setter)bpy_bmesh_select_mode_set, (char *)bpy_bmesh_select_mode_doc, NULL},
-
- {(char *)"select_history", (getter)bpy_bmesh_select_history_get, (setter)bpy_bmesh_select_history_set, (char *)bpy_bmesh_select_history_doc, NULL},
-
- /* readonly checks */
- {(char *)"is_wrapped", (getter)bpy_bmesh_is_wrapped_get, (setter)NULL, (char *)bpy_bmesh_is_wrapped_doc, NULL}, /* as with mathutils */
- {(char *)"is_valid", (getter)bpy_bm_is_valid_get, (setter)NULL, (char *)bpy_bm_is_valid_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"verts", (getter)bpy_bmvertseq_get, (setter)NULL, (char *)bpy_bmvertseq_doc, NULL},
+ {(char *)"edges", (getter)bpy_bmedgeseq_get, (setter)NULL, (char *)bpy_bmedgeseq_doc, NULL},
+ {(char *)"faces", (getter)bpy_bmfaceseq_get, (setter)NULL, (char *)bpy_bmfaceseq_doc, NULL},
+ {(char *)"loops", (getter)bpy_bmloopseq_get, (setter)NULL, (char *)bpy_bmloopseq_doc, NULL},
+ {(char *)"select_mode",
+ (getter)bpy_bmesh_select_mode_get,
+ (setter)bpy_bmesh_select_mode_set,
+ (char *)bpy_bmesh_select_mode_doc,
+ NULL},
+
+ {(char *)"select_history",
+ (getter)bpy_bmesh_select_history_get,
+ (setter)bpy_bmesh_select_history_set,
+ (char *)bpy_bmesh_select_history_doc,
+ NULL},
+
+ /* readonly checks */
+ {(char *)"is_wrapped",
+ (getter)bpy_bmesh_is_wrapped_get,
+ (setter)NULL,
+ (char *)bpy_bmesh_is_wrapped_doc,
+ NULL}, /* as with mathutils */
+ {(char *)"is_valid",
+ (getter)bpy_bm_is_valid_get,
+ (setter)NULL,
+ (char *)bpy_bm_is_valid_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmvert_getseters[] = {
- /* generic */
- {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
- {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
- {(char *)"tag", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_tag_doc, (void *)BM_ELEM_TAG},
- {(char *)"index", (getter)bpy_bm_elem_index_get, (setter)bpy_bm_elem_index_set, (char *)bpy_bm_elem_index_doc, NULL},
-
- {(char *)"co", (getter)bpy_bmvert_co_get, (setter)bpy_bmvert_co_set, (char *)bpy_bmvert_co_doc, NULL},
- {(char *)"normal", (getter)bpy_bmvert_normal_get, (setter)bpy_bmvert_normal_set, (char *)bpy_bmvert_normal_doc, NULL},
-
- /* connectivity data */
- {(char *)"link_edges", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmvert_link_edges_doc, (void *)BM_EDGES_OF_VERT},
- {(char *)"link_faces", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmvert_link_faces_doc, (void *)BM_FACES_OF_VERT},
- {(char *)"link_loops", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmvert_link_loops_doc, (void *)BM_LOOPS_OF_VERT},
-
- /* readonly checks */
- {(char *)"is_manifold", (getter)bpy_bmvert_is_manifold_get, (setter)NULL, (char *)bpy_bmvert_is_manifold_doc, NULL},
- {(char *)"is_wire", (getter)bpy_bmvert_is_wire_get, (setter)NULL, (char *)bpy_bmvert_is_wire_doc, NULL},
- {(char *)"is_boundary", (getter)bpy_bmvert_is_boundary_get, (setter)NULL, (char *)bpy_bmvert_is_boundary_doc, NULL},
- {(char *)"is_valid", (getter)bpy_bm_is_valid_get, (setter)NULL, (char *)bpy_bm_is_valid_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* generic */
+ {(char *)"select",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_select_doc,
+ (void *)BM_ELEM_SELECT},
+ {(char *)"hide",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_hide_doc,
+ (void *)BM_ELEM_HIDDEN},
+ {(char *)"tag",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_tag_doc,
+ (void *)BM_ELEM_TAG},
+ {(char *)"index",
+ (getter)bpy_bm_elem_index_get,
+ (setter)bpy_bm_elem_index_set,
+ (char *)bpy_bm_elem_index_doc,
+ NULL},
+
+ {(char *)"co",
+ (getter)bpy_bmvert_co_get,
+ (setter)bpy_bmvert_co_set,
+ (char *)bpy_bmvert_co_doc,
+ NULL},
+ {(char *)"normal",
+ (getter)bpy_bmvert_normal_get,
+ (setter)bpy_bmvert_normal_set,
+ (char *)bpy_bmvert_normal_doc,
+ NULL},
+
+ /* connectivity data */
+ {(char *)"link_edges",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_link_edges_doc,
+ (void *)BM_EDGES_OF_VERT},
+ {(char *)"link_faces",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_link_faces_doc,
+ (void *)BM_FACES_OF_VERT},
+ {(char *)"link_loops",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_link_loops_doc,
+ (void *)BM_LOOPS_OF_VERT},
+
+ /* readonly checks */
+ {(char *)"is_manifold",
+ (getter)bpy_bmvert_is_manifold_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_is_manifold_doc,
+ NULL},
+ {(char *)"is_wire",
+ (getter)bpy_bmvert_is_wire_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_is_wire_doc,
+ NULL},
+ {(char *)"is_boundary",
+ (getter)bpy_bmvert_is_boundary_get,
+ (setter)NULL,
+ (char *)bpy_bmvert_is_boundary_doc,
+ NULL},
+ {(char *)"is_valid",
+ (getter)bpy_bm_is_valid_get,
+ (setter)NULL,
+ (char *)bpy_bm_is_valid_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmedge_getseters[] = {
- /* generic */
- {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
- {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
- {(char *)"tag", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_tag_doc, (void *)BM_ELEM_TAG},
- {(char *)"index", (getter)bpy_bm_elem_index_get, (setter)bpy_bm_elem_index_set, (char *)bpy_bm_elem_index_doc, NULL},
-
- {(char *)"smooth", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_smooth_doc, (void *)BM_ELEM_SMOOTH},
- {(char *)"seam", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_seam_doc, (void *)BM_ELEM_SEAM},
-
- /* connectivity data */
- {(char *)"verts", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmedge_verts_doc, (void *)BM_VERTS_OF_EDGE},
-
- {(char *)"link_faces", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmedge_link_faces_doc, (void *)BM_FACES_OF_EDGE},
- {(char *)"link_loops", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmedge_link_loops_doc, (void *)BM_LOOPS_OF_EDGE},
-
- /* readonly checks */
- {(char *)"is_manifold", (getter)bpy_bmedge_is_manifold_get, (setter)NULL, (char *)bpy_bmedge_is_manifold_doc, NULL},
- {(char *)"is_contiguous", (getter)bpy_bmedge_is_contiguous_get, (setter)NULL, (char *)bpy_bmedge_is_contiguous_doc, NULL},
- {(char *)"is_convex", (getter)bpy_bmedge_is_convex_get, (setter)NULL, (char *)bpy_bmedge_is_convex_doc, NULL},
- {(char *)"is_wire", (getter)bpy_bmedge_is_wire_get, (setter)NULL, (char *)bpy_bmedge_is_wire_doc, NULL},
- {(char *)"is_boundary", (getter)bpy_bmedge_is_boundary_get, (setter)NULL, (char *)bpy_bmedge_is_boundary_doc, NULL},
- {(char *)"is_valid", (getter)bpy_bm_is_valid_get, (setter)NULL, (char *)bpy_bm_is_valid_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* generic */
+ {(char *)"select",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_select_doc,
+ (void *)BM_ELEM_SELECT},
+ {(char *)"hide",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_hide_doc,
+ (void *)BM_ELEM_HIDDEN},
+ {(char *)"tag",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_tag_doc,
+ (void *)BM_ELEM_TAG},
+ {(char *)"index",
+ (getter)bpy_bm_elem_index_get,
+ (setter)bpy_bm_elem_index_set,
+ (char *)bpy_bm_elem_index_doc,
+ NULL},
+
+ {(char *)"smooth",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_smooth_doc,
+ (void *)BM_ELEM_SMOOTH},
+ {(char *)"seam",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_seam_doc,
+ (void *)BM_ELEM_SEAM},
+
+ /* connectivity data */
+ {(char *)"verts",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_verts_doc,
+ (void *)BM_VERTS_OF_EDGE},
+
+ {(char *)"link_faces",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_link_faces_doc,
+ (void *)BM_FACES_OF_EDGE},
+ {(char *)"link_loops",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_link_loops_doc,
+ (void *)BM_LOOPS_OF_EDGE},
+
+ /* readonly checks */
+ {(char *)"is_manifold",
+ (getter)bpy_bmedge_is_manifold_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_is_manifold_doc,
+ NULL},
+ {(char *)"is_contiguous",
+ (getter)bpy_bmedge_is_contiguous_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_is_contiguous_doc,
+ NULL},
+ {(char *)"is_convex",
+ (getter)bpy_bmedge_is_convex_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_is_convex_doc,
+ NULL},
+ {(char *)"is_wire",
+ (getter)bpy_bmedge_is_wire_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_is_wire_doc,
+ NULL},
+ {(char *)"is_boundary",
+ (getter)bpy_bmedge_is_boundary_get,
+ (setter)NULL,
+ (char *)bpy_bmedge_is_boundary_doc,
+ NULL},
+ {(char *)"is_valid",
+ (getter)bpy_bm_is_valid_get,
+ (setter)NULL,
+ (char *)bpy_bm_is_valid_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmface_getseters[] = {
- /* generic */
- {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
- {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
- {(char *)"tag", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_tag_doc, (void *)BM_ELEM_TAG},
- {(char *)"index", (getter)bpy_bm_elem_index_get, (setter)bpy_bm_elem_index_set, (char *)bpy_bm_elem_index_doc, NULL},
-
- {(char *)"smooth", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_smooth_doc, (void *)BM_ELEM_SMOOTH},
-
- {(char *)"normal", (getter)bpy_bmface_normal_get, (setter)bpy_bmface_normal_set, (char *)bpy_bmface_normal_doc, NULL},
-
- {(char *)"material_index", (getter)bpy_bmface_material_index_get, (setter)bpy_bmface_material_index_set, (char *)bpy_bmface_material_index_doc, NULL},
-
- /* connectivity data */
- {(char *)"verts", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmface_verts_doc, (void *)BM_VERTS_OF_FACE},
- {(char *)"edges", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmface_edges_doc, (void *)BM_EDGES_OF_FACE},
- {(char *)"loops", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmface_loops_doc, (void *)BM_LOOPS_OF_FACE},
-
- /* readonly checks */
- {(char *)"is_valid", (getter)bpy_bm_is_valid_get, (setter)NULL, (char *)bpy_bm_is_valid_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* generic */
+ {(char *)"select",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_select_doc,
+ (void *)BM_ELEM_SELECT},
+ {(char *)"hide",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_hide_doc,
+ (void *)BM_ELEM_HIDDEN},
+ {(char *)"tag",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_tag_doc,
+ (void *)BM_ELEM_TAG},
+ {(char *)"index",
+ (getter)bpy_bm_elem_index_get,
+ (setter)bpy_bm_elem_index_set,
+ (char *)bpy_bm_elem_index_doc,
+ NULL},
+
+ {(char *)"smooth",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_smooth_doc,
+ (void *)BM_ELEM_SMOOTH},
+
+ {(char *)"normal",
+ (getter)bpy_bmface_normal_get,
+ (setter)bpy_bmface_normal_set,
+ (char *)bpy_bmface_normal_doc,
+ NULL},
+
+ {(char *)"material_index",
+ (getter)bpy_bmface_material_index_get,
+ (setter)bpy_bmface_material_index_set,
+ (char *)bpy_bmface_material_index_doc,
+ NULL},
+
+ /* connectivity data */
+ {(char *)"verts",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmface_verts_doc,
+ (void *)BM_VERTS_OF_FACE},
+ {(char *)"edges",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmface_edges_doc,
+ (void *)BM_EDGES_OF_FACE},
+ {(char *)"loops",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmface_loops_doc,
+ (void *)BM_LOOPS_OF_FACE},
+
+ /* readonly checks */
+ {(char *)"is_valid",
+ (getter)bpy_bm_is_valid_get,
+ (setter)NULL,
+ (char *)bpy_bm_is_valid_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmloop_getseters[] = {
- /* generic */
- /* flags are available but not used for loops. */
- // {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
- // {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
- {(char *)"tag", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_tag_doc, (void *)BM_ELEM_TAG},
- {(char *)"index", (getter)bpy_bm_elem_index_get, (setter)bpy_bm_elem_index_set, (char *)bpy_bm_elem_index_doc, NULL},
-
- {(char *)"vert", (getter)bpy_bmloop_vert_get, (setter)NULL, (char *)bpy_bmloop_vert_doc, NULL},
- {(char *)"edge", (getter)bpy_bmloop_edge_get, (setter)NULL, (char *)bpy_bmloop_edge_doc, NULL},
- {(char *)"face", (getter)bpy_bmloop_face_get, (setter)NULL, (char *)bpy_bmloop_face_doc, NULL},
-
- /* connectivity data */
- {(char *)"link_loops", (getter)bpy_bmelemseq_elem_get, (setter)NULL, (char *)bpy_bmloops_link_loops_doc, (void *)BM_LOOPS_OF_LOOP},
- {(char *)"link_loop_next", (getter)bpy_bmloop_link_loop_next_get, (setter)NULL, (char *)bpy_bmloop_link_loop_next_doc, NULL},
- {(char *)"link_loop_prev", (getter)bpy_bmloop_link_loop_prev_get, (setter)NULL, (char *)bpy_bmloop_link_loop_prev_doc, NULL},
- {(char *)"link_loop_radial_next", (getter)bpy_bmloop_link_loop_radial_next_get, (setter)NULL, (char *)bpy_bmloop_link_loop_radial_next_doc, NULL},
- {(char *)"link_loop_radial_prev", (getter)bpy_bmloop_link_loop_radial_prev_get, (setter)NULL, (char *)bpy_bmloop_link_loop_radial_prev_doc, NULL},
-
- /* readonly checks */
- {(char *)"is_convex", (getter)bpy_bmloop_is_convex_get, (setter)NULL, (char *)bpy_bmloop_is_convex_doc, NULL},
- {(char *)"is_valid", (getter)bpy_bm_is_valid_get, (setter)NULL, (char *)bpy_bm_is_valid_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* generic */
+ /* flags are available but not used for loops. */
+ // {(char *)"select", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_select_doc, (void *)BM_ELEM_SELECT},
+ // {(char *)"hide", (getter)bpy_bm_elem_hflag_get, (setter)bpy_bm_elem_hflag_set, (char *)bpy_bm_elem_hide_doc, (void *)BM_ELEM_HIDDEN},
+ {(char *)"tag",
+ (getter)bpy_bm_elem_hflag_get,
+ (setter)bpy_bm_elem_hflag_set,
+ (char *)bpy_bm_elem_tag_doc,
+ (void *)BM_ELEM_TAG},
+ {(char *)"index",
+ (getter)bpy_bm_elem_index_get,
+ (setter)bpy_bm_elem_index_set,
+ (char *)bpy_bm_elem_index_doc,
+ NULL},
+
+ {(char *)"vert", (getter)bpy_bmloop_vert_get, (setter)NULL, (char *)bpy_bmloop_vert_doc, NULL},
+ {(char *)"edge", (getter)bpy_bmloop_edge_get, (setter)NULL, (char *)bpy_bmloop_edge_doc, NULL},
+ {(char *)"face", (getter)bpy_bmloop_face_get, (setter)NULL, (char *)bpy_bmloop_face_doc, NULL},
+
+ /* connectivity data */
+ {(char *)"link_loops",
+ (getter)bpy_bmelemseq_elem_get,
+ (setter)NULL,
+ (char *)bpy_bmloops_link_loops_doc,
+ (void *)BM_LOOPS_OF_LOOP},
+ {(char *)"link_loop_next",
+ (getter)bpy_bmloop_link_loop_next_get,
+ (setter)NULL,
+ (char *)bpy_bmloop_link_loop_next_doc,
+ NULL},
+ {(char *)"link_loop_prev",
+ (getter)bpy_bmloop_link_loop_prev_get,
+ (setter)NULL,
+ (char *)bpy_bmloop_link_loop_prev_doc,
+ NULL},
+ {(char *)"link_loop_radial_next",
+ (getter)bpy_bmloop_link_loop_radial_next_get,
+ (setter)NULL,
+ (char *)bpy_bmloop_link_loop_radial_next_doc,
+ NULL},
+ {(char *)"link_loop_radial_prev",
+ (getter)bpy_bmloop_link_loop_radial_prev_get,
+ (setter)NULL,
+ (char *)bpy_bmloop_link_loop_radial_prev_doc,
+ NULL},
+
+ /* readonly checks */
+ {(char *)"is_convex",
+ (getter)bpy_bmloop_is_convex_get,
+ (setter)NULL,
+ (char *)bpy_bmloop_is_convex_doc,
+ NULL},
+ {(char *)"is_valid",
+ (getter)bpy_bm_is_valid_get,
+ (setter)NULL,
+ (char *)bpy_bm_is_valid_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmvertseq_getseters[] = {
- {(char *)"layers", (getter)bpy_bmelemseq_layers_get, (setter)NULL, (char *)bpy_bmelemseq_layers_vert_doc, (void *)BM_VERT},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"layers",
+ (getter)bpy_bmelemseq_layers_get,
+ (setter)NULL,
+ (char *)bpy_bmelemseq_layers_vert_doc,
+ (void *)BM_VERT},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmedgeseq_getseters[] = {
- {(char *)"layers", (getter)bpy_bmelemseq_layers_get, (setter)NULL, (char *)bpy_bmelemseq_layers_edge_doc, (void *)BM_EDGE},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"layers",
+ (getter)bpy_bmelemseq_layers_get,
+ (setter)NULL,
+ (char *)bpy_bmelemseq_layers_edge_doc,
+ (void *)BM_EDGE},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmfaceseq_getseters[] = {
- {(char *)"layers", (getter)bpy_bmelemseq_layers_get, (setter)NULL, (char *)bpy_bmelemseq_layers_face_doc, (void *)BM_FACE},
- /* face only */
- {(char *)"active", (getter)bpy_bmfaceseq_active_get, (setter)bpy_bmfaceseq_active_set, (char *)bpy_bmfaceseq_active_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"layers",
+ (getter)bpy_bmelemseq_layers_get,
+ (setter)NULL,
+ (char *)bpy_bmelemseq_layers_face_doc,
+ (void *)BM_FACE},
+ /* face only */
+ {(char *)"active",
+ (getter)bpy_bmfaceseq_active_get,
+ (setter)bpy_bmfaceseq_active_set,
+ (char *)bpy_bmfaceseq_active_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmloopseq_getseters[] = {
- {(char *)"layers", (getter)bpy_bmelemseq_layers_get, (setter)NULL, (char *)bpy_bmelemseq_layers_loop_doc, (void *)BM_LOOP},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"layers",
+ (getter)bpy_bmelemseq_layers_get,
+ (setter)NULL,
+ (char *)bpy_bmelemseq_layers_loop_doc,
+ (void *)BM_LOOP},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
/* Methods
* ======= */
-
/* Mesh
* ---- */
PyDoc_STRVAR(bpy_bmesh_copy_doc,
-".. method:: copy()\n"
-"\n"
-" :return: A copy of this BMesh.\n"
-" :rtype: :class:`BMesh`\n"
-);
+ ".. method:: copy()\n"
+ "\n"
+ " :return: A copy of this BMesh.\n"
+ " :rtype: :class:`BMesh`\n");
static PyObject *bpy_bmesh_copy(BPy_BMesh *self)
{
- BMesh *bm;
- BMesh *bm_copy;
+ BMesh *bm;
+ BMesh *bm_copy;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- bm = self->bm;
+ bm = self->bm;
- bm_copy = BM_mesh_copy(bm);
+ bm_copy = BM_mesh_copy(bm);
- if (bm_copy) {
- return BPy_BMesh_CreatePyObject(bm_copy, BPY_BMFLAG_NOP);
- }
- else {
- PyErr_SetString(PyExc_SystemError, "Unable to copy BMesh, internal error");
- return NULL;
- }
+ if (bm_copy) {
+ return BPy_BMesh_CreatePyObject(bm_copy, BPY_BMFLAG_NOP);
+ }
+ else {
+ PyErr_SetString(PyExc_SystemError, "Unable to copy BMesh, internal error");
+ return NULL;
+ }
}
PyDoc_STRVAR(bpy_bmesh_clear_doc,
-".. method:: clear()\n"
-"\n"
-" Clear all mesh data.\n"
-);
+ ".. method:: clear()\n"
+ "\n"
+ " Clear all mesh data.\n");
static PyObject *bpy_bmesh_clear(BPy_BMesh *self)
{
- BMesh *bm;
+ BMesh *bm;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- bm = self->bm;
+ bm = self->bm;
- BM_mesh_clear(bm);
+ BM_mesh_clear(bm);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpy_bmesh_free_doc,
-".. method:: free()\n"
-"\n"
-" Explicitly free the BMesh data from memory, causing exceptions on further access.\n"
-"\n"
-" .. note::\n"
-"\n"
-" The BMesh is freed automatically, typically when the script finishes executing.\n"
-" However in some cases its hard to predict when this will be and its useful to\n"
-" explicitly free the data.\n"
-);
+PyDoc_STRVAR(
+ bpy_bmesh_free_doc,
+ ".. method:: free()\n"
+ "\n"
+ " Explicitly free the BMesh data from memory, causing exceptions on further access.\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " The BMesh is freed automatically, typically when the script finishes executing.\n"
+ " However in some cases its hard to predict when this will be and its useful to\n"
+ " explicitly free the data.\n");
static PyObject *bpy_bmesh_free(BPy_BMesh *self)
{
- if (self->bm) {
- BMesh *bm = self->bm;
+ if (self->bm) {
+ BMesh *bm = self->bm;
- bm_dealloc_editmode_warn(self);
+ bm_dealloc_editmode_warn(self);
- if ((self->flag & BPY_BMFLAG_IS_WRAPPED) == 0) {
- BM_mesh_free(bm);
- }
+ if ((self->flag & BPY_BMFLAG_IS_WRAPPED) == 0) {
+ BM_mesh_free(bm);
+ }
- bpy_bm_generic_invalidate((BPy_BMGeneric *)self);
- }
+ bpy_bm_generic_invalidate((BPy_BMGeneric *)self);
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bmesh_to_mesh_doc,
-".. method:: to_mesh(mesh)\n"
-"\n"
-" Writes this BMesh data into an existing Mesh datablock.\n"
-"\n"
-" :arg mesh: The mesh data to write into.\n"
-" :type mesh: :class:`Mesh`\n"
-);
+ ".. method:: to_mesh(mesh)\n"
+ "\n"
+ " Writes this BMesh data into an existing Mesh datablock.\n"
+ "\n"
+ " :arg mesh: The mesh data to write into.\n"
+ " :type mesh: :class:`Mesh`\n");
static PyObject *bpy_bmesh_to_mesh(BPy_BMesh *self, PyObject *args)
{
- PyObject *py_mesh;
- Mesh *me;
- BMesh *bm;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "O:to_mesh", &py_mesh) ||
- !(me = PyC_RNA_AsPointer(py_mesh, "Mesh")))
- {
- return NULL;
- }
-
- /* we could allow this but its almost certainly _not_ what script authors want */
- if (me->edit_mesh) {
- PyErr_Format(PyExc_ValueError,
- "to_mesh(): Mesh '%s' is in editmode", me->id.name + 2);
- return NULL;
- }
-
- bm = self->bm;
-
- BLI_assert(BKE_id_is_in_global_main(&me->id));
- BM_mesh_bm_to_me(
- G_MAIN, /* XXX UGLY! */
- bm, me,
- (&(struct BMeshToMeshParams){
- .calc_object_remap = true,
- }));
-
- /* we could have the user do this but if they forget blender can easy crash
- * since the references arrays for the objects derived meshes are now invalid */
- DEG_id_tag_update(&me->id, ID_RECALC_GEOMETRY);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(bpy_bmesh_from_object_doc,
-".. method:: from_object(object, depsgraph, deform=True, cage=False, face_normals=True)\n"
-"\n"
-" Initialize this bmesh from existing object datablock (currently only meshes are supported).\n"
-"\n"
-" :arg object: The object data to load.\n"
-" :type object: :class:`Object`\n"
-" :arg deform: Apply deformation modifiers.\n"
-" :type deform: boolean\n"
-" :arg cage: Get the mesh as a deformed cage.\n"
-" :type cage: boolean\n"
-" :arg face_normals: Calculate face normals.\n"
-" :type face_normals: boolean\n"
-);
+ PyObject *py_mesh;
+ Mesh *me;
+ BMesh *bm;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "O:to_mesh", &py_mesh) ||
+ !(me = PyC_RNA_AsPointer(py_mesh, "Mesh"))) {
+ return NULL;
+ }
+
+ /* we could allow this but its almost certainly _not_ what script authors want */
+ if (me->edit_mesh) {
+ PyErr_Format(PyExc_ValueError, "to_mesh(): Mesh '%s' is in editmode", me->id.name + 2);
+ return NULL;
+ }
+
+ bm = self->bm;
+
+ BLI_assert(BKE_id_is_in_global_main(&me->id));
+ BM_mesh_bm_to_me(G_MAIN, /* XXX UGLY! */
+ bm,
+ me,
+ (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
+
+ /* we could have the user do this but if they forget blender can easy crash
+ * since the references arrays for the objects derived meshes are now invalid */
+ DEG_id_tag_update(&me->id, ID_RECALC_GEOMETRY);
+
+ Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(
+ bpy_bmesh_from_object_doc,
+ ".. method:: from_object(object, depsgraph, deform=True, cage=False, face_normals=True)\n"
+ "\n"
+ " Initialize this bmesh from existing object datablock (currently only meshes are "
+ "supported).\n"
+ "\n"
+ " :arg object: The object data to load.\n"
+ " :type object: :class:`Object`\n"
+ " :arg deform: Apply deformation modifiers.\n"
+ " :type deform: boolean\n"
+ " :arg cage: Get the mesh as a deformed cage.\n"
+ " :type cage: boolean\n"
+ " :arg face_normals: Calculate face normals.\n"
+ " :type face_normals: boolean\n");
static PyObject *bpy_bmesh_from_object(BPy_BMesh *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"object", "depsgraph", "deform", "cage", "face_normals", NULL};
- PyObject *py_object;
- PyObject *py_depsgraph;
- Object *ob, *ob_eval;
- struct Depsgraph *depsgraph;
- struct Scene *scene_eval;
- Mesh *me_eval;
- BMesh *bm;
- bool use_deform = true;
- bool use_cage = false;
- bool use_fnorm = true;
- CustomData_MeshMasks data_masks = CD_MASK_BMESH;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "OO|O&O&O&:from_object", (char **)kwlist,
- &py_object, &py_depsgraph,
- PyC_ParseBool, &use_deform,
- PyC_ParseBool, &use_cage,
- PyC_ParseBool, &use_fnorm) ||
- !(ob = PyC_RNA_AsPointer(py_object, "Object")) ||
- !(depsgraph = PyC_RNA_AsPointer(py_depsgraph, "Depsgraph")))
- {
- return NULL;
- }
-
- if (ob->type != OB_MESH) {
- PyErr_SetString(PyExc_ValueError,
- "from_object(...): currently only mesh objects are supported");
- return NULL;
- }
-
- const bool use_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER;
- scene_eval = DEG_get_evaluated_scene(depsgraph);
- ob_eval = DEG_get_evaluated_object(depsgraph, ob);
-
- /* Write the display mesh into the dummy mesh */
- if (use_deform) {
- if (use_render) {
- if (use_cage) {
- PyErr_SetString(PyExc_ValueError,
- "from_object(...): cage arg is unsupported when dependency graph evaluation mode is RENDER");
- return NULL;
- }
- else {
- me_eval = mesh_create_eval_final_render(depsgraph, scene_eval, ob_eval, &data_masks);
- }
- }
- else {
- if (use_cage) {
- me_eval = mesh_get_eval_deform(depsgraph, scene_eval, ob_eval, &data_masks);
- }
- else {
- me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &data_masks);
- }
- }
- }
- else {
- /* !use_deform */
- if (use_cage) {
- PyErr_SetString(PyExc_ValueError,
- "from_object(...): cage arg is unsupported when deform=False");
- return NULL;
- }
- else if (use_render) {
- me_eval = mesh_create_eval_no_deform_render(depsgraph, scene_eval, ob, &data_masks);
- }
- else {
- me_eval = mesh_create_eval_no_deform(depsgraph, scene_eval, ob, &data_masks);
- }
- }
-
- if (me_eval == NULL) {
- PyErr_Format(PyExc_ValueError,
- "from_object(...): Object '%s' has no usable mesh data", ob->id.name + 2);
- return NULL;
- }
-
- bm = self->bm;
-
- BM_mesh_bm_from_me(
- bm, me_eval, (&(struct BMeshFromMeshParams){
- .calc_face_normal = use_fnorm,
- }));
-
- Py_RETURN_NONE;
-}
-
-
-PyDoc_STRVAR(bpy_bmesh_from_mesh_doc,
-".. method:: from_mesh(mesh, face_normals=True, use_shape_key=False, shape_key_index=0)\n"
-"\n"
-" Initialize this bmesh from existing mesh datablock.\n"
-"\n"
-" :arg mesh: The mesh data to load.\n"
-" :type mesh: :class:`Mesh`\n"
-" :arg use_shape_key: Use the locations from a shape key.\n"
-" :type use_shape_key: boolean\n"
-" :arg shape_key_index: The shape key index to use.\n"
-" :type shape_key_index: int\n"
-"\n"
-" .. note::\n"
-"\n"
-" Multiple calls can be used to join multiple meshes.\n"
-"\n"
-" Custom-data layers are only copied from ``mesh`` on initialization.\n"
-" Further calls will copy custom-data to matching layers, layers missing on the target mesh wont be added.\n"
-);
+ static const char *kwlist[] = {"object", "depsgraph", "deform", "cage", "face_normals", NULL};
+ PyObject *py_object;
+ PyObject *py_depsgraph;
+ Object *ob, *ob_eval;
+ struct Depsgraph *depsgraph;
+ struct Scene *scene_eval;
+ Mesh *me_eval;
+ BMesh *bm;
+ bool use_deform = true;
+ bool use_cage = false;
+ bool use_fnorm = true;
+ CustomData_MeshMasks data_masks = CD_MASK_BMESH;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "OO|O&O&O&:from_object",
+ (char **)kwlist,
+ &py_object,
+ &py_depsgraph,
+ PyC_ParseBool,
+ &use_deform,
+ PyC_ParseBool,
+ &use_cage,
+ PyC_ParseBool,
+ &use_fnorm) ||
+ !(ob = PyC_RNA_AsPointer(py_object, "Object")) ||
+ !(depsgraph = PyC_RNA_AsPointer(py_depsgraph, "Depsgraph"))) {
+ return NULL;
+ }
+
+ if (ob->type != OB_MESH) {
+ PyErr_SetString(PyExc_ValueError,
+ "from_object(...): currently only mesh objects are supported");
+ return NULL;
+ }
+
+ const bool use_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER;
+ scene_eval = DEG_get_evaluated_scene(depsgraph);
+ ob_eval = DEG_get_evaluated_object(depsgraph, ob);
+
+ /* Write the display mesh into the dummy mesh */
+ if (use_deform) {
+ if (use_render) {
+ if (use_cage) {
+ PyErr_SetString(PyExc_ValueError,
+ "from_object(...): cage arg is unsupported when dependency graph "
+ "evaluation mode is RENDER");
+ return NULL;
+ }
+ else {
+ me_eval = mesh_create_eval_final_render(depsgraph, scene_eval, ob_eval, &data_masks);
+ }
+ }
+ else {
+ if (use_cage) {
+ me_eval = mesh_get_eval_deform(depsgraph, scene_eval, ob_eval, &data_masks);
+ }
+ else {
+ me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &data_masks);
+ }
+ }
+ }
+ else {
+ /* !use_deform */
+ if (use_cage) {
+ PyErr_SetString(PyExc_ValueError,
+ "from_object(...): cage arg is unsupported when deform=False");
+ return NULL;
+ }
+ else if (use_render) {
+ me_eval = mesh_create_eval_no_deform_render(depsgraph, scene_eval, ob, &data_masks);
+ }
+ else {
+ me_eval = mesh_create_eval_no_deform(depsgraph, scene_eval, ob, &data_masks);
+ }
+ }
+
+ if (me_eval == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "from_object(...): Object '%s' has no usable mesh data",
+ ob->id.name + 2);
+ return NULL;
+ }
+
+ bm = self->bm;
+
+ BM_mesh_bm_from_me(bm,
+ me_eval,
+ (&(struct BMeshFromMeshParams){
+ .calc_face_normal = use_fnorm,
+ }));
+
+ Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(
+ bpy_bmesh_from_mesh_doc,
+ ".. method:: from_mesh(mesh, face_normals=True, use_shape_key=False, shape_key_index=0)\n"
+ "\n"
+ " Initialize this bmesh from existing mesh datablock.\n"
+ "\n"
+ " :arg mesh: The mesh data to load.\n"
+ " :type mesh: :class:`Mesh`\n"
+ " :arg use_shape_key: Use the locations from a shape key.\n"
+ " :type use_shape_key: boolean\n"
+ " :arg shape_key_index: The shape key index to use.\n"
+ " :type shape_key_index: int\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " Multiple calls can be used to join multiple meshes.\n"
+ "\n"
+ " Custom-data layers are only copied from ``mesh`` on initialization.\n"
+ " Further calls will copy custom-data to matching layers, layers missing on the target "
+ "mesh wont be added.\n");
static PyObject *bpy_bmesh_from_mesh(BPy_BMesh *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"mesh", "face_normals", "use_shape_key", "shape_key_index", NULL};
- BMesh *bm;
- PyObject *py_mesh;
- Mesh *me;
- bool use_fnorm = true;
- bool use_shape_key = false;
- int shape_key_index = 0;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "O|O&O&i:from_mesh", (char **)kwlist,
- &py_mesh,
- PyC_ParseBool, &use_fnorm,
- PyC_ParseBool, &use_shape_key,
- &shape_key_index) ||
- !(me = PyC_RNA_AsPointer(py_mesh, "Mesh")))
- {
- return NULL;
- }
-
- bm = self->bm;
-
- BM_mesh_bm_from_me(
- bm, me, (&(struct BMeshFromMeshParams){
- .calc_face_normal = use_fnorm, .use_shapekey = use_shape_key, .active_shapekey = shape_key_index + 1,
- }));
-
- Py_RETURN_NONE;
+ static const char *kwlist[] = {"mesh", "face_normals", "use_shape_key", "shape_key_index", NULL};
+ BMesh *bm;
+ PyObject *py_mesh;
+ Mesh *me;
+ bool use_fnorm = true;
+ bool use_shape_key = false;
+ int shape_key_index = 0;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O|O&O&i:from_mesh",
+ (char **)kwlist,
+ &py_mesh,
+ PyC_ParseBool,
+ &use_fnorm,
+ PyC_ParseBool,
+ &use_shape_key,
+ &shape_key_index) ||
+ !(me = PyC_RNA_AsPointer(py_mesh, "Mesh"))) {
+ return NULL;
+ }
+
+ bm = self->bm;
+
+ BM_mesh_bm_from_me(bm,
+ me,
+ (&(struct BMeshFromMeshParams){
+ .calc_face_normal = use_fnorm,
+ .use_shapekey = use_shape_key,
+ .active_shapekey = shape_key_index + 1,
+ }));
+
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmesh_select_flush_mode_doc,
-".. method:: select_flush_mode()\n"
-"\n"
-" flush selection based on the current mode current :class:`BMesh.select_mode`.\n"
-);
+ ".. method:: select_flush_mode()\n"
+ "\n"
+ " flush selection based on the current mode current :class:`BMesh.select_mode`.\n");
static PyObject *bpy_bmesh_select_flush_mode(BPy_BMesh *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_mesh_select_mode_flush(self->bm);
+ BM_mesh_select_mode_flush(self->bm);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmesh_select_flush_doc,
-".. method:: select_flush(select)\n"
-"\n"
-" Flush selection, independent of the current selection mode.\n"
-"\n"
-" :arg select: flush selection or de-selected elements.\n"
-" :type select: boolean\n"
-);
+ ".. method:: select_flush(select)\n"
+ "\n"
+ " Flush selection, independent of the current selection mode.\n"
+ "\n"
+ " :arg select: flush selection or de-selected elements.\n"
+ " :type select: boolean\n");
static PyObject *bpy_bmesh_select_flush(BPy_BMesh *self, PyObject *value)
{
- int param;
+ int param;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if ((param = PyC_Long_AsBool(value)) == -1) {
- return NULL;
- }
+ if ((param = PyC_Long_AsBool(value)) == -1) {
+ return NULL;
+ }
- if (param) {
- BM_mesh_select_flush(self->bm);
- }
- else {
- BM_mesh_deselect_flush(self->bm);
- }
+ if (param) {
+ BM_mesh_select_flush(self->bm);
+ }
+ else {
+ BM_mesh_deselect_flush(self->bm);
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmesh_normal_update_doc,
-".. method:: normal_update()\n"
-"\n"
-" Update mesh normals.\n"
-);
+ ".. method:: normal_update()\n"
+ "\n"
+ " Update mesh normals.\n");
static PyObject *bpy_bmesh_normal_update(BPy_BMesh *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_mesh_normals_update(self->bm);
+ BM_mesh_normals_update(self->bm);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmesh_transform_doc,
-".. method:: transform(matrix, filter=None)\n"
-"\n"
-" Transform the mesh (optionally filtering flagged data only).\n"
-"\n"
-" :arg matrix: transform matrix.\n"
-" :type matrix: 4x4 :class:`mathutils.Matrix`\n"
-" :arg filter: set of values in " BPY_BM_HFLAG_ALL_STR ".\n"
-" :type filter: set\n"
-);
+ ".. method:: transform(matrix, filter=None)\n"
+ "\n"
+ " Transform the mesh (optionally filtering flagged data only).\n"
+ "\n"
+ " :arg matrix: transform matrix.\n"
+ " :type matrix: 4x4 :class:`mathutils.Matrix`\n"
+ " :arg filter: set of values in " BPY_BM_HFLAG_ALL_STR
+ ".\n"
+ " :type filter: set\n");
static PyObject *bpy_bmesh_transform(BPy_BMElem *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"matrix", "filter", NULL};
-
- MatrixObject *mat;
- PyObject *filter = NULL;
- int filter_flags = 0;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "O!|O!:transform",
- (char **)kwlist,
- &matrix_Type, &mat,
- &PySet_Type, &filter))
- {
- return NULL;
- }
- else {
- BMVert *eve;
- BMIter iter;
- void *mat_ptr;
-
- if (BaseMath_ReadCallback(mat) == -1) {
- return NULL;
- }
- else if (mat->num_col != 4 || mat->num_row != 4) {
- PyErr_SetString(PyExc_ValueError,
- "expected a 4x4 matrix");
- return NULL;
- }
-
- if (filter != NULL && PyC_FlagSet_ToBitfield(bpy_bm_hflag_all_flags, filter,
- &filter_flags, "bm.transform") == -1)
- {
- return NULL;
- }
-
- mat_ptr = mat->matrix;
-
- if (!filter_flags) {
- BM_ITER_MESH (eve, &iter, self->bm, BM_VERTS_OF_MESH) {
- mul_m4_v3((float (*)[4])mat_ptr, eve->co);
- }
- }
- else {
- char filter_flags_ch = (char)filter_flags;
- BM_ITER_MESH (eve, &iter, self->bm, BM_VERTS_OF_MESH) {
- if (BM_elem_flag_test(eve, filter_flags_ch)) {
- mul_m4_v3((float (*)[4])mat_ptr, eve->co);
- }
- }
- }
- }
-
- Py_RETURN_NONE;
+ static const char *kwlist[] = {"matrix", "filter", NULL};
+
+ MatrixObject *mat;
+ PyObject *filter = NULL;
+ int filter_flags = 0;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O!|O!:transform",
+ (char **)kwlist,
+ &matrix_Type,
+ &mat,
+ &PySet_Type,
+ &filter)) {
+ return NULL;
+ }
+ else {
+ BMVert *eve;
+ BMIter iter;
+ void *mat_ptr;
+
+ if (BaseMath_ReadCallback(mat) == -1) {
+ return NULL;
+ }
+ else if (mat->num_col != 4 || mat->num_row != 4) {
+ PyErr_SetString(PyExc_ValueError, "expected a 4x4 matrix");
+ return NULL;
+ }
+
+ if (filter != NULL &&
+ PyC_FlagSet_ToBitfield(bpy_bm_hflag_all_flags, filter, &filter_flags, "bm.transform") ==
+ -1) {
+ return NULL;
+ }
+
+ mat_ptr = mat->matrix;
+
+ if (!filter_flags) {
+ BM_ITER_MESH (eve, &iter, self->bm, BM_VERTS_OF_MESH) {
+ mul_m4_v3((float(*)[4])mat_ptr, eve->co);
+ }
+ }
+ else {
+ char filter_flags_ch = (char)filter_flags;
+ BM_ITER_MESH (eve, &iter, self->bm, BM_VERTS_OF_MESH) {
+ if (BM_elem_flag_test(eve, filter_flags_ch)) {
+ mul_m4_v3((float(*)[4])mat_ptr, eve->co);
+ }
+ }
+ }
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bmesh_calc_volume_doc,
-".. method:: calc_volume(signed=False)\n"
-"\n"
-" Calculate mesh volume based on face normals.\n"
-"\n"
-" :arg signed: when signed is true, negative values may be returned.\n"
-" :type signed: bool\n"
-" :return: The volume of the mesh.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_volume(signed=False)\n"
+ "\n"
+ " Calculate mesh volume based on face normals.\n"
+ "\n"
+ " :arg signed: when signed is true, negative values may be returned.\n"
+ " :type signed: bool\n"
+ " :return: The volume of the mesh.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmesh_calc_volume(BPy_BMElem *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"signed", NULL};
- PyObject *is_signed = Py_False;
+ static const char *kwlist[] = {"signed", NULL};
+ PyObject *is_signed = Py_False;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "|O!:calc_volume",
- (char **)kwlist,
- &PyBool_Type, &is_signed))
- {
- return NULL;
- }
- else {
- return PyFloat_FromDouble(BM_mesh_calc_volume(self->bm, is_signed != Py_False));
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "|O!:calc_volume", (char **)kwlist, &PyBool_Type, &is_signed)) {
+ return NULL;
+ }
+ else {
+ return PyFloat_FromDouble(BM_mesh_calc_volume(self->bm, is_signed != Py_False));
+ }
}
PyDoc_STRVAR(bpy_bmesh_calc_loop_triangles_doc,
-".. method:: calc_loop_triangles()\n"
-"\n"
-" Calculate triangle tessellation from quads/ngons.\n"
-"\n"
-" :return: The triangulated faces.\n"
-" :rtype: list of :class:`BMLoop` tuples\n"
-);
+ ".. method:: calc_loop_triangles()\n"
+ "\n"
+ " Calculate triangle tessellation from quads/ngons.\n"
+ "\n"
+ " :return: The triangulated faces.\n"
+ " :rtype: list of :class:`BMLoop` tuples\n");
static PyObject *bpy_bmesh_calc_loop_triangles(BPy_BMElem *self)
{
- BMesh *bm;
+ BMesh *bm;
- int looptris_tot;
- int tottri;
- BMLoop *(*looptris)[3];
+ int looptris_tot;
+ int tottri;
+ BMLoop *(*looptris)[3];
- PyObject *ret;
- int i;
+ PyObject *ret;
+ int i;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- bm = self->bm;
+ bm = self->bm;
- looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
- looptris = PyMem_MALLOC(sizeof(*looptris) * looptris_tot);
+ looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
+ looptris = PyMem_MALLOC(sizeof(*looptris) * looptris_tot);
- BM_mesh_calc_tessellation(bm, looptris, &tottri);
+ BM_mesh_calc_tessellation(bm, looptris, &tottri);
- ret = PyList_New(tottri);
- for (i = 0; i < tottri; i++) {
- PyList_SET_ITEM(ret, i, BPy_BMLoop_Array_As_Tuple(bm, looptris[i], 3));
- }
+ ret = PyList_New(tottri);
+ for (i = 0; i < tottri; i++) {
+ PyList_SET_ITEM(ret, i, BPy_BMLoop_Array_As_Tuple(bm, looptris[i], 3));
+ }
- PyMem_FREE(looptris);
+ PyMem_FREE(looptris);
- return ret;
+ return ret;
}
-
/* Elem
* ---- */
PyDoc_STRVAR(bpy_bm_elem_select_set_doc,
-".. method:: select_set(select)\n"
-"\n"
-" Set the selection.\n"
-" This is different from the *select* attribute because it updates the selection state of associated geometry.\n"
-"\n"
-" :arg select: Select or de-select.\n"
-" :type select: boolean\n"
-"\n"
-" .. note::\n"
-"\n"
-" Currently this only flushes down, so selecting a face will select all its vertices but de-selecting a vertex "
-" won't de-select all the faces that use it, before finishing with a mesh typically flushing is still needed.\n"
-);
+ ".. method:: select_set(select)\n"
+ "\n"
+ " Set the selection.\n"
+ " This is different from the *select* attribute because it updates the selection "
+ "state of associated geometry.\n"
+ "\n"
+ " :arg select: Select or de-select.\n"
+ " :type select: boolean\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " Currently this only flushes down, so selecting a face will select all its "
+ "vertices but de-selecting a vertex "
+ " won't de-select all the faces that use it, before finishing with a mesh "
+ "typically flushing is still needed.\n");
static PyObject *bpy_bm_elem_select_set(BPy_BMElem *self, PyObject *value)
{
- int param;
+ int param;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if ((param = PyC_Long_AsBool(value)) == -1) {
- return NULL;
- }
+ if ((param = PyC_Long_AsBool(value)) == -1) {
+ return NULL;
+ }
- BM_elem_select_set(self->bm, self->ele, param);
+ BM_elem_select_set(self->bm, self->ele, param);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bm_elem_hide_set_doc,
-".. method:: hide_set(hide)\n"
-"\n"
-" Set the hide state.\n"
-" This is different from the *hide* attribute because it updates the selection and hide state of associated geometry.\n"
-"\n"
-" :arg hide: Hidden or visible.\n"
-" :type hide: boolean\n"
-);
+ ".. method:: hide_set(hide)\n"
+ "\n"
+ " Set the hide state.\n"
+ " This is different from the *hide* attribute because it updates the selection and "
+ "hide state of associated geometry.\n"
+ "\n"
+ " :arg hide: Hidden or visible.\n"
+ " :type hide: boolean\n");
static PyObject *bpy_bm_elem_hide_set(BPy_BMElem *self, PyObject *value)
{
- int param;
+ int param;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if ((param = PyC_Long_AsBool(value)) == -1) {
- return NULL;
- }
+ if ((param = PyC_Long_AsBool(value)) == -1) {
+ return NULL;
+ }
- BM_elem_hide_set(self->bm, self->ele, param);
+ BM_elem_hide_set(self->bm, self->ele, param);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bm_elem_copy_from_doc,
-".. method:: copy_from(other)\n"
-"\n"
-" Copy values from another element of matching type.\n"
-);
+ ".. method:: copy_from(other)\n"
+ "\n"
+ " Copy values from another element of matching type.\n");
static PyObject *bpy_bm_elem_copy_from(BPy_BMElem *self, BPy_BMElem *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (Py_TYPE(self) != Py_TYPE(value)) {
- PyErr_Format(PyExc_TypeError,
- "expected element of type '%.200s' not '%.200s'",
- Py_TYPE(self)->tp_name, Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if (Py_TYPE(self) != Py_TYPE(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "expected element of type '%.200s' not '%.200s'",
+ Py_TYPE(self)->tp_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- if (value->ele != self->ele) {
- BM_elem_attrs_copy(value->bm, self->bm, value->ele, self->ele);
- }
+ if (value->ele != self->ele) {
+ BM_elem_attrs_copy(value->bm, self->bm, value->ele, self->ele);
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
/* Vert
* ---- */
-
PyDoc_STRVAR(bpy_bmvert_copy_from_vert_interp_doc,
-".. method:: copy_from_vert_interp(vert_pair, fac)\n"
-"\n"
-" Interpolate the customdata from a vert between 2 other verts.\n"
-"\n"
-" :arg vert_pair: The vert to interpolate data from.\n"
-" :type vert_pair: :class:`BMVert`\n"
-);
+ ".. method:: copy_from_vert_interp(vert_pair, fac)\n"
+ "\n"
+ " Interpolate the customdata from a vert between 2 other verts.\n"
+ "\n"
+ " :arg vert_pair: The vert to interpolate data from.\n"
+ " :type vert_pair: :class:`BMVert`\n");
static PyObject *bpy_bmvert_copy_from_vert_interp(BPy_BMVert *self, PyObject *args)
{
- PyObject *vert_seq;
- float fac;
+ PyObject *vert_seq;
+ float fac;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "Of:BMVert.copy_from_vert_interp",
- &vert_seq, &fac))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- BMVert **vert_array = NULL;
- Py_ssize_t vert_seq_len; /* always 2 */
+ if (!PyArg_ParseTuple(args, "Of:BMVert.copy_from_vert_interp", &vert_seq, &fac)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ BMVert **vert_array = NULL;
+ Py_ssize_t vert_seq_len; /* always 2 */
- vert_array = BPy_BMElem_PySeq_As_Array(&bm, vert_seq, 2, 2,
- &vert_seq_len, BM_VERT,
- true, true, "BMVert.copy_from_vert_interp(...)");
+ vert_array = BPy_BMElem_PySeq_As_Array(&bm,
+ vert_seq,
+ 2,
+ 2,
+ &vert_seq_len,
+ BM_VERT,
+ true,
+ true,
+ "BMVert.copy_from_vert_interp(...)");
- if (vert_array == NULL) {
- return NULL;
- }
+ if (vert_array == NULL) {
+ return NULL;
+ }
- BM_data_interp_from_verts(bm, vert_array[0], vert_array[1], self->v, clamp_f(fac, 0.0f, 1.0f));
+ BM_data_interp_from_verts(bm, vert_array[0], vert_array[1], self->v, clamp_f(fac, 0.0f, 1.0f));
- PyMem_FREE(vert_array);
- Py_RETURN_NONE;
- }
+ PyMem_FREE(vert_array);
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bmvert_copy_from_face_interp_doc,
-".. method:: copy_from_face_interp(face)\n"
-"\n"
-" Interpolate the customdata from a face onto this loop (the loops vert should overlap the face).\n"
-"\n"
-" :arg face: The face to interpolate data from.\n"
-" :type face: :class:`BMFace`\n"
-);
+ ".. method:: copy_from_face_interp(face)\n"
+ "\n"
+ " Interpolate the customdata from a face onto this loop (the loops vert should "
+ "overlap the face).\n"
+ "\n"
+ " :arg face: The face to interpolate data from.\n"
+ " :type face: :class:`BMFace`\n");
static PyObject *bpy_bmvert_copy_from_face_interp(BPy_BMVert *self, PyObject *args)
{
- BPy_BMFace *py_face = NULL;
+ BPy_BMFace *py_face = NULL;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "O!:BMVert.copy_from_face_interp",
- &BPy_BMFace_Type, &py_face))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!PyArg_ParseTuple(args, "O!:BMVert.copy_from_face_interp", &BPy_BMFace_Type, &py_face)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "copy_from_face_interp()", py_face);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "copy_from_face_interp()", py_face);
- BM_vert_interp_from_face(bm, self->v, py_face->f);
+ BM_vert_interp_from_face(bm, self->v, py_face->f);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bmvert_calc_edge_angle_doc,
-".. method:: calc_edge_angle(fallback=None)\n"
-"\n"
-" Return the angle between this vert's two connected edges.\n"
-"\n"
-" :arg fallback: return this when the vert doesn't have 2 edges\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: Angle between edges in radians.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_edge_angle(fallback=None)\n"
+ "\n"
+ " Return the angle between this vert's two connected edges.\n"
+ "\n"
+ " :arg fallback: return this when the vert doesn't have 2 edges\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: Angle between edges in radians.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmvert_calc_edge_angle(BPy_BMVert *self, PyObject *args)
{
- const float angle_invalid = -1.0f;
- float angle;
- PyObject *fallback = NULL;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "|O:calc_edge_angle", &fallback)) {
- return NULL;
- }
-
- angle = BM_vert_calc_edge_angle_ex(self->v, angle_invalid);
-
- if (angle == angle_invalid) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "BMVert.calc_edge_angle(): "
- "vert must connect to exactly 2 edges");
- return NULL;
- }
- }
-
- return PyFloat_FromDouble(angle);
-}
-
-PyDoc_STRVAR(bpy_bmvert_calc_shell_factor_doc,
-".. method:: calc_shell_factor()\n"
-"\n"
-" Return a multiplier calculated based on the sharpness of the vertex.\n"
-" Where a flat surface gives 1.0, and higher values sharper edges.\n"
-" This is used to maintain shell thickness when offsetting verts along their normals.\n"
-"\n"
-" :return: offset multiplier\n"
-" :rtype: float\n"
-);
+ const float angle_invalid = -1.0f;
+ float angle;
+ PyObject *fallback = NULL;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "|O:calc_edge_angle", &fallback)) {
+ return NULL;
+ }
+
+ angle = BM_vert_calc_edge_angle_ex(self->v, angle_invalid);
+
+ if (angle == angle_invalid) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "BMVert.calc_edge_angle(): "
+ "vert must connect to exactly 2 edges");
+ return NULL;
+ }
+ }
+
+ return PyFloat_FromDouble(angle);
+}
+
+PyDoc_STRVAR(
+ bpy_bmvert_calc_shell_factor_doc,
+ ".. method:: calc_shell_factor()\n"
+ "\n"
+ " Return a multiplier calculated based on the sharpness of the vertex.\n"
+ " Where a flat surface gives 1.0, and higher values sharper edges.\n"
+ " This is used to maintain shell thickness when offsetting verts along their normals.\n"
+ "\n"
+ " :return: offset multiplier\n"
+ " :rtype: float\n");
static PyObject *bpy_bmvert_calc_shell_factor(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyFloat_FromDouble(BM_vert_calc_shell_factor(self->v));
+ BPY_BM_CHECK_OBJ(self);
+ return PyFloat_FromDouble(BM_vert_calc_shell_factor(self->v));
}
PyDoc_STRVAR(bpy_bmvert_normal_update_doc,
-".. method:: normal_update()\n"
-"\n"
-" Update vertex normal.\n"
-);
+ ".. method:: normal_update()\n"
+ "\n"
+ " Update vertex normal.\n");
static PyObject *bpy_bmvert_normal_update(BPy_BMVert *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_vert_normal_update(self->v);
+ BM_vert_normal_update(self->v);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
/* Edge
* ---- */
PyDoc_STRVAR(bpy_bmedge_calc_length_doc,
-".. method:: calc_length()\n"
-"\n"
-" :return: The length between both verts.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_length()\n"
+ "\n"
+ " :return: The length between both verts.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmedge_calc_length(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyFloat_FromDouble(len_v3v3(self->e->v1->co, self->e->v2->co));
+ BPY_BM_CHECK_OBJ(self);
+ return PyFloat_FromDouble(len_v3v3(self->e->v1->co, self->e->v2->co));
}
PyDoc_STRVAR(bpy_bmedge_calc_face_angle_doc,
-".. method:: calc_face_angle(fallback=None)\n"
-"\n"
-" :arg fallback: return this when the edge doesn't have 2 faces\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: The angle between 2 connected faces in radians.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_face_angle(fallback=None)\n"
+ "\n"
+ " :arg fallback: return this when the edge doesn't have 2 faces\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: The angle between 2 connected faces in radians.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmedge_calc_face_angle(BPy_BMEdge *self, PyObject *args)
{
- const float angle_invalid = -1.0f;
- float angle;
- PyObject *fallback = NULL;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "|O:calc_face_angle", &fallback)) {
- return NULL;
- }
-
- angle = BM_edge_calc_face_angle_ex(self->e, angle_invalid);
-
- if (angle == angle_invalid) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "BMEdge.calc_face_angle(): "
- "edge doesn't use 2 faces");
- return NULL;
- }
- }
-
- return PyFloat_FromDouble(angle);
-}
-
-PyDoc_STRVAR(bpy_bmedge_calc_face_angle_signed_doc,
-".. method:: calc_face_angle_signed(fallback=None)\n"
-"\n"
-" :arg fallback: return this when the edge doesn't have 2 faces\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: The angle between 2 connected faces in radians (negative for concave join).\n"
-" :rtype: float\n"
-);
+ const float angle_invalid = -1.0f;
+ float angle;
+ PyObject *fallback = NULL;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "|O:calc_face_angle", &fallback)) {
+ return NULL;
+ }
+
+ angle = BM_edge_calc_face_angle_ex(self->e, angle_invalid);
+
+ if (angle == angle_invalid) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "BMEdge.calc_face_angle(): "
+ "edge doesn't use 2 faces");
+ return NULL;
+ }
+ }
+
+ return PyFloat_FromDouble(angle);
+}
+
+PyDoc_STRVAR(
+ bpy_bmedge_calc_face_angle_signed_doc,
+ ".. method:: calc_face_angle_signed(fallback=None)\n"
+ "\n"
+ " :arg fallback: return this when the edge doesn't have 2 faces\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: The angle between 2 connected faces in radians (negative for concave join).\n"
+ " :rtype: float\n");
static PyObject *bpy_bmedge_calc_face_angle_signed(BPy_BMEdge *self, PyObject *args)
{
- const float angle_invalid = -FLT_MAX;
- float angle;
- PyObject *fallback = NULL;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "|O:calc_face_angle_signed", &fallback)) {
- return NULL;
- }
-
- angle = BM_edge_calc_face_angle_signed_ex(self->e, angle_invalid);
-
- if (angle == angle_invalid) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "BMEdge.calc_face_angle_signed(): "
- "edge doesn't use 2 faces");
- return NULL;
- }
- }
-
- return PyFloat_FromDouble(angle);
-}
-
-PyDoc_STRVAR(bpy_bmedge_calc_tangent_doc,
-".. method:: calc_tangent(loop)\n"
-"\n"
-" Return the tangent at this edge relative to a face (pointing inward into the face).\n"
-" This uses the face normal for calculation.\n"
-"\n"
-" :arg loop: The loop used for tangent calculation.\n"
-" :type loop: :class:`BMLoop`\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ const float angle_invalid = -FLT_MAX;
+ float angle;
+ PyObject *fallback = NULL;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "|O:calc_face_angle_signed", &fallback)) {
+ return NULL;
+ }
+
+ angle = BM_edge_calc_face_angle_signed_ex(self->e, angle_invalid);
+
+ if (angle == angle_invalid) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "BMEdge.calc_face_angle_signed(): "
+ "edge doesn't use 2 faces");
+ return NULL;
+ }
+ }
+
+ return PyFloat_FromDouble(angle);
+}
+
+PyDoc_STRVAR(
+ bpy_bmedge_calc_tangent_doc,
+ ".. method:: calc_tangent(loop)\n"
+ "\n"
+ " Return the tangent at this edge relative to a face (pointing inward into the face).\n"
+ " This uses the face normal for calculation.\n"
+ "\n"
+ " :arg loop: The loop used for tangent calculation.\n"
+ " :type loop: :class:`BMLoop`\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmedge_calc_tangent(BPy_BMEdge *self, PyObject *args)
{
- BPy_BMLoop *py_loop;
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "O!:BMEdge.calc_face_tangent",
- &BPy_BMLoop_Type, &py_loop))
- {
- return NULL;
- }
- else {
- float vec[3];
- BPY_BM_CHECK_OBJ(py_loop);
- /* no need to check if they are from the same mesh or even connected */
- BM_edge_calc_face_tangent(self->e, py_loop->l, vec);
- return Vector_CreatePyObject(vec, 3, NULL);
- }
-}
-
-
-PyDoc_STRVAR(bpy_bmedge_other_vert_doc,
-".. method:: other_vert(vert)\n"
-"\n"
-" Return the other vertex on this edge or None if the vertex is not used by this edge.\n"
-"\n"
-" :arg vert: a vert in this edge.\n"
-" :type vert: :class:`BMVert`\n"
-" :return: The edges other vert.\n"
-" :rtype: :class:`BMVert` or None\n"
-);
+ BPy_BMLoop *py_loop;
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "O!:BMEdge.calc_face_tangent", &BPy_BMLoop_Type, &py_loop)) {
+ return NULL;
+ }
+ else {
+ float vec[3];
+ BPY_BM_CHECK_OBJ(py_loop);
+ /* no need to check if they are from the same mesh or even connected */
+ BM_edge_calc_face_tangent(self->e, py_loop->l, vec);
+ return Vector_CreatePyObject(vec, 3, NULL);
+ }
+}
+
+PyDoc_STRVAR(
+ bpy_bmedge_other_vert_doc,
+ ".. method:: other_vert(vert)\n"
+ "\n"
+ " Return the other vertex on this edge or None if the vertex is not used by this edge.\n"
+ "\n"
+ " :arg vert: a vert in this edge.\n"
+ " :type vert: :class:`BMVert`\n"
+ " :return: The edges other vert.\n"
+ " :rtype: :class:`BMVert` or None\n");
static PyObject *bpy_bmedge_other_vert(BPy_BMEdge *self, BPy_BMVert *value)
{
- BMVert *other;
- BPY_BM_CHECK_OBJ(self);
+ BMVert *other;
+ BPY_BM_CHECK_OBJ(self);
- if (!BPy_BMVert_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "BMEdge.other_vert(vert): BMVert expected, not '%.200s'",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if (!BPy_BMVert_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "BMEdge.other_vert(vert): BMVert expected, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_SOURCE_OBJ(self->bm, "BMEdge.other_vert(vert)", value);
+ BPY_BM_CHECK_SOURCE_OBJ(self->bm, "BMEdge.other_vert(vert)", value);
- other = BM_edge_other_vert(self->e, value->v);
+ other = BM_edge_other_vert(self->e, value->v);
- if (other) {
- return BPy_BMVert_CreatePyObject(self->bm, other);
- }
- else {
- /* could raise an exception here */
- Py_RETURN_NONE;
- }
+ if (other) {
+ return BPy_BMVert_CreatePyObject(self->bm, other);
+ }
+ else {
+ /* could raise an exception here */
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bmedge_normal_update_doc,
-".. method:: normal_update()\n"
-"\n"
-" Update edges vertex normals.\n"
-);
+ ".. method:: normal_update()\n"
+ "\n"
+ " Update edges vertex normals.\n");
static PyObject *bpy_bmedge_normal_update(BPy_BMEdge *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_edge_normals_update(self->e);
+ BM_edge_normals_update(self->e);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
/* Face
* ---- */
-PyDoc_STRVAR(bpy_bmface_copy_from_face_interp_doc,
-".. method:: copy_from_face_interp(face, vert=True)\n"
-"\n"
-" Interpolate the customdata from another face onto this one (faces should overlap).\n"
-"\n"
-" :arg face: The face to interpolate data from.\n"
-" :type face: :class:`BMFace`\n"
-" :arg vert: When True, also copy vertex data.\n"
-" :type vert: boolean\n"
-);
+PyDoc_STRVAR(
+ bpy_bmface_copy_from_face_interp_doc,
+ ".. method:: copy_from_face_interp(face, vert=True)\n"
+ "\n"
+ " Interpolate the customdata from another face onto this one (faces should overlap).\n"
+ "\n"
+ " :arg face: The face to interpolate data from.\n"
+ " :type face: :class:`BMFace`\n"
+ " :arg vert: When True, also copy vertex data.\n"
+ " :type vert: boolean\n");
static PyObject *bpy_bmface_copy_from_face_interp(BPy_BMFace *self, PyObject *args)
{
- BPy_BMFace *py_face = NULL;
- bool do_vertex = true;
+ BPy_BMFace *py_face = NULL;
+ bool do_vertex = true;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(
- args, "O!|O&:BMFace.copy_from_face_interp",
- &BPy_BMFace_Type, &py_face,
- PyC_ParseBool, &do_vertex))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!PyArg_ParseTuple(args,
+ "O!|O&:BMFace.copy_from_face_interp",
+ &BPy_BMFace_Type,
+ &py_face,
+ PyC_ParseBool,
+ &do_vertex)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "BMFace.copy_from_face_interp(face)", py_face);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "BMFace.copy_from_face_interp(face)", py_face);
- BM_face_interp_from_face(bm, self->f, py_face->f, do_vertex);
+ BM_face_interp_from_face(bm, self->f, py_face->f, do_vertex);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bmface_copy_doc,
-".. method:: copy(verts=True, edges=True)\n"
-"\n"
-" Make a copy of this face.\n"
-"\n"
-" :arg verts: When set, the faces verts will be duplicated too.\n"
-" :type verts: boolean\n"
-" :arg edges: When set, the faces edges will be duplicated too.\n"
-" :type edges: boolean\n"
-" :return: The newly created face.\n"
-" :rtype: :class:`BMFace`\n"
-);
+ ".. method:: copy(verts=True, edges=True)\n"
+ "\n"
+ " Make a copy of this face.\n"
+ "\n"
+ " :arg verts: When set, the faces verts will be duplicated too.\n"
+ " :type verts: boolean\n"
+ " :arg edges: When set, the faces edges will be duplicated too.\n"
+ " :type edges: boolean\n"
+ " :return: The newly created face.\n"
+ " :rtype: :class:`BMFace`\n");
static PyObject *bpy_bmface_copy(BPy_BMFace *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"verts", "edges", NULL};
+ static const char *kwlist[] = {"verts", "edges", NULL};
- BMesh *bm = self->bm;
- bool do_verts = true;
- bool do_edges = true;
+ BMesh *bm = self->bm;
+ bool do_verts = true;
+ bool do_edges = true;
- BMFace *f_cpy;
- BPY_BM_CHECK_OBJ(self);
+ BMFace *f_cpy;
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTupleAndKeywords(
- args, kw,
- "|O&O&:BMFace.copy", (char **)kwlist,
- PyC_ParseBool, &do_verts,
- PyC_ParseBool, &do_edges))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "|O&O&:BMFace.copy",
+ (char **)kwlist,
+ PyC_ParseBool,
+ &do_verts,
+ PyC_ParseBool,
+ &do_edges)) {
+ return NULL;
+ }
- f_cpy = BM_face_copy(bm, bm, self->f, do_verts, do_edges);
+ f_cpy = BM_face_copy(bm, bm, self->f, do_verts, do_edges);
- if (f_cpy) {
- return BPy_BMFace_CreatePyObject(bm, f_cpy);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "BMFace.copy(): couldn't create the new face, internal error");
- return NULL;
- }
+ if (f_cpy) {
+ return BPy_BMFace_CreatePyObject(bm, f_cpy);
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "BMFace.copy(): couldn't create the new face, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bmface_calc_area_doc,
-".. method:: calc_area()\n"
-"\n"
-" Return the area of the face.\n"
-"\n"
-" :return: Return the area of the face.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_area()\n"
+ "\n"
+ " Return the area of the face.\n"
+ "\n"
+ " :return: Return the area of the face.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmface_calc_area(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyFloat_FromDouble(BM_face_calc_area(self->f));
+ BPY_BM_CHECK_OBJ(self);
+ return PyFloat_FromDouble(BM_face_calc_area(self->f));
}
-
PyDoc_STRVAR(bpy_bmface_calc_perimeter_doc,
-".. method:: calc_perimeter()\n"
-"\n"
-" Return the perimeter of the face.\n"
-"\n"
-" :return: Return the perimeter of the face.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_perimeter()\n"
+ "\n"
+ " Return the perimeter of the face.\n"
+ "\n"
+ " :return: Return the perimeter of the face.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmface_calc_perimeter(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyFloat_FromDouble(BM_face_calc_perimeter(self->f));
+ BPY_BM_CHECK_OBJ(self);
+ return PyFloat_FromDouble(BM_face_calc_perimeter(self->f));
}
-
PyDoc_STRVAR(bpy_bmface_calc_tangent_edge_doc,
-".. method:: calc_tangent_edge()\n"
-"\n"
-" Return face tangent based on longest edge.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_tangent_edge()\n"
+ "\n"
+ " Return face tangent based on longest edge.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_tangent_edge(BPy_BMFace *self)
{
- float tangent[3];
+ float tangent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_tangent_edge(self->f, tangent);
- return Vector_CreatePyObject(tangent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_tangent_edge(self->f, tangent);
+ return Vector_CreatePyObject(tangent, 3, NULL);
}
-
PyDoc_STRVAR(bpy_bmface_calc_tangent_edge_pair_doc,
-".. method:: calc_tangent_edge_pair()\n"
-"\n"
-" Return face tangent based on the two longest disconnected edges.\n"
-"\n"
-" - Tris: Use the edge pair with the most similar lengths.\n"
-" - Quads: Use the longest edge pair.\n"
-" - NGons: Use the two longest disconnected edges.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_tangent_edge_pair()\n"
+ "\n"
+ " Return face tangent based on the two longest disconnected edges.\n"
+ "\n"
+ " - Tris: Use the edge pair with the most similar lengths.\n"
+ " - Quads: Use the longest edge pair.\n"
+ " - NGons: Use the two longest disconnected edges.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_tangent_edge_pair(BPy_BMFace *self)
{
- float tangent[3];
+ float tangent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_tangent_edge_pair(self->f, tangent);
- return Vector_CreatePyObject(tangent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_tangent_edge_pair(self->f, tangent);
+ return Vector_CreatePyObject(tangent, 3, NULL);
}
-
PyDoc_STRVAR(bpy_bmface_calc_tangent_edge_diagonal_doc,
-".. method:: calc_tangent_edge_diagonal()\n"
-"\n"
-" Return face tangent based on the edge farthest from any vertex.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_tangent_edge_diagonal()\n"
+ "\n"
+ " Return face tangent based on the edge farthest from any vertex.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_tangent_edge_diagonal(BPy_BMFace *self)
{
- float tangent[3];
+ float tangent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_tangent_edge_diagonal(self->f, tangent);
- return Vector_CreatePyObject(tangent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_tangent_edge_diagonal(self->f, tangent);
+ return Vector_CreatePyObject(tangent, 3, NULL);
}
-
PyDoc_STRVAR(bpy_bmface_calc_tangent_vert_diagonal_doc,
-".. method:: calc_tangent_vert_diagonal()\n"
-"\n"
-" Return face tangent based on the two most distent vertices.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_tangent_vert_diagonal()\n"
+ "\n"
+ " Return face tangent based on the two most distent vertices.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_tangent_vert_diagonal(BPy_BMFace *self)
{
- float tangent[3];
+ float tangent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_tangent_vert_diagonal(self->f, tangent);
- return Vector_CreatePyObject(tangent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_tangent_vert_diagonal(self->f, tangent);
+ return Vector_CreatePyObject(tangent, 3, NULL);
}
-
PyDoc_STRVAR(bpy_bmface_calc_center_median_doc,
-".. method:: calc_center_median()\n"
-"\n"
-" Return median center of the face.\n"
-"\n"
-" :return: a 3D vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_center_median()\n"
+ "\n"
+ " Return median center of the face.\n"
+ "\n"
+ " :return: a 3D vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_center_mean(BPy_BMFace *self)
{
- float cent[3];
+ float cent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_center_median(self->f, cent);
- return Vector_CreatePyObject(cent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_center_median(self->f, cent);
+ return Vector_CreatePyObject(cent, 3, NULL);
}
PyDoc_STRVAR(bpy_bmface_calc_center_median_weighted_doc,
-".. method:: calc_center_median_weighted()\n"
-"\n"
-" Return median center of the face weighted by edge lengths.\n"
-"\n"
-" :return: a 3D vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_center_median_weighted()\n"
+ "\n"
+ " Return median center of the face weighted by edge lengths.\n"
+ "\n"
+ " :return: a 3D vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_center_median_weighted(BPy_BMFace *self)
{
- float cent[3];
+ float cent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_center_median_weighted(self->f, cent);
- return Vector_CreatePyObject(cent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_center_median_weighted(self->f, cent);
+ return Vector_CreatePyObject(cent, 3, NULL);
}
PyDoc_STRVAR(bpy_bmface_calc_center_bounds_doc,
-".. method:: calc_center_bounds()\n"
-"\n"
-" Return bounds center of the face.\n"
-"\n"
-" :return: a 3D vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_center_bounds()\n"
+ "\n"
+ " Return bounds center of the face.\n"
+ "\n"
+ " :return: a 3D vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmface_calc_center_bounds(BPy_BMFace *self)
{
- float cent[3];
+ float cent[3];
- BPY_BM_CHECK_OBJ(self);
- BM_face_calc_center_bounds(self->f, cent);
- return Vector_CreatePyObject(cent, 3, NULL);
+ BPY_BM_CHECK_OBJ(self);
+ BM_face_calc_center_bounds(self->f, cent);
+ return Vector_CreatePyObject(cent, 3, NULL);
}
-
PyDoc_STRVAR(bpy_bmface_normal_update_doc,
-".. method:: normal_update()\n"
-"\n"
-" Update face's normal.\n"
-);
+ ".. method:: normal_update()\n"
+ "\n"
+ " Update face's normal.\n");
static PyObject *bpy_bmface_normal_update(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_face_normal_update(self->f);
+ BM_face_normal_update(self->f);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmface_normal_flip_doc,
-".. method:: normal_flip()\n"
-"\n"
-" Reverses winding of a face, which flips its normal.\n"
-);
+ ".. method:: normal_flip()\n"
+ "\n"
+ " Reverses winding of a face, which flips its normal.\n");
static PyObject *bpy_bmface_normal_flip(BPy_BMFace *self)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- BM_face_normal_flip(self->bm, self->f);
+ BM_face_normal_flip(self->bm, self->f);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
/* Loop
* ---- */
PyDoc_STRVAR(bpy_bmloop_copy_from_face_interp_doc,
-".. method:: copy_from_face_interp(face, vert=True, multires=True)\n"
-"\n"
-" Interpolate the customdata from a face onto this loop (the loops vert should overlap the face).\n"
-"\n"
-" :arg face: The face to interpolate data from.\n"
-" :type face: :class:`BMFace`\n"
-" :arg vert: When enabled, interpolate the loops vertex data (optional).\n"
-" :type vert: boolean\n"
-" :arg multires: When enabled, interpolate the loops multires data (optional).\n"
-" :type multires: boolean\n"
-);
+ ".. method:: copy_from_face_interp(face, vert=True, multires=True)\n"
+ "\n"
+ " Interpolate the customdata from a face onto this loop (the loops vert should "
+ "overlap the face).\n"
+ "\n"
+ " :arg face: The face to interpolate data from.\n"
+ " :type face: :class:`BMFace`\n"
+ " :arg vert: When enabled, interpolate the loops vertex data (optional).\n"
+ " :type vert: boolean\n"
+ " :arg multires: When enabled, interpolate the loops multires data (optional).\n"
+ " :type multires: boolean\n");
static PyObject *bpy_bmloop_copy_from_face_interp(BPy_BMLoop *self, PyObject *args)
{
- BPy_BMFace *py_face = NULL;
- bool do_vertex = true;
- bool do_multires = true;
+ BPy_BMFace *py_face = NULL;
+ bool do_vertex = true;
+ bool do_multires = true;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(
- args, "O!|O&O&:BMLoop.copy_from_face_interp",
- &BPy_BMFace_Type, &py_face,
- PyC_ParseBool, &do_vertex,
- PyC_ParseBool, &do_multires))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!PyArg_ParseTuple(args,
+ "O!|O&O&:BMLoop.copy_from_face_interp",
+ &BPy_BMFace_Type,
+ &py_face,
+ PyC_ParseBool,
+ &do_vertex,
+ PyC_ParseBool,
+ &do_multires)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "BMLoop.copy_from_face_interp(face)", py_face);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "BMLoop.copy_from_face_interp(face)", py_face);
- BM_loop_interp_from_face(bm, self->l, py_face->f, do_vertex, do_multires);
+ BM_loop_interp_from_face(bm, self->l, py_face->f, do_vertex, do_multires);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bmloop_calc_angle_doc,
-".. method:: calc_angle()\n"
-"\n"
-" Return the angle at this loops corner of the face.\n"
-" This is calculated so sharper corners give lower angles.\n"
-"\n"
-" :return: The angle in radians.\n"
-" :rtype: float\n"
-);
+ ".. method:: calc_angle()\n"
+ "\n"
+ " Return the angle at this loops corner of the face.\n"
+ " This is calculated so sharper corners give lower angles.\n"
+ "\n"
+ " :return: The angle in radians.\n"
+ " :rtype: float\n");
static PyObject *bpy_bmloop_calc_angle(BPy_BMLoop *self)
{
- BPY_BM_CHECK_OBJ(self);
- return PyFloat_FromDouble(BM_loop_calc_face_angle(self->l));
+ BPY_BM_CHECK_OBJ(self);
+ return PyFloat_FromDouble(BM_loop_calc_face_angle(self->l));
}
PyDoc_STRVAR(bpy_bmloop_calc_normal_doc,
-".. method:: calc_normal()\n"
-"\n"
-" Return normal at this loops corner of the face.\n"
-" Falls back to the face normal for straight lines.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. method:: calc_normal()\n"
+ "\n"
+ " Return normal at this loops corner of the face.\n"
+ " Falls back to the face normal for straight lines.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmloop_calc_normal(BPy_BMLoop *self)
{
- float vec[3];
- BPY_BM_CHECK_OBJ(self);
- BM_loop_calc_face_normal(self->l, vec);
- return Vector_CreatePyObject(vec, 3, NULL);
-}
-
-PyDoc_STRVAR(bpy_bmloop_calc_tangent_doc,
-".. method:: calc_tangent()\n"
-"\n"
-" Return the tangent at this loops corner of the face (pointing inward into the face).\n"
-" Falls back to the face normal for straight lines.\n"
-"\n"
-" :return: a normalized vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ float vec[3];
+ BPY_BM_CHECK_OBJ(self);
+ BM_loop_calc_face_normal(self->l, vec);
+ return Vector_CreatePyObject(vec, 3, NULL);
+}
+
+PyDoc_STRVAR(
+ bpy_bmloop_calc_tangent_doc,
+ ".. method:: calc_tangent()\n"
+ "\n"
+ " Return the tangent at this loops corner of the face (pointing inward into the face).\n"
+ " Falls back to the face normal for straight lines.\n"
+ "\n"
+ " :return: a normalized vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *bpy_bmloop_calc_tangent(BPy_BMLoop *self)
{
- float vec[3];
- BPY_BM_CHECK_OBJ(self);
- BM_loop_calc_face_tangent(self->l, vec);
- return Vector_CreatePyObject(vec, 3, NULL);
+ float vec[3];
+ BPY_BM_CHECK_OBJ(self);
+ BM_loop_calc_face_tangent(self->l, vec);
+ return Vector_CreatePyObject(vec, 3, NULL);
}
/* Vert Seq
* -------- */
PyDoc_STRVAR(bpy_bmvertseq_new_doc,
-".. method:: new(co=(0.0, 0.0, 0.0), example=None)\n"
-"\n"
-" Create a new vertex.\n"
-"\n"
-" :arg co: The initial location of the vertex (optional argument).\n"
-" :type co: float triplet\n"
-" :arg example: Existing vert to initialize settings.\n"
-" :type example: :class:`BMVert`\n"
-" :return: The newly created edge.\n"
-" :rtype: :class:`BMVert`\n"
-);
+ ".. method:: new(co=(0.0, 0.0, 0.0), example=None)\n"
+ "\n"
+ " Create a new vertex.\n"
+ "\n"
+ " :arg co: The initial location of the vertex (optional argument).\n"
+ " :type co: float triplet\n"
+ " :arg example: Existing vert to initialize settings.\n"
+ " :type example: :class:`BMVert`\n"
+ " :return: The newly created edge.\n"
+ " :rtype: :class:`BMVert`\n");
static PyObject *bpy_bmvertseq_new(BPy_BMElemSeq *self, PyObject *args)
{
- PyObject *py_co = NULL;
- BPy_BMVert *py_vert_example = NULL; /* optional */
+ PyObject *py_co = NULL;
+ BPy_BMVert *py_vert_example = NULL; /* optional */
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "|OO!:verts.new",
- &py_co,
- &BPy_BMVert_Type, &py_vert_example))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- BMVert *v;
- float co[3] = {0.0f, 0.0f, 0.0f};
+ if (!PyArg_ParseTuple(args, "|OO!:verts.new", &py_co, &BPy_BMVert_Type, &py_vert_example)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ BMVert *v;
+ float co[3] = {0.0f, 0.0f, 0.0f};
- if (py_vert_example) {
- BPY_BM_CHECK_OBJ(py_vert_example);
- }
+ if (py_vert_example) {
+ BPY_BM_CHECK_OBJ(py_vert_example);
+ }
- if (py_co && mathutils_array_parse(co, 3, 3, py_co, "verts.new(co)") == -1) {
- return NULL;
- }
+ if (py_co && mathutils_array_parse(co, 3, 3, py_co, "verts.new(co)") == -1) {
+ return NULL;
+ }
- v = BM_vert_create(bm, co, NULL, BM_CREATE_NOP);
+ v = BM_vert_create(bm, co, NULL, BM_CREATE_NOP);
- if (v == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "faces.new(verts): couldn't create the new face, internal error");
- return NULL;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "faces.new(verts): couldn't create the new face, internal error");
+ return NULL;
+ }
- if (py_vert_example) {
- BM_elem_attrs_copy(py_vert_example->bm, bm, py_vert_example->v, v);
- }
+ if (py_vert_example) {
+ BM_elem_attrs_copy(py_vert_example->bm, bm, py_vert_example->v, v);
+ }
- return BPy_BMVert_CreatePyObject(bm, v);
- }
+ return BPy_BMVert_CreatePyObject(bm, v);
+ }
}
-
/* Edge Seq
* -------- */
PyDoc_STRVAR(bpy_bmedgeseq_new_doc,
-".. method:: new(verts, example=None)\n"
-"\n"
-" Create a new edge from a given pair of verts.\n"
-"\n"
-" :arg verts: Vertex pair.\n"
-" :type verts: pair of :class:`BMVert`\n"
-" :arg example: Existing edge to initialize settings (optional argument).\n"
-" :type example: :class:`BMEdge`\n"
-" :return: The newly created edge.\n"
-" :rtype: :class:`BMEdge`\n"
-);
+ ".. method:: new(verts, example=None)\n"
+ "\n"
+ " Create a new edge from a given pair of verts.\n"
+ "\n"
+ " :arg verts: Vertex pair.\n"
+ " :type verts: pair of :class:`BMVert`\n"
+ " :arg example: Existing edge to initialize settings (optional argument).\n"
+ " :type example: :class:`BMEdge`\n"
+ " :return: The newly created edge.\n"
+ " :rtype: :class:`BMEdge`\n");
static PyObject *bpy_bmedgeseq_new(BPy_BMElemSeq *self, PyObject *args)
{
- PyObject *vert_seq;
- BPy_BMEdge *py_edge_example = NULL; /* optional */
+ PyObject *vert_seq;
+ BPy_BMEdge *py_edge_example = NULL; /* optional */
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "O|O!:edges.new",
- &vert_seq,
- &BPy_BMEdge_Type, &py_edge_example))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- BMEdge *e;
- BMVert **vert_array = NULL;
- Py_ssize_t vert_seq_len; /* always 2 */
- PyObject *ret = NULL;
+ if (!PyArg_ParseTuple(args, "O|O!:edges.new", &vert_seq, &BPy_BMEdge_Type, &py_edge_example)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ BMEdge *e;
+ BMVert **vert_array = NULL;
+ Py_ssize_t vert_seq_len; /* always 2 */
+ PyObject *ret = NULL;
- if (py_edge_example) {
- BPY_BM_CHECK_OBJ(py_edge_example);
- }
+ if (py_edge_example) {
+ BPY_BM_CHECK_OBJ(py_edge_example);
+ }
- vert_array = BPy_BMElem_PySeq_As_Array(&bm, vert_seq, 2, 2,
- &vert_seq_len, BM_VERT,
- true, true, "edges.new(...)");
+ vert_array = BPy_BMElem_PySeq_As_Array(
+ &bm, vert_seq, 2, 2, &vert_seq_len, BM_VERT, true, true, "edges.new(...)");
- if (vert_array == NULL) {
- return NULL;
- }
+ if (vert_array == NULL) {
+ return NULL;
+ }
- if (BM_edge_exists(vert_array[0], vert_array[1])) {
- PyErr_SetString(PyExc_ValueError,
- "edges.new(): this edge exists");
- goto cleanup;
- }
+ if (BM_edge_exists(vert_array[0], vert_array[1])) {
+ PyErr_SetString(PyExc_ValueError, "edges.new(): this edge exists");
+ goto cleanup;
+ }
- e = BM_edge_create(bm, vert_array[0], vert_array[1], NULL, BM_CREATE_NOP);
+ e = BM_edge_create(bm, vert_array[0], vert_array[1], NULL, BM_CREATE_NOP);
- if (e == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "faces.new(verts): couldn't create the new face, internal error");
- goto cleanup;
- }
+ if (e == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "faces.new(verts): couldn't create the new face, internal error");
+ goto cleanup;
+ }
- if (py_edge_example) {
- BM_elem_attrs_copy(py_edge_example->bm, bm, py_edge_example->e, e);
- }
+ if (py_edge_example) {
+ BM_elem_attrs_copy(py_edge_example->bm, bm, py_edge_example->e, e);
+ }
- ret = BPy_BMEdge_CreatePyObject(bm, e);
+ ret = BPy_BMEdge_CreatePyObject(bm, e);
-cleanup:
- if (vert_array) {
- PyMem_FREE(vert_array);
- }
- return ret;
- }
+ cleanup:
+ if (vert_array) {
+ PyMem_FREE(vert_array);
+ }
+ return ret;
+ }
}
-
/* Face Seq
* -------- */
PyDoc_STRVAR(bpy_bmfaceseq_new_doc,
-".. method:: new(verts, example=None)\n"
-"\n"
-" Create a new face from a given set of verts.\n"
-"\n"
-" :arg verts: Sequence of 3 or more verts.\n"
-" :type verts: :class:`BMVert`\n"
-" :arg example: Existing face to initialize settings (optional argument).\n"
-" :type example: :class:`BMFace`\n"
-" :return: The newly created face.\n"
-" :rtype: :class:`BMFace`\n"
-);
+ ".. method:: new(verts, example=None)\n"
+ "\n"
+ " Create a new face from a given set of verts.\n"
+ "\n"
+ " :arg verts: Sequence of 3 or more verts.\n"
+ " :type verts: :class:`BMVert`\n"
+ " :arg example: Existing face to initialize settings (optional argument).\n"
+ " :type example: :class:`BMFace`\n"
+ " :return: The newly created face.\n"
+ " :rtype: :class:`BMFace`\n");
static PyObject *bpy_bmfaceseq_new(BPy_BMElemSeq *self, PyObject *args)
{
- PyObject *vert_seq;
- BPy_BMFace *py_face_example = NULL; /* optional */
+ PyObject *vert_seq;
+ BPy_BMFace *py_face_example = NULL; /* optional */
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "O|O!:faces.new",
- &vert_seq,
- &BPy_BMFace_Type, &py_face_example))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- Py_ssize_t vert_seq_len;
+ if (!PyArg_ParseTuple(args, "O|O!:faces.new", &vert_seq, &BPy_BMFace_Type, &py_face_example)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ Py_ssize_t vert_seq_len;
- BMVert **vert_array = NULL;
+ BMVert **vert_array = NULL;
- PyObject *ret = NULL;
+ PyObject *ret = NULL;
- BMFace *f_new;
+ BMFace *f_new;
- if (py_face_example) {
- BPY_BM_CHECK_OBJ(py_face_example);
- }
+ if (py_face_example) {
+ BPY_BM_CHECK_OBJ(py_face_example);
+ }
- vert_array = BPy_BMElem_PySeq_As_Array(&bm, vert_seq, 3, PY_SSIZE_T_MAX,
- &vert_seq_len, BM_VERT,
- true, true, "faces.new(...)");
+ vert_array = BPy_BMElem_PySeq_As_Array(
+ &bm, vert_seq, 3, PY_SSIZE_T_MAX, &vert_seq_len, BM_VERT, true, true, "faces.new(...)");
- if (vert_array == NULL) {
- return NULL;
- }
+ if (vert_array == NULL) {
+ return NULL;
+ }
- /* check if the face exists */
- if (BM_face_exists(vert_array, vert_seq_len) != NULL) {
- PyErr_SetString(PyExc_ValueError,
- "faces.new(verts): face already exists");
- goto cleanup;
- }
+ /* check if the face exists */
+ if (BM_face_exists(vert_array, vert_seq_len) != NULL) {
+ PyErr_SetString(PyExc_ValueError, "faces.new(verts): face already exists");
+ goto cleanup;
+ }
- /* Go ahead and make the face!
- * --------------------------- */
+ /* Go ahead and make the face!
+ * --------------------------- */
- f_new = BM_face_create_verts(bm, vert_array, vert_seq_len,
- py_face_example ? py_face_example->f : NULL, BM_CREATE_NOP, true);
+ f_new = BM_face_create_verts(bm,
+ vert_array,
+ vert_seq_len,
+ py_face_example ? py_face_example->f : NULL,
+ BM_CREATE_NOP,
+ true);
- if (UNLIKELY(f_new == NULL)) {
- PyErr_SetString(PyExc_ValueError,
- "faces.new(verts): couldn't create the new face, internal error");
- goto cleanup;
- }
+ if (UNLIKELY(f_new == NULL)) {
+ PyErr_SetString(PyExc_ValueError,
+ "faces.new(verts): couldn't create the new face, internal error");
+ goto cleanup;
+ }
- ret = BPy_BMFace_CreatePyObject(bm, f_new);
+ ret = BPy_BMFace_CreatePyObject(bm, f_new);
- /* pass through */
-cleanup:
- if (vert_array) {
- PyMem_FREE(vert_array);
- }
- return ret;
- }
+ /* pass through */
+ cleanup:
+ if (vert_array) {
+ PyMem_FREE(vert_array);
+ }
+ return ret;
+ }
}
/* Elem Seq
* -------- */
PyDoc_STRVAR(bpy_bmvertseq_remove_doc,
-".. method:: remove(vert)\n"
-"\n"
-" Remove a vert.\n"
-);
+ ".. method:: remove(vert)\n"
+ "\n"
+ " Remove a vert.\n");
static PyObject *bpy_bmvertseq_remove(BPy_BMElemSeq *self, BPy_BMVert *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!BPy_BMVert_Check(value)) {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!BPy_BMVert_Check(value)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "verts.remove(vert)", value);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "verts.remove(vert)", value);
- BM_vert_kill(bm, value->v);
- bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
+ BM_vert_kill(bm, value->v);
+ bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(bpy_bmedgeseq_remove_doc,
-".. method:: remove(edge)\n"
-"\n"
-" Remove an edge.\n"
-);
+ ".. method:: remove(edge)\n"
+ "\n"
+ " Remove an edge.\n");
static PyObject *bpy_bmedgeseq_remove(BPy_BMElemSeq *self, BPy_BMEdge *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!BPy_BMEdge_Check(value)) {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!BPy_BMEdge_Check(value)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "edges.remove(edges)", value);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "edges.remove(edges)", value);
- BM_edge_kill(bm, value->e);
- bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
+ BM_edge_kill(bm, value->e);
+ bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(bpy_bmfaceseq_remove_doc,
-".. method:: remove(face)\n"
-"\n"
-" Remove a face.\n"
-);
+ ".. method:: remove(face)\n"
+ "\n"
+ " Remove a face.\n");
static PyObject *bpy_bmfaceseq_remove(BPy_BMElemSeq *self, BPy_BMFace *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!BPy_BMFace_Check(value)) {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
+ if (!BPy_BMFace_Check(value)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "faces.remove(face)", value);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "faces.remove(face)", value);
- BM_face_kill(bm, value->f);
- bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
+ BM_face_kill(bm, value->f);
+ bpy_bm_generic_invalidate((BPy_BMGeneric *)value);
- Py_RETURN_NONE;
- }
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(bpy_bmedgeseq_get__method_doc,
-".. method:: get(verts, fallback=None)\n"
-"\n"
-" Return an edge which uses the **verts** passed.\n"
-"\n"
-" :arg verts: Sequence of verts.\n"
-" :type verts: :class:`BMVert`\n"
-" :arg fallback: Return this value if nothing is found.\n"
-" :return: The edge found or None\n"
-" :rtype: :class:`BMEdge`\n"
-);
+ ".. method:: get(verts, fallback=None)\n"
+ "\n"
+ " Return an edge which uses the **verts** passed.\n"
+ "\n"
+ " :arg verts: Sequence of verts.\n"
+ " :type verts: :class:`BMVert`\n"
+ " :arg fallback: Return this value if nothing is found.\n"
+ " :return: The edge found or None\n"
+ " :rtype: :class:`BMEdge`\n");
static PyObject *bpy_bmedgeseq_get__method(BPy_BMElemSeq *self, PyObject *args)
{
- PyObject *vert_seq;
- PyObject *fallback = Py_None; /* optional */
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "O|O:edges.get",
- &vert_seq,
- &fallback))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- BMEdge *e;
- BMVert **vert_array = NULL;
- Py_ssize_t vert_seq_len; /* always 2 */
- PyObject *ret = NULL;
-
- vert_array = BPy_BMElem_PySeq_As_Array(&bm, vert_seq, 2, 2,
- &vert_seq_len, BM_VERT,
- true, true, "edges.get(...)");
-
- if (vert_array == NULL) {
- return NULL;
- }
-
- if ((e = BM_edge_exists(vert_array[0], vert_array[1]))) {
- ret = BPy_BMEdge_CreatePyObject(bm, e);
- }
- else {
- ret = fallback;
- Py_INCREF(ret);
- }
-
- PyMem_FREE(vert_array);
- return ret;
- }
+ PyObject *vert_seq;
+ PyObject *fallback = Py_None; /* optional */
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "O|O:edges.get", &vert_seq, &fallback)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ BMEdge *e;
+ BMVert **vert_array = NULL;
+ Py_ssize_t vert_seq_len; /* always 2 */
+ PyObject *ret = NULL;
+
+ vert_array = BPy_BMElem_PySeq_As_Array(
+ &bm, vert_seq, 2, 2, &vert_seq_len, BM_VERT, true, true, "edges.get(...)");
+
+ if (vert_array == NULL) {
+ return NULL;
+ }
+
+ if ((e = BM_edge_exists(vert_array[0], vert_array[1]))) {
+ ret = BPy_BMEdge_CreatePyObject(bm, e);
+ }
+ else {
+ ret = fallback;
+ Py_INCREF(ret);
+ }
+
+ PyMem_FREE(vert_array);
+ return ret;
+ }
}
PyDoc_STRVAR(bpy_bmfaceseq_get__method_doc,
-".. method:: get(verts, fallback=None)\n"
-"\n"
-" Return a face which uses the **verts** passed.\n"
-"\n"
-" :arg verts: Sequence of verts.\n"
-" :type verts: :class:`BMVert`\n"
-" :arg fallback: Return this value if nothing is found.\n"
-" :return: The face found or None\n"
-" :rtype: :class:`BMFace`\n"
-);
+ ".. method:: get(verts, fallback=None)\n"
+ "\n"
+ " Return a face which uses the **verts** passed.\n"
+ "\n"
+ " :arg verts: Sequence of verts.\n"
+ " :type verts: :class:`BMVert`\n"
+ " :arg fallback: Return this value if nothing is found.\n"
+ " :return: The face found or None\n"
+ " :rtype: :class:`BMFace`\n");
static PyObject *bpy_bmfaceseq_get__method(BPy_BMElemSeq *self, PyObject *args)
{
- PyObject *vert_seq;
- PyObject *fallback = Py_None; /* optional */
-
- BPY_BM_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "O|O:faces.get",
- &vert_seq,
- &fallback))
- {
- return NULL;
- }
- else {
- BMesh *bm = self->bm;
- BMFace *f = NULL;
- BMVert **vert_array = NULL;
- Py_ssize_t vert_seq_len;
- PyObject *ret = NULL;
-
- vert_array = BPy_BMElem_PySeq_As_Array(&bm, vert_seq, 1, PY_SSIZE_T_MAX,
- &vert_seq_len, BM_VERT,
- true, true, "faces.get(...)");
-
- if (vert_array == NULL) {
- return NULL;
- }
-
- f = BM_face_exists(vert_array, vert_seq_len);
- if (f != NULL) {
- ret = BPy_BMFace_CreatePyObject(bm, f);
- }
- else {
- ret = fallback;
- Py_INCREF(ret);
- }
-
- PyMem_FREE(vert_array);
- return ret;
- }
-}
-
-PyDoc_STRVAR(bpy_bmelemseq_index_update_doc,
-".. method:: index_update()\n"
-"\n"
-" Initialize the index values of this sequence.\n"
-"\n"
-" This is the equivalent of looping over all elements and assigning the index values.\n"
-"\n"
-" .. code-block:: python\n"
-"\n"
-" for index, ele in enumerate(sequence):\n"
-" ele.index = index\n"
-"\n"
-" .. note::\n"
-"\n"
-" Running this on sequences besides :class:`BMesh.verts`, :class:`BMesh.edges`, :class:`BMesh.faces`\n"
-" works but wont result in each element having a valid index, instead its order in the sequence will be set.\n"
-);
+ PyObject *vert_seq;
+ PyObject *fallback = Py_None; /* optional */
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "O|O:faces.get", &vert_seq, &fallback)) {
+ return NULL;
+ }
+ else {
+ BMesh *bm = self->bm;
+ BMFace *f = NULL;
+ BMVert **vert_array = NULL;
+ Py_ssize_t vert_seq_len;
+ PyObject *ret = NULL;
+
+ vert_array = BPy_BMElem_PySeq_As_Array(
+ &bm, vert_seq, 1, PY_SSIZE_T_MAX, &vert_seq_len, BM_VERT, true, true, "faces.get(...)");
+
+ if (vert_array == NULL) {
+ return NULL;
+ }
+
+ f = BM_face_exists(vert_array, vert_seq_len);
+ if (f != NULL) {
+ ret = BPy_BMFace_CreatePyObject(bm, f);
+ }
+ else {
+ ret = fallback;
+ Py_INCREF(ret);
+ }
+
+ PyMem_FREE(vert_array);
+ return ret;
+ }
+}
+
+PyDoc_STRVAR(
+ bpy_bmelemseq_index_update_doc,
+ ".. method:: index_update()\n"
+ "\n"
+ " Initialize the index values of this sequence.\n"
+ "\n"
+ " This is the equivalent of looping over all elements and assigning the index values.\n"
+ "\n"
+ " .. code-block:: python\n"
+ "\n"
+ " for index, ele in enumerate(sequence):\n"
+ " ele.index = index\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " Running this on sequences besides :class:`BMesh.verts`, :class:`BMesh.edges`, "
+ ":class:`BMesh.faces`\n"
+ " works but wont result in each element having a valid index, instead its order in the "
+ "sequence will be set.\n");
static PyObject *bpy_bmelemseq_index_update(BPy_BMElemSeq *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- switch ((BMIterType)self->itype) {
- case BM_VERTS_OF_MESH:
- BM_mesh_elem_index_ensure(self->bm, BM_VERT);
- break;
- case BM_EDGES_OF_MESH:
- BM_mesh_elem_index_ensure(self->bm, BM_EDGE);
- break;
- case BM_FACES_OF_MESH:
- BM_mesh_elem_index_ensure(self->bm, BM_FACE);
- break;
- default:
- {
- BMIter iter;
- BMElem *ele;
- int index = 0;
- const char htype = bm_iter_itype_htype_map[self->itype];
+ switch ((BMIterType)self->itype) {
+ case BM_VERTS_OF_MESH:
+ BM_mesh_elem_index_ensure(self->bm, BM_VERT);
+ break;
+ case BM_EDGES_OF_MESH:
+ BM_mesh_elem_index_ensure(self->bm, BM_EDGE);
+ break;
+ case BM_FACES_OF_MESH:
+ BM_mesh_elem_index_ensure(self->bm, BM_FACE);
+ break;
+ default: {
+ BMIter iter;
+ BMElem *ele;
+ int index = 0;
+ const char htype = bm_iter_itype_htype_map[self->itype];
- BM_ITER_BPY_BM_SEQ (ele, &iter, self) {
- BM_elem_index_set(ele, index); /* set_dirty! */
- index++;
- }
+ BM_ITER_BPY_BM_SEQ(ele, &iter, self)
+ {
+ BM_elem_index_set(ele, index); /* set_dirty! */
+ index++;
+ }
- /* since this isn't the normal vert/edge/face loops,
- * we're setting dirty values here. so tag as dirty. */
- bm->elem_index_dirty |= htype;
+ /* since this isn't the normal vert/edge/face loops,
+ * we're setting dirty values here. so tag as dirty. */
+ bm->elem_index_dirty |= htype;
- break;
- }
- }
+ break;
+ }
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bmelemseq_ensure_lookup_table_doc,
-".. method:: ensure_lookup_table()\n"
-"\n"
-" Ensure internal data needed for int subscription is initialized with verts/edges/faces, eg ``bm.verts[index]``.\n"
-"\n"
-" This needs to be called again after adding/removing data in this sequence."
-);
+ ".. method:: ensure_lookup_table()\n"
+ "\n"
+ " Ensure internal data needed for int subscription is initialized with "
+ "verts/edges/faces, eg ``bm.verts[index]``.\n"
+ "\n"
+ " This needs to be called again after adding/removing data in this sequence.");
static PyObject *bpy_bmelemseq_ensure_lookup_table(BPy_BMElemSeq *self)
{
- BPY_BM_CHECK_OBJ(self);
-
- BM_mesh_elem_table_ensure(self->bm, bm_iter_itype_htype_map[self->itype]);
-
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(bpy_bmelemseq_sort_doc,
-".. method:: sort(key=None, reverse=False)\n"
-"\n"
-" Sort the elements of this sequence, using an optional custom sort key.\n"
-" Indices of elements are not changed, BMElemeSeq.index_update() can be used for that.\n"
-"\n"
-" :arg key: The key that sets the ordering of the elements.\n"
-" :type key: :function: returning a number\n"
-" :arg reverse: Reverse the order of the elements\n"
-" :type reverse: :boolean:\n"
-"\n"
-" .. note::\n"
-"\n"
-" When the 'key' argument is not provided, the elements are reordered following their current index value.\n"
-" In particular this can be used by setting indices manually before calling this method.\n"
-"\n"
-" .. warning::\n"
-"\n"
-" Existing references to the N'th element, will continue to point the data at that index.\n"
-);
+ BPY_BM_CHECK_OBJ(self);
+
+ BM_mesh_elem_table_ensure(self->bm, bm_iter_itype_htype_map[self->itype]);
+
+ Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(
+ bpy_bmelemseq_sort_doc,
+ ".. method:: sort(key=None, reverse=False)\n"
+ "\n"
+ " Sort the elements of this sequence, using an optional custom sort key.\n"
+ " Indices of elements are not changed, BMElemeSeq.index_update() can be used for that.\n"
+ "\n"
+ " :arg key: The key that sets the ordering of the elements.\n"
+ " :type key: :function: returning a number\n"
+ " :arg reverse: Reverse the order of the elements\n"
+ " :type reverse: :boolean:\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " When the 'key' argument is not provided, the elements are reordered following their "
+ "current index value.\n"
+ " In particular this can be used by setting indices manually before calling this "
+ "method.\n"
+ "\n"
+ " .. warning::\n"
+ "\n"
+ " Existing references to the N'th element, will continue to point the data at that "
+ "index.\n");
/* Use a static variable here because there is the need to sort some array
* doing comparisons on elements of another array, qsort_r would have been
@@ -2536,320 +2662,439 @@ PyDoc_STRVAR(bpy_bmelemseq_sort_doc,
* has enough elements to complete the task.
*/
-static int bpy_bmelemseq_sort_cmp_by_keys_ascending(const void *index1_v, const void *index2_v, void *keys_v)
+static int bpy_bmelemseq_sort_cmp_by_keys_ascending(const void *index1_v,
+ const void *index2_v,
+ void *keys_v)
{
- const double *keys = keys_v;
- const int *index1 = (int *)index1_v;
- const int *index2 = (int *)index2_v;
+ const double *keys = keys_v;
+ const int *index1 = (int *)index1_v;
+ const int *index2 = (int *)index2_v;
- if (keys[*index1] < keys[*index2]) {
- return -1;
- }
- else if (keys[*index1] > keys[*index2]) {
- return 1;
- }
- else {
- return 0;
- }
+ if (keys[*index1] < keys[*index2]) {
+ return -1;
+ }
+ else if (keys[*index1] > keys[*index2]) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
}
-static int bpy_bmelemseq_sort_cmp_by_keys_descending(const void *index1_v, const void *index2_v, void *keys_v)
+static int bpy_bmelemseq_sort_cmp_by_keys_descending(const void *index1_v,
+ const void *index2_v,
+ void *keys_v)
{
- return -bpy_bmelemseq_sort_cmp_by_keys_ascending(index1_v, index2_v, keys_v);
+ return -bpy_bmelemseq_sort_cmp_by_keys_ascending(index1_v, index2_v, keys_v);
}
static PyObject *bpy_bmelemseq_sort(BPy_BMElemSeq *self, PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"key", "reverse", NULL};
- PyObject *keyfunc = NULL; /* optional */
- bool do_reverse = false; /* optional */
-
- const char htype = bm_iter_itype_htype_map[self->itype];
- int n_elem;
-
- BMIter iter;
- BMElem *ele;
-
- double *keys;
- int *elem_idx;
- unsigned int *elem_map_idx;
- int (*elem_idx_compare_by_keys)(const void *, const void *, void *);
-
- unsigned int *vert_idx = NULL;
- unsigned int *edge_idx = NULL;
- unsigned int *face_idx = NULL;
- int i;
-
- BMesh *bm = self->bm;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (args != NULL) {
- if (!PyArg_ParseTupleAndKeywords(
- args, kw,
- "|OO&:BMElemSeq.sort", (char **)kwlist,
- &keyfunc,
- PyC_ParseBool, &do_reverse))
- {
- return NULL;
- }
- }
-
- if (keyfunc != NULL && !PyCallable_Check(keyfunc)) {
- PyErr_SetString(PyExc_TypeError,
- "the 'key' argument is not a callable object");
- return NULL;
- }
-
- n_elem = BM_mesh_elem_count(bm, htype);
- if (n_elem <= 1) {
- /* 0 or 1 elements: sorted already */
- Py_RETURN_NONE;
- }
-
- keys = PyMem_MALLOC(sizeof(*keys) * n_elem);
- if (keys == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- i = 0;
- BM_ITER_BPY_BM_SEQ (ele, &iter, self) {
- if (keyfunc != NULL) {
- PyObject *py_elem;
- PyObject *index;
-
- py_elem = BPy_BMElem_CreatePyObject(self->bm, (BMHeader *)ele);
- index = PyObject_CallFunctionObjArgs(keyfunc, py_elem, NULL);
- Py_DECREF(py_elem);
- if (index == NULL) {
- /* No need to set the exception here,
- * PyObject_CallFunctionObjArgs() does that */
- PyMem_FREE(keys);
- return NULL;
- }
-
- if ((keys[i] = PyFloat_AsDouble(index)) == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "the value returned by the 'key' function is not a number");
- Py_DECREF(index);
- PyMem_FREE(keys);
- return NULL;
- }
-
- Py_DECREF(index);
- }
- else {
- /* If the 'key' function is not provided we sort
- * according to the current index values */
- keys[i] = ele->head.index;
- }
-
- i++;
- }
-
- elem_idx = PyMem_MALLOC(sizeof(*elem_idx) * n_elem);
- if (elem_idx == NULL) {
- PyErr_NoMemory();
- PyMem_FREE(keys);
- return NULL;
- }
-
- /* Initialize the element index array */
- range_vn_i(elem_idx, n_elem, 0);
-
- /* Sort the index array according to the order of the 'keys' array */
- if (do_reverse) {
- elem_idx_compare_by_keys = bpy_bmelemseq_sort_cmp_by_keys_descending;
- }
- else {
- elem_idx_compare_by_keys = bpy_bmelemseq_sort_cmp_by_keys_ascending;
- }
-
- BLI_qsort_r(elem_idx, n_elem, sizeof(*elem_idx), elem_idx_compare_by_keys, keys);
-
- elem_map_idx = PyMem_MALLOC(sizeof(*elem_map_idx) * n_elem);
- if (elem_map_idx == NULL) {
- PyErr_NoMemory();
- PyMem_FREE(elem_idx);
- PyMem_FREE(keys);
- return NULL;
- }
-
- /* Initialize the map array
- *
- * We need to know the index such that if used as the new_index in
- * BM_mesh_remap() will give the order of the sorted keys like in
- * elem_idx */
- for (i = 0; i < n_elem; i++) {
- elem_map_idx[elem_idx[i]] = i;
- }
-
- switch ((BMIterType)self->itype) {
- case BM_VERTS_OF_MESH:
- vert_idx = elem_map_idx;
- break;
- case BM_EDGES_OF_MESH:
- edge_idx = elem_map_idx;
- break;
- case BM_FACES_OF_MESH:
- face_idx = elem_map_idx;
- break;
- default:
- PyErr_Format(PyExc_TypeError, "element type %d not supported", self->itype);
- PyMem_FREE(elem_map_idx);
- PyMem_FREE(elem_idx);
- PyMem_FREE(keys);
- return NULL;
- }
-
- BM_mesh_remap(bm, vert_idx, edge_idx, face_idx);
-
- PyMem_FREE(elem_map_idx);
- PyMem_FREE(elem_idx);
- PyMem_FREE(keys);
-
- Py_RETURN_NONE;
+ static const char *kwlist[] = {"key", "reverse", NULL};
+ PyObject *keyfunc = NULL; /* optional */
+ bool do_reverse = false; /* optional */
+
+ const char htype = bm_iter_itype_htype_map[self->itype];
+ int n_elem;
+
+ BMIter iter;
+ BMElem *ele;
+
+ double *keys;
+ int *elem_idx;
+ unsigned int *elem_map_idx;
+ int (*elem_idx_compare_by_keys)(const void *, const void *, void *);
+
+ unsigned int *vert_idx = NULL;
+ unsigned int *edge_idx = NULL;
+ unsigned int *face_idx = NULL;
+ int i;
+
+ BMesh *bm = self->bm;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (args != NULL) {
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "|OO&:BMElemSeq.sort",
+ (char **)kwlist,
+ &keyfunc,
+ PyC_ParseBool,
+ &do_reverse)) {
+ return NULL;
+ }
+ }
+
+ if (keyfunc != NULL && !PyCallable_Check(keyfunc)) {
+ PyErr_SetString(PyExc_TypeError, "the 'key' argument is not a callable object");
+ return NULL;
+ }
+
+ n_elem = BM_mesh_elem_count(bm, htype);
+ if (n_elem <= 1) {
+ /* 0 or 1 elements: sorted already */
+ Py_RETURN_NONE;
+ }
+
+ keys = PyMem_MALLOC(sizeof(*keys) * n_elem);
+ if (keys == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ i = 0;
+ BM_ITER_BPY_BM_SEQ(ele, &iter, self)
+ {
+ if (keyfunc != NULL) {
+ PyObject *py_elem;
+ PyObject *index;
+
+ py_elem = BPy_BMElem_CreatePyObject(self->bm, (BMHeader *)ele);
+ index = PyObject_CallFunctionObjArgs(keyfunc, py_elem, NULL);
+ Py_DECREF(py_elem);
+ if (index == NULL) {
+ /* No need to set the exception here,
+ * PyObject_CallFunctionObjArgs() does that */
+ PyMem_FREE(keys);
+ return NULL;
+ }
+
+ if ((keys[i] = PyFloat_AsDouble(index)) == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "the value returned by the 'key' function is not a number");
+ Py_DECREF(index);
+ PyMem_FREE(keys);
+ return NULL;
+ }
+
+ Py_DECREF(index);
+ }
+ else {
+ /* If the 'key' function is not provided we sort
+ * according to the current index values */
+ keys[i] = ele->head.index;
+ }
+
+ i++;
+ }
+
+ elem_idx = PyMem_MALLOC(sizeof(*elem_idx) * n_elem);
+ if (elem_idx == NULL) {
+ PyErr_NoMemory();
+ PyMem_FREE(keys);
+ return NULL;
+ }
+
+ /* Initialize the element index array */
+ range_vn_i(elem_idx, n_elem, 0);
+
+ /* Sort the index array according to the order of the 'keys' array */
+ if (do_reverse) {
+ elem_idx_compare_by_keys = bpy_bmelemseq_sort_cmp_by_keys_descending;
+ }
+ else {
+ elem_idx_compare_by_keys = bpy_bmelemseq_sort_cmp_by_keys_ascending;
+ }
+
+ BLI_qsort_r(elem_idx, n_elem, sizeof(*elem_idx), elem_idx_compare_by_keys, keys);
+
+ elem_map_idx = PyMem_MALLOC(sizeof(*elem_map_idx) * n_elem);
+ if (elem_map_idx == NULL) {
+ PyErr_NoMemory();
+ PyMem_FREE(elem_idx);
+ PyMem_FREE(keys);
+ return NULL;
+ }
+
+ /* Initialize the map array
+ *
+ * We need to know the index such that if used as the new_index in
+ * BM_mesh_remap() will give the order of the sorted keys like in
+ * elem_idx */
+ for (i = 0; i < n_elem; i++) {
+ elem_map_idx[elem_idx[i]] = i;
+ }
+
+ switch ((BMIterType)self->itype) {
+ case BM_VERTS_OF_MESH:
+ vert_idx = elem_map_idx;
+ break;
+ case BM_EDGES_OF_MESH:
+ edge_idx = elem_map_idx;
+ break;
+ case BM_FACES_OF_MESH:
+ face_idx = elem_map_idx;
+ break;
+ default:
+ PyErr_Format(PyExc_TypeError, "element type %d not supported", self->itype);
+ PyMem_FREE(elem_map_idx);
+ PyMem_FREE(elem_idx);
+ PyMem_FREE(keys);
+ return NULL;
+ }
+
+ BM_mesh_remap(bm, vert_idx, edge_idx, face_idx);
+
+ PyMem_FREE(elem_map_idx);
+ PyMem_FREE(elem_idx);
+ PyMem_FREE(keys);
+
+ Py_RETURN_NONE;
}
static struct PyMethodDef bpy_bmesh_methods[] = {
- /* utility */
- {"copy", (PyCFunction)bpy_bmesh_copy, METH_NOARGS, bpy_bmesh_copy_doc},
- {"clear", (PyCFunction)bpy_bmesh_clear, METH_NOARGS, bpy_bmesh_clear_doc},
- {"free", (PyCFunction)bpy_bmesh_free, METH_NOARGS, bpy_bmesh_free_doc},
-
- /* conversion */
- {"from_object", (PyCFunction)bpy_bmesh_from_object, METH_VARARGS | METH_KEYWORDS, bpy_bmesh_from_object_doc},
- {"from_mesh", (PyCFunction)bpy_bmesh_from_mesh, METH_VARARGS | METH_KEYWORDS, bpy_bmesh_from_mesh_doc},
- {"to_mesh", (PyCFunction)bpy_bmesh_to_mesh, METH_VARARGS, bpy_bmesh_to_mesh_doc},
-
- /* meshdata */
- {"select_flush_mode", (PyCFunction)bpy_bmesh_select_flush_mode, METH_NOARGS, bpy_bmesh_select_flush_mode_doc},
- {"select_flush", (PyCFunction)bpy_bmesh_select_flush, METH_O, bpy_bmesh_select_flush_doc},
- {"normal_update", (PyCFunction)bpy_bmesh_normal_update, METH_NOARGS, bpy_bmesh_normal_update_doc},
- {"transform", (PyCFunction)bpy_bmesh_transform, METH_VARARGS | METH_KEYWORDS, bpy_bmesh_transform_doc},
-
- /* calculations */
- {"calc_volume", (PyCFunction)bpy_bmesh_calc_volume, METH_VARARGS | METH_KEYWORDS, bpy_bmesh_calc_volume_doc},
- {"calc_loop_triangles", (PyCFunction)bpy_bmesh_calc_loop_triangles, METH_NOARGS, bpy_bmesh_calc_loop_triangles_doc},
- {NULL, NULL, 0, NULL},
+ /* utility */
+ {"copy", (PyCFunction)bpy_bmesh_copy, METH_NOARGS, bpy_bmesh_copy_doc},
+ {"clear", (PyCFunction)bpy_bmesh_clear, METH_NOARGS, bpy_bmesh_clear_doc},
+ {"free", (PyCFunction)bpy_bmesh_free, METH_NOARGS, bpy_bmesh_free_doc},
+
+ /* conversion */
+ {"from_object",
+ (PyCFunction)bpy_bmesh_from_object,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmesh_from_object_doc},
+ {"from_mesh",
+ (PyCFunction)bpy_bmesh_from_mesh,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmesh_from_mesh_doc},
+ {"to_mesh", (PyCFunction)bpy_bmesh_to_mesh, METH_VARARGS, bpy_bmesh_to_mesh_doc},
+
+ /* meshdata */
+ {"select_flush_mode",
+ (PyCFunction)bpy_bmesh_select_flush_mode,
+ METH_NOARGS,
+ bpy_bmesh_select_flush_mode_doc},
+ {"select_flush", (PyCFunction)bpy_bmesh_select_flush, METH_O, bpy_bmesh_select_flush_doc},
+ {"normal_update",
+ (PyCFunction)bpy_bmesh_normal_update,
+ METH_NOARGS,
+ bpy_bmesh_normal_update_doc},
+ {"transform",
+ (PyCFunction)bpy_bmesh_transform,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmesh_transform_doc},
+
+ /* calculations */
+ {"calc_volume",
+ (PyCFunction)bpy_bmesh_calc_volume,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmesh_calc_volume_doc},
+ {"calc_loop_triangles",
+ (PyCFunction)bpy_bmesh_calc_loop_triangles,
+ METH_NOARGS,
+ bpy_bmesh_calc_loop_triangles_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmvert_methods[] = {
- {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
- {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
- {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
- {"copy_from_face_interp", (PyCFunction)bpy_bmvert_copy_from_face_interp, METH_VARARGS, bpy_bmvert_copy_from_face_interp_doc},
- {"copy_from_vert_interp", (PyCFunction)bpy_bmvert_copy_from_vert_interp, METH_VARARGS, bpy_bmvert_copy_from_vert_interp_doc},
-
- {"calc_edge_angle", (PyCFunction)bpy_bmvert_calc_edge_angle, METH_VARARGS, bpy_bmvert_calc_edge_angle_doc},
- {"calc_shell_factor", (PyCFunction)bpy_bmvert_calc_shell_factor, METH_NOARGS, bpy_bmvert_calc_shell_factor_doc},
-
- {"normal_update", (PyCFunction)bpy_bmvert_normal_update, METH_NOARGS, bpy_bmvert_normal_update_doc},
-
- {NULL, NULL, 0, NULL},
+ {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
+ {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
+ {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
+ {"copy_from_face_interp",
+ (PyCFunction)bpy_bmvert_copy_from_face_interp,
+ METH_VARARGS,
+ bpy_bmvert_copy_from_face_interp_doc},
+ {"copy_from_vert_interp",
+ (PyCFunction)bpy_bmvert_copy_from_vert_interp,
+ METH_VARARGS,
+ bpy_bmvert_copy_from_vert_interp_doc},
+
+ {"calc_edge_angle",
+ (PyCFunction)bpy_bmvert_calc_edge_angle,
+ METH_VARARGS,
+ bpy_bmvert_calc_edge_angle_doc},
+ {"calc_shell_factor",
+ (PyCFunction)bpy_bmvert_calc_shell_factor,
+ METH_NOARGS,
+ bpy_bmvert_calc_shell_factor_doc},
+
+ {"normal_update",
+ (PyCFunction)bpy_bmvert_normal_update,
+ METH_NOARGS,
+ bpy_bmvert_normal_update_doc},
+
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmedge_methods[] = {
- {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
- {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
- {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
-
- {"other_vert", (PyCFunction)bpy_bmedge_other_vert, METH_O, bpy_bmedge_other_vert_doc},
-
- {"calc_length", (PyCFunction)bpy_bmedge_calc_length, METH_NOARGS, bpy_bmedge_calc_length_doc},
- {"calc_face_angle", (PyCFunction)bpy_bmedge_calc_face_angle, METH_VARARGS, bpy_bmedge_calc_face_angle_doc},
- {"calc_face_angle_signed", (PyCFunction)bpy_bmedge_calc_face_angle_signed, METH_VARARGS, bpy_bmedge_calc_face_angle_signed_doc},
- {"calc_tangent", (PyCFunction)bpy_bmedge_calc_tangent, METH_VARARGS, bpy_bmedge_calc_tangent_doc},
-
- {"normal_update", (PyCFunction)bpy_bmedge_normal_update, METH_NOARGS, bpy_bmedge_normal_update_doc},
-
- {NULL, NULL, 0, NULL},
+ {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
+ {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
+ {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
+
+ {"other_vert", (PyCFunction)bpy_bmedge_other_vert, METH_O, bpy_bmedge_other_vert_doc},
+
+ {"calc_length", (PyCFunction)bpy_bmedge_calc_length, METH_NOARGS, bpy_bmedge_calc_length_doc},
+ {"calc_face_angle",
+ (PyCFunction)bpy_bmedge_calc_face_angle,
+ METH_VARARGS,
+ bpy_bmedge_calc_face_angle_doc},
+ {"calc_face_angle_signed",
+ (PyCFunction)bpy_bmedge_calc_face_angle_signed,
+ METH_VARARGS,
+ bpy_bmedge_calc_face_angle_signed_doc},
+ {"calc_tangent",
+ (PyCFunction)bpy_bmedge_calc_tangent,
+ METH_VARARGS,
+ bpy_bmedge_calc_tangent_doc},
+
+ {"normal_update",
+ (PyCFunction)bpy_bmedge_normal_update,
+ METH_NOARGS,
+ bpy_bmedge_normal_update_doc},
+
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmface_methods[] = {
- {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
- {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
-
- {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
- {"copy_from_face_interp", (PyCFunction)bpy_bmface_copy_from_face_interp, METH_O, bpy_bmface_copy_from_face_interp_doc},
-
- {"copy", (PyCFunction)bpy_bmface_copy, METH_VARARGS | METH_KEYWORDS, bpy_bmface_copy_doc},
-
- {"calc_area", (PyCFunction)bpy_bmface_calc_area, METH_NOARGS, bpy_bmface_calc_area_doc},
- {"calc_perimeter", (PyCFunction)bpy_bmface_calc_perimeter, METH_NOARGS, bpy_bmface_calc_perimeter_doc},
- {"calc_tangent_edge", (PyCFunction)bpy_bmface_calc_tangent_edge, METH_NOARGS, bpy_bmface_calc_tangent_edge_doc},
- {"calc_tangent_edge_pair", (PyCFunction)bpy_bmface_calc_tangent_edge_pair, METH_NOARGS, bpy_bmface_calc_tangent_edge_pair_doc},
- {"calc_tangent_edge_diagonal", (PyCFunction)bpy_bmface_calc_tangent_edge_diagonal, METH_NOARGS, bpy_bmface_calc_tangent_edge_diagonal_doc},
- {"calc_tangent_vert_diagonal", (PyCFunction)bpy_bmface_calc_tangent_vert_diagonal, METH_NOARGS, bpy_bmface_calc_tangent_vert_diagonal_doc},
- {"calc_center_median", (PyCFunction)bpy_bmface_calc_center_mean, METH_NOARGS, bpy_bmface_calc_center_median_doc},
- {"calc_center_median_weighted", (PyCFunction)bpy_bmface_calc_center_median_weighted, METH_NOARGS, bpy_bmface_calc_center_median_weighted_doc},
- {"calc_center_bounds", (PyCFunction)bpy_bmface_calc_center_bounds, METH_NOARGS, bpy_bmface_calc_center_bounds_doc},
-
- {"normal_update", (PyCFunction)bpy_bmface_normal_update, METH_NOARGS, bpy_bmface_normal_update_doc},
- {"normal_flip", (PyCFunction)bpy_bmface_normal_flip, METH_NOARGS, bpy_bmface_normal_flip_doc},
-
- {NULL, NULL, 0, NULL},
+ {"select_set", (PyCFunction)bpy_bm_elem_select_set, METH_O, bpy_bm_elem_select_set_doc},
+ {"hide_set", (PyCFunction)bpy_bm_elem_hide_set, METH_O, bpy_bm_elem_hide_set_doc},
+
+ {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
+ {"copy_from_face_interp",
+ (PyCFunction)bpy_bmface_copy_from_face_interp,
+ METH_O,
+ bpy_bmface_copy_from_face_interp_doc},
+
+ {"copy", (PyCFunction)bpy_bmface_copy, METH_VARARGS | METH_KEYWORDS, bpy_bmface_copy_doc},
+
+ {"calc_area", (PyCFunction)bpy_bmface_calc_area, METH_NOARGS, bpy_bmface_calc_area_doc},
+ {"calc_perimeter",
+ (PyCFunction)bpy_bmface_calc_perimeter,
+ METH_NOARGS,
+ bpy_bmface_calc_perimeter_doc},
+ {"calc_tangent_edge",
+ (PyCFunction)bpy_bmface_calc_tangent_edge,
+ METH_NOARGS,
+ bpy_bmface_calc_tangent_edge_doc},
+ {"calc_tangent_edge_pair",
+ (PyCFunction)bpy_bmface_calc_tangent_edge_pair,
+ METH_NOARGS,
+ bpy_bmface_calc_tangent_edge_pair_doc},
+ {"calc_tangent_edge_diagonal",
+ (PyCFunction)bpy_bmface_calc_tangent_edge_diagonal,
+ METH_NOARGS,
+ bpy_bmface_calc_tangent_edge_diagonal_doc},
+ {"calc_tangent_vert_diagonal",
+ (PyCFunction)bpy_bmface_calc_tangent_vert_diagonal,
+ METH_NOARGS,
+ bpy_bmface_calc_tangent_vert_diagonal_doc},
+ {"calc_center_median",
+ (PyCFunction)bpy_bmface_calc_center_mean,
+ METH_NOARGS,
+ bpy_bmface_calc_center_median_doc},
+ {"calc_center_median_weighted",
+ (PyCFunction)bpy_bmface_calc_center_median_weighted,
+ METH_NOARGS,
+ bpy_bmface_calc_center_median_weighted_doc},
+ {"calc_center_bounds",
+ (PyCFunction)bpy_bmface_calc_center_bounds,
+ METH_NOARGS,
+ bpy_bmface_calc_center_bounds_doc},
+
+ {"normal_update",
+ (PyCFunction)bpy_bmface_normal_update,
+ METH_NOARGS,
+ bpy_bmface_normal_update_doc},
+ {"normal_flip", (PyCFunction)bpy_bmface_normal_flip, METH_NOARGS, bpy_bmface_normal_flip_doc},
+
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmloop_methods[] = {
- {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
- {"copy_from_face_interp", (PyCFunction)bpy_bmloop_copy_from_face_interp, METH_O, bpy_bmloop_copy_from_face_interp_doc},
-
- {"calc_angle", (PyCFunction)bpy_bmloop_calc_angle, METH_NOARGS, bpy_bmloop_calc_angle_doc},
- {"calc_normal", (PyCFunction)bpy_bmloop_calc_normal, METH_NOARGS, bpy_bmloop_calc_normal_doc},
- {"calc_tangent", (PyCFunction)bpy_bmloop_calc_tangent, METH_NOARGS, bpy_bmloop_calc_tangent_doc},
- {NULL, NULL, 0, NULL},
+ {"copy_from", (PyCFunction)bpy_bm_elem_copy_from, METH_O, bpy_bm_elem_copy_from_doc},
+ {"copy_from_face_interp",
+ (PyCFunction)bpy_bmloop_copy_from_face_interp,
+ METH_O,
+ bpy_bmloop_copy_from_face_interp_doc},
+
+ {"calc_angle", (PyCFunction)bpy_bmloop_calc_angle, METH_NOARGS, bpy_bmloop_calc_angle_doc},
+ {"calc_normal", (PyCFunction)bpy_bmloop_calc_normal, METH_NOARGS, bpy_bmloop_calc_normal_doc},
+ {"calc_tangent",
+ (PyCFunction)bpy_bmloop_calc_tangent,
+ METH_NOARGS,
+ bpy_bmloop_calc_tangent_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmelemseq_methods[] = {
- /* odd function, initializes index values */
- {"index_update", (PyCFunction)bpy_bmelemseq_index_update, METH_NOARGS, bpy_bmelemseq_index_update_doc},
- {NULL, NULL, 0, NULL},
+ /* odd function, initializes index values */
+ {"index_update",
+ (PyCFunction)bpy_bmelemseq_index_update,
+ METH_NOARGS,
+ bpy_bmelemseq_index_update_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmvertseq_methods[] = {
- {"new", (PyCFunction)bpy_bmvertseq_new, METH_VARARGS, bpy_bmvertseq_new_doc},
- {"remove", (PyCFunction)bpy_bmvertseq_remove, METH_O, bpy_bmvertseq_remove_doc},
-
- /* odd function, initializes index values */
- {"index_update", (PyCFunction)bpy_bmelemseq_index_update, METH_NOARGS, bpy_bmelemseq_index_update_doc},
- {"ensure_lookup_table", (PyCFunction)bpy_bmelemseq_ensure_lookup_table, METH_NOARGS, bpy_bmelemseq_ensure_lookup_table_doc},
- {"sort", (PyCFunction)bpy_bmelemseq_sort, METH_VARARGS | METH_KEYWORDS, bpy_bmelemseq_sort_doc},
- {NULL, NULL, 0, NULL},
+ {"new", (PyCFunction)bpy_bmvertseq_new, METH_VARARGS, bpy_bmvertseq_new_doc},
+ {"remove", (PyCFunction)bpy_bmvertseq_remove, METH_O, bpy_bmvertseq_remove_doc},
+
+ /* odd function, initializes index values */
+ {"index_update",
+ (PyCFunction)bpy_bmelemseq_index_update,
+ METH_NOARGS,
+ bpy_bmelemseq_index_update_doc},
+ {"ensure_lookup_table",
+ (PyCFunction)bpy_bmelemseq_ensure_lookup_table,
+ METH_NOARGS,
+ bpy_bmelemseq_ensure_lookup_table_doc},
+ {"sort",
+ (PyCFunction)bpy_bmelemseq_sort,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmelemseq_sort_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmedgeseq_methods[] = {
- {"new", (PyCFunction)bpy_bmedgeseq_new, METH_VARARGS, bpy_bmedgeseq_new_doc},
- {"remove", (PyCFunction)bpy_bmedgeseq_remove, METH_O, bpy_bmedgeseq_remove_doc},
- /* 'bpy_bmelemseq_get' for different purpose */
- {"get", (PyCFunction)bpy_bmedgeseq_get__method, METH_VARARGS, bpy_bmedgeseq_get__method_doc},
-
- /* odd function, initializes index values */
- {"index_update", (PyCFunction)bpy_bmelemseq_index_update, METH_NOARGS, bpy_bmelemseq_index_update_doc},
- {"ensure_lookup_table", (PyCFunction)bpy_bmelemseq_ensure_lookup_table, METH_NOARGS, bpy_bmelemseq_ensure_lookup_table_doc},
- {"sort", (PyCFunction)bpy_bmelemseq_sort, METH_VARARGS | METH_KEYWORDS, bpy_bmelemseq_sort_doc},
- {NULL, NULL, 0, NULL},
+ {"new", (PyCFunction)bpy_bmedgeseq_new, METH_VARARGS, bpy_bmedgeseq_new_doc},
+ {"remove", (PyCFunction)bpy_bmedgeseq_remove, METH_O, bpy_bmedgeseq_remove_doc},
+ /* 'bpy_bmelemseq_get' for different purpose */
+ {"get", (PyCFunction)bpy_bmedgeseq_get__method, METH_VARARGS, bpy_bmedgeseq_get__method_doc},
+
+ /* odd function, initializes index values */
+ {"index_update",
+ (PyCFunction)bpy_bmelemseq_index_update,
+ METH_NOARGS,
+ bpy_bmelemseq_index_update_doc},
+ {"ensure_lookup_table",
+ (PyCFunction)bpy_bmelemseq_ensure_lookup_table,
+ METH_NOARGS,
+ bpy_bmelemseq_ensure_lookup_table_doc},
+ {"sort",
+ (PyCFunction)bpy_bmelemseq_sort,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmelemseq_sort_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmfaceseq_methods[] = {
- {"new", (PyCFunction)bpy_bmfaceseq_new, METH_VARARGS, bpy_bmfaceseq_new_doc},
- {"remove", (PyCFunction)bpy_bmfaceseq_remove, METH_O, bpy_bmfaceseq_remove_doc},
- /* 'bpy_bmelemseq_get' for different purpose */
- {"get", (PyCFunction)bpy_bmfaceseq_get__method, METH_VARARGS, bpy_bmfaceseq_get__method_doc},
-
- /* odd function, initializes index values */
- {"index_update", (PyCFunction)bpy_bmelemseq_index_update, METH_NOARGS, bpy_bmelemseq_index_update_doc},
- {"ensure_lookup_table", (PyCFunction)bpy_bmelemseq_ensure_lookup_table, METH_NOARGS, bpy_bmelemseq_ensure_lookup_table_doc},
- {"sort", (PyCFunction)bpy_bmelemseq_sort, METH_VARARGS | METH_KEYWORDS, bpy_bmelemseq_sort_doc},
- {NULL, NULL, 0, NULL},
+ {"new", (PyCFunction)bpy_bmfaceseq_new, METH_VARARGS, bpy_bmfaceseq_new_doc},
+ {"remove", (PyCFunction)bpy_bmfaceseq_remove, METH_O, bpy_bmfaceseq_remove_doc},
+ /* 'bpy_bmelemseq_get' for different purpose */
+ {"get", (PyCFunction)bpy_bmfaceseq_get__method, METH_VARARGS, bpy_bmfaceseq_get__method_doc},
+
+ /* odd function, initializes index values */
+ {"index_update",
+ (PyCFunction)bpy_bmelemseq_index_update,
+ METH_NOARGS,
+ bpy_bmelemseq_index_update_doc},
+ {"ensure_lookup_table",
+ (PyCFunction)bpy_bmelemseq_ensure_lookup_table,
+ METH_NOARGS,
+ bpy_bmelemseq_ensure_lookup_table_doc},
+ {"sort",
+ (PyCFunction)bpy_bmelemseq_sort,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bmelemseq_sort_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmloopseq_methods[] = {
- /* odd function, initializes index values */
- /* no: index_update() function since we cant iterate over loops */
- /* no: sort() function since we cant iterate over loops */
- {NULL, NULL, 0, NULL},
+ /* odd function, initializes index values */
+ /* no: index_update() function since we cant iterate over loops */
+ /* no: sort() function since we cant iterate over loops */
+ {NULL, NULL, 0, NULL},
};
/* Sequences
@@ -2860,253 +3105,254 @@ static struct PyMethodDef bpy_bmloopseq_methods[] = {
static PyTypeObject *bpy_bm_itype_as_pytype(const char itype)
{
- /* should cover all types */
- switch ((BMIterType)itype) {
- case BM_VERTS_OF_MESH:
- case BM_VERTS_OF_FACE:
- case BM_VERTS_OF_EDGE:
- return &BPy_BMVert_Type;
+ /* should cover all types */
+ switch ((BMIterType)itype) {
+ case BM_VERTS_OF_MESH:
+ case BM_VERTS_OF_FACE:
+ case BM_VERTS_OF_EDGE:
+ return &BPy_BMVert_Type;
- case BM_EDGES_OF_MESH:
- case BM_EDGES_OF_FACE:
- case BM_EDGES_OF_VERT:
- return &BPy_BMEdge_Type;
+ case BM_EDGES_OF_MESH:
+ case BM_EDGES_OF_FACE:
+ case BM_EDGES_OF_VERT:
+ return &BPy_BMEdge_Type;
- case BM_FACES_OF_MESH:
- case BM_FACES_OF_EDGE:
- case BM_FACES_OF_VERT:
- return &BPy_BMFace_Type;
+ case BM_FACES_OF_MESH:
+ case BM_FACES_OF_EDGE:
+ case BM_FACES_OF_VERT:
+ return &BPy_BMFace_Type;
- // case BM_ALL_LOOPS_OF_FACE:
- case BM_LOOPS_OF_FACE:
- case BM_LOOPS_OF_EDGE:
- case BM_LOOPS_OF_VERT:
- case BM_LOOPS_OF_LOOP:
- return &BPy_BMLoop_Type;
- }
+ // case BM_ALL_LOOPS_OF_FACE:
+ case BM_LOOPS_OF_FACE:
+ case BM_LOOPS_OF_EDGE:
+ case BM_LOOPS_OF_VERT:
+ case BM_LOOPS_OF_LOOP:
+ return &BPy_BMLoop_Type;
+ }
- return NULL;
+ return NULL;
}
static Py_ssize_t bpy_bmelemseq_length(BPy_BMElemSeq *self)
{
- BPY_BM_CHECK_INT(self);
-
- /* first check if the size is known */
- switch ((BMIterType)self->itype) {
- /* main-types */
- case BM_VERTS_OF_MESH:
- return self->bm->totvert;
- case BM_EDGES_OF_MESH:
- return self->bm->totedge;
- case BM_FACES_OF_MESH:
- return self->bm->totface;
-
- /* sub-types */
- case BM_VERTS_OF_FACE:
- case BM_EDGES_OF_FACE:
- case BM_LOOPS_OF_FACE:
- BPY_BM_CHECK_INT(self->py_ele);
- return ((BMFace *)self->py_ele->ele)->len;
-
- case BM_VERTS_OF_EDGE:
- return 2;
-
- default:
- /* quiet compiler */
- break;
- }
-
-
- /* loop over all items, avoid this if we can */
- {
- BMIter iter;
- BMHeader *ele;
- Py_ssize_t tot = 0;
-
- BM_ITER_BPY_BM_SEQ (ele, &iter, self) {
- tot++;
- }
- return tot;
- }
+ BPY_BM_CHECK_INT(self);
+
+ /* first check if the size is known */
+ switch ((BMIterType)self->itype) {
+ /* main-types */
+ case BM_VERTS_OF_MESH:
+ return self->bm->totvert;
+ case BM_EDGES_OF_MESH:
+ return self->bm->totedge;
+ case BM_FACES_OF_MESH:
+ return self->bm->totface;
+
+ /* sub-types */
+ case BM_VERTS_OF_FACE:
+ case BM_EDGES_OF_FACE:
+ case BM_LOOPS_OF_FACE:
+ BPY_BM_CHECK_INT(self->py_ele);
+ return ((BMFace *)self->py_ele->ele)->len;
+
+ case BM_VERTS_OF_EDGE:
+ return 2;
+
+ default:
+ /* quiet compiler */
+ break;
+ }
+
+ /* loop over all items, avoid this if we can */
+ {
+ BMIter iter;
+ BMHeader *ele;
+ Py_ssize_t tot = 0;
+
+ BM_ITER_BPY_BM_SEQ(ele, &iter, self)
+ {
+ tot++;
+ }
+ return tot;
+ }
}
static PyObject *bpy_bmelemseq_subscript_int(BPy_BMElemSeq *self, int keynum)
{
- BPY_BM_CHECK_OBJ(self);
-
- if (keynum < 0) {
- /* only get length on negative value, may loop entire seq */
- keynum += bpy_bmelemseq_length(self);
- }
- if (keynum >= 0) {
- if (self->itype <= BM_FACES_OF_MESH) {
- if ((self->bm->elem_table_dirty & bm_iter_itype_htype_map[self->itype]) == 0) {
- BMHeader *ele = NULL;
- switch (self->itype) {
- case BM_VERTS_OF_MESH:
- if (keynum < self->bm->totvert) {
- ele = (BMHeader *)self->bm->vtable[keynum];
- }
- break;
- case BM_EDGES_OF_MESH:
- if (keynum < self->bm->totedge) {
- ele = (BMHeader *)self->bm->etable[keynum];
- }
- break;
- case BM_FACES_OF_MESH:
- if (keynum < self->bm->totface) {
- ele = (BMHeader *)self->bm->ftable[keynum];
- }
- break;
- }
- if (ele) {
- return BPy_BMElem_CreatePyObject(self->bm, ele);
- }
- /* fall through to index error below */
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "BMElemSeq[index]: outdated internal index table, "
- "run ensure_lookup_table() first");
- return NULL;
- }
- }
- else {
- BMHeader *ele = BM_iter_at_index(self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL, keynum);
- if (ele) {
- return BPy_BMElem_CreatePyObject(self->bm, ele);
- }
- }
- }
-
- PyErr_Format(PyExc_IndexError,
- "BMElemSeq[index]: index %d out of range", keynum);
- return NULL;
-}
-
-static PyObject *bpy_bmelemseq_subscript_slice(BPy_BMElemSeq *self, Py_ssize_t start, Py_ssize_t stop)
-{
- BMIter iter;
- int count = 0;
- bool ok;
-
- PyObject *list;
- BMHeader *ele;
-
- BPY_BM_CHECK_OBJ(self);
-
- list = PyList_New(0);
-
- ok = BM_iter_init(&iter, self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL);
-
- BLI_assert(ok == true);
-
- if (UNLIKELY(ok == false)) {
- return list;
- }
-
- /* first loop up-until the start */
- for (ok = true; ok; ok = (BM_iter_step(&iter) != NULL)) {
- if (count == start) {
- break;
- }
- count++;
- }
-
- /* add items until stop */
- while ((ele = BM_iter_step(&iter))) {
- PyList_APPEND(list, BPy_BMElem_CreatePyObject(self->bm, ele));
-
- count++;
- if (count == stop) {
- break;
- }
- }
-
- return list;
+ BPY_BM_CHECK_OBJ(self);
+
+ if (keynum < 0) {
+ /* only get length on negative value, may loop entire seq */
+ keynum += bpy_bmelemseq_length(self);
+ }
+ if (keynum >= 0) {
+ if (self->itype <= BM_FACES_OF_MESH) {
+ if ((self->bm->elem_table_dirty & bm_iter_itype_htype_map[self->itype]) == 0) {
+ BMHeader *ele = NULL;
+ switch (self->itype) {
+ case BM_VERTS_OF_MESH:
+ if (keynum < self->bm->totvert) {
+ ele = (BMHeader *)self->bm->vtable[keynum];
+ }
+ break;
+ case BM_EDGES_OF_MESH:
+ if (keynum < self->bm->totedge) {
+ ele = (BMHeader *)self->bm->etable[keynum];
+ }
+ break;
+ case BM_FACES_OF_MESH:
+ if (keynum < self->bm->totface) {
+ ele = (BMHeader *)self->bm->ftable[keynum];
+ }
+ break;
+ }
+ if (ele) {
+ return BPy_BMElem_CreatePyObject(self->bm, ele);
+ }
+ /* fall through to index error below */
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError,
+ "BMElemSeq[index]: outdated internal index table, "
+ "run ensure_lookup_table() first");
+ return NULL;
+ }
+ }
+ else {
+ BMHeader *ele = BM_iter_at_index(
+ self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL, keynum);
+ if (ele) {
+ return BPy_BMElem_CreatePyObject(self->bm, ele);
+ }
+ }
+ }
+
+ PyErr_Format(PyExc_IndexError, "BMElemSeq[index]: index %d out of range", keynum);
+ return NULL;
+}
+
+static PyObject *bpy_bmelemseq_subscript_slice(BPy_BMElemSeq *self,
+ Py_ssize_t start,
+ Py_ssize_t stop)
+{
+ BMIter iter;
+ int count = 0;
+ bool ok;
+
+ PyObject *list;
+ BMHeader *ele;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ list = PyList_New(0);
+
+ ok = BM_iter_init(&iter, self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL);
+
+ BLI_assert(ok == true);
+
+ if (UNLIKELY(ok == false)) {
+ return list;
+ }
+
+ /* first loop up-until the start */
+ for (ok = true; ok; ok = (BM_iter_step(&iter) != NULL)) {
+ if (count == start) {
+ break;
+ }
+ count++;
+ }
+
+ /* add items until stop */
+ while ((ele = BM_iter_step(&iter))) {
+ PyList_APPEND(list, BPy_BMElem_CreatePyObject(self->bm, ele));
+
+ count++;
+ if (count == stop) {
+ break;
+ }
+ }
+
+ return list;
}
static PyObject *bpy_bmelemseq_subscript(BPy_BMElemSeq *self, PyObject *key)
{
- /* don't need error check here */
- if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- return bpy_bmelemseq_subscript_int(self, i);
- }
- else if (PySlice_Check(key)) {
- PySliceObject *key_slice = (PySliceObject *)key;
- Py_ssize_t step = 1;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError,
- "BMElemSeq[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- return bpy_bmelemseq_subscript_slice(self, 0, PY_SSIZE_T_MAX);
- }
- else {
- Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
-
- /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
- if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
- return NULL;
- }
- if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
- return NULL;
- }
-
- if (start < 0 || stop < 0) {
- /* only get the length for negative values */
- Py_ssize_t len = bpy_bmelemseq_length(self);
- if (start < 0) {
- start += len;
- }
- if (stop < 0) {
- stop += len;
- }
- }
-
- if (stop - start <= 0) {
- return PyList_New(0);
- }
- else {
- return bpy_bmelemseq_subscript_slice(self, start, stop);
- }
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "BMElemSeq[key]: invalid key, key must be an int");
- return NULL;
- }
+ /* don't need error check here */
+ if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ return bpy_bmelemseq_subscript_int(self, i);
+ }
+ else if (PySlice_Check(key)) {
+ PySliceObject *key_slice = (PySliceObject *)key;
+ Py_ssize_t step = 1;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "BMElemSeq[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ return bpy_bmelemseq_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ }
+ else {
+ Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
+
+ /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
+ if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
+ return NULL;
+ }
+ if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
+ return NULL;
+ }
+
+ if (start < 0 || stop < 0) {
+ /* only get the length for negative values */
+ Py_ssize_t len = bpy_bmelemseq_length(self);
+ if (start < 0) {
+ start += len;
+ }
+ if (stop < 0) {
+ stop += len;
+ }
+ }
+
+ if (stop - start <= 0) {
+ return PyList_New(0);
+ }
+ else {
+ return bpy_bmelemseq_subscript_slice(self, start, stop);
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "BMElemSeq[key]: invalid key, key must be an int");
+ return NULL;
+ }
}
static int bpy_bmelemseq_contains(BPy_BMElemSeq *self, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (Py_TYPE(value) == bpy_bm_itype_as_pytype(self->itype)) {
- BPy_BMElem *value_bm_ele = (BPy_BMElem *)value;
- if (value_bm_ele->bm == self->bm) {
- BMElem *ele, *ele_test = value_bm_ele->ele;
- BMIter iter;
- BM_ITER_BPY_BM_SEQ (ele, &iter, self) {
- if (ele == ele_test) {
- return 1;
- }
- }
- }
- }
+ if (Py_TYPE(value) == bpy_bm_itype_as_pytype(self->itype)) {
+ BPy_BMElem *value_bm_ele = (BPy_BMElem *)value;
+ if (value_bm_ele->bm == self->bm) {
+ BMElem *ele, *ele_test = value_bm_ele->ele;
+ BMIter iter;
+ BM_ITER_BPY_BM_SEQ(ele, &iter, self)
+ {
+ if (ele == ele_test) {
+ return 1;
+ }
+ }
+ }
+ }
- return 0;
+ return 0;
}
/* BMElem (customdata)
@@ -3114,42 +3360,44 @@ static int bpy_bmelemseq_contains(BPy_BMElemSeq *self, PyObject *value)
static PyObject *bpy_bmelem_subscript(BPy_BMElem *self, BPy_BMLayerItem *key)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return BPy_BMLayerItem_GetItem(self, key);
+ return BPy_BMLayerItem_GetItem(self, key);
}
static int bpy_bmelem_ass_subscript(BPy_BMElem *self, BPy_BMLayerItem *key, PyObject *value)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- return BPy_BMLayerItem_SetItem(self, key, value);
+ return BPy_BMLayerItem_SetItem(self, key, value);
}
static PySequenceMethods bpy_bmelemseq_as_sequence = {
- (lenfunc)bpy_bmelemseq_length, /* sq_length */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- (ssizeargfunc)bpy_bmelemseq_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* sq_slice */
- (ssizeobjargproc)NULL, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)bpy_bmelemseq_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)bpy_bmelemseq_length, /* sq_length */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ (ssizeargfunc)bpy_bmelemseq_subscript_int,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* sq_slice */
+ (ssizeobjargproc)NULL, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)bpy_bmelemseq_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyMappingMethods bpy_bmelemseq_as_mapping = {
- (lenfunc)bpy_bmelemseq_length, /* mp_length */
- (binaryfunc)bpy_bmelemseq_subscript, /* mp_subscript */
- (objobjargproc)NULL, /* mp_ass_subscript */
+ (lenfunc)bpy_bmelemseq_length, /* mp_length */
+ (binaryfunc)bpy_bmelemseq_subscript, /* mp_subscript */
+ (objobjargproc)NULL, /* mp_ass_subscript */
};
/* for customdata access */
static PyMappingMethods bpy_bm_elem_as_mapping = {
- (lenfunc)NULL, /* mp_length */ /* keep this empty, messes up 'if elem: ...' test */
- (binaryfunc)bpy_bmelem_subscript, /* mp_subscript */
- (objobjargproc)bpy_bmelem_ass_subscript, /* mp_ass_subscript */
+ (lenfunc)NULL,
+ /* mp_length */ /* keep this empty, messes up 'if elem: ...' test */
+ (binaryfunc)bpy_bmelem_subscript, /* mp_subscript */
+ (objobjargproc)bpy_bmelem_ass_subscript, /* mp_ass_subscript */
};
/* Iterator
@@ -3157,230 +3405,228 @@ static PyMappingMethods bpy_bm_elem_as_mapping = {
static PyObject *bpy_bmelemseq_iter(BPy_BMElemSeq *self)
{
- BPy_BMIter *py_iter;
+ BPy_BMIter *py_iter;
- BPY_BM_CHECK_OBJ(self);
- py_iter = (BPy_BMIter *)BPy_BMIter_CreatePyObject(self->bm);
- BM_iter_init(&(py_iter->iter), self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL);
- return (PyObject *)py_iter;
+ BPY_BM_CHECK_OBJ(self);
+ py_iter = (BPy_BMIter *)BPy_BMIter_CreatePyObject(self->bm);
+ BM_iter_init(&(py_iter->iter), self->bm, self->itype, self->py_ele ? self->py_ele->ele : NULL);
+ return (PyObject *)py_iter;
}
static PyObject *bpy_bmiter_next(BPy_BMIter *self)
{
- BMHeader *ele = BM_iter_step(&self->iter);
- if (ele == NULL) {
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
- else {
- return (PyObject *)BPy_BMElem_CreatePyObject(self->bm, ele);
- }
+ BMHeader *ele = BM_iter_step(&self->iter);
+ if (ele == NULL) {
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+ else {
+ return (PyObject *)BPy_BMElem_CreatePyObject(self->bm, ele);
+ }
}
-
/* Dealloc Functions
* ================= */
static void bpy_bmesh_dealloc(BPy_BMesh *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- /* have have been freed by bmesh */
- if (bm) {
- bm_dealloc_editmode_warn(self);
+ /* have have been freed by bmesh */
+ if (bm) {
+ bm_dealloc_editmode_warn(self);
- if (CustomData_has_layer(&bm->vdata, CD_BM_ELEM_PYPTR)) {
- BM_data_layer_free(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
- }
- if (CustomData_has_layer(&bm->edata, CD_BM_ELEM_PYPTR)) {
- BM_data_layer_free(bm, &bm->edata, CD_BM_ELEM_PYPTR);
- }
- if (CustomData_has_layer(&bm->pdata, CD_BM_ELEM_PYPTR)) {
- BM_data_layer_free(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
- }
- if (CustomData_has_layer(&bm->ldata, CD_BM_ELEM_PYPTR)) {
- BM_data_layer_free(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
- }
+ if (CustomData_has_layer(&bm->vdata, CD_BM_ELEM_PYPTR)) {
+ BM_data_layer_free(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
+ }
+ if (CustomData_has_layer(&bm->edata, CD_BM_ELEM_PYPTR)) {
+ BM_data_layer_free(bm, &bm->edata, CD_BM_ELEM_PYPTR);
+ }
+ if (CustomData_has_layer(&bm->pdata, CD_BM_ELEM_PYPTR)) {
+ BM_data_layer_free(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
+ }
+ if (CustomData_has_layer(&bm->ldata, CD_BM_ELEM_PYPTR)) {
+ BM_data_layer_free(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
+ }
- bm->py_handle = NULL;
+ bm->py_handle = NULL;
- if ((self->flag & BPY_BMFLAG_IS_WRAPPED) == 0) {
- BM_mesh_free(bm);
- }
- }
+ if ((self->flag & BPY_BMFLAG_IS_WRAPPED) == 0) {
+ BM_mesh_free(bm);
+ }
+ }
- PyObject_DEL(self);
+ PyObject_DEL(self);
}
static void bpy_bmvert_dealloc(BPy_BMElem *self)
{
- BMesh *bm = self->bm;
- if (bm) {
- void **ptr = CustomData_bmesh_get(&bm->vdata, self->ele->head.data, CD_BM_ELEM_PYPTR);
- if (ptr) {
- *ptr = NULL;
- }
- }
- PyObject_DEL(self);
+ BMesh *bm = self->bm;
+ if (bm) {
+ void **ptr = CustomData_bmesh_get(&bm->vdata, self->ele->head.data, CD_BM_ELEM_PYPTR);
+ if (ptr) {
+ *ptr = NULL;
+ }
+ }
+ PyObject_DEL(self);
}
static void bpy_bmedge_dealloc(BPy_BMElem *self)
{
- BMesh *bm = self->bm;
- if (bm) {
- void **ptr = CustomData_bmesh_get(&bm->edata, self->ele->head.data, CD_BM_ELEM_PYPTR);
- if (ptr) {
- *ptr = NULL;
- }
- }
- PyObject_DEL(self);
+ BMesh *bm = self->bm;
+ if (bm) {
+ void **ptr = CustomData_bmesh_get(&bm->edata, self->ele->head.data, CD_BM_ELEM_PYPTR);
+ if (ptr) {
+ *ptr = NULL;
+ }
+ }
+ PyObject_DEL(self);
}
static void bpy_bmface_dealloc(BPy_BMElem *self)
{
- BMesh *bm = self->bm;
- if (bm) {
- void **ptr = CustomData_bmesh_get(&bm->pdata, self->ele->head.data, CD_BM_ELEM_PYPTR);
- if (ptr) {
- *ptr = NULL;
- }
- }
- PyObject_DEL(self);
+ BMesh *bm = self->bm;
+ if (bm) {
+ void **ptr = CustomData_bmesh_get(&bm->pdata, self->ele->head.data, CD_BM_ELEM_PYPTR);
+ if (ptr) {
+ *ptr = NULL;
+ }
+ }
+ PyObject_DEL(self);
}
static void bpy_bmloop_dealloc(BPy_BMElem *self)
{
- BMesh *bm = self->bm;
- if (bm) {
- void **ptr = CustomData_bmesh_get(&bm->ldata, self->ele->head.data, CD_BM_ELEM_PYPTR);
- if (ptr) {
- *ptr = NULL;
- }
- }
- PyObject_DEL(self);
+ BMesh *bm = self->bm;
+ if (bm) {
+ void **ptr = CustomData_bmesh_get(&bm->ldata, self->ele->head.data, CD_BM_ELEM_PYPTR);
+ if (ptr) {
+ *ptr = NULL;
+ }
+ }
+ PyObject_DEL(self);
}
static void bpy_bmelemseq_dealloc(BPy_BMElemSeq *self)
{
- Py_XDECREF(self->py_ele);
+ Py_XDECREF(self->py_ele);
- PyObject_DEL(self);
+ PyObject_DEL(self);
}
/* not sure where this should go */
static Py_hash_t bpy_bm_elem_hash(PyObject *self)
{
- return _Py_HashPointer(((BPy_BMElem *)self)->ele);
+ return _Py_HashPointer(((BPy_BMElem *)self)->ele);
}
static Py_hash_t bpy_bm_hash(PyObject *self)
{
- return _Py_HashPointer(((BPy_BMesh *)self)->bm);
+ return _Py_HashPointer(((BPy_BMesh *)self)->bm);
}
/* Type Docstrings
* =============== */
-PyDoc_STRVAR(bpy_bmesh_doc,
-"The BMesh data structure\n"
-);
-PyDoc_STRVAR(bpy_bmvert_doc,
-"The BMesh vertex type\n"
-);
-PyDoc_STRVAR(bpy_bmedge_doc,
-"The BMesh edge connecting 2 verts\n"
-);
-PyDoc_STRVAR(bpy_bmface_doc,
-"The BMesh face with 3 or more sides\n"
-);
+PyDoc_STRVAR(bpy_bmesh_doc, "The BMesh data structure\n");
+PyDoc_STRVAR(bpy_bmvert_doc, "The BMesh vertex type\n");
+PyDoc_STRVAR(bpy_bmedge_doc, "The BMesh edge connecting 2 verts\n");
+PyDoc_STRVAR(bpy_bmface_doc, "The BMesh face with 3 or more sides\n");
PyDoc_STRVAR(bpy_bmloop_doc,
-"This is normally accessed from :class:`BMFace.loops` where each face loop represents a corner of the face.\n"
-);
+ "This is normally accessed from :class:`BMFace.loops` where each face loop "
+ "represents a corner of the face.\n");
PyDoc_STRVAR(bpy_bmelemseq_doc,
-"General sequence type used for accessing any sequence of\n"
-":class:`BMVert`, :class:`BMEdge`, :class:`BMFace`, :class:`BMLoop`.\n"
-"\n"
-"When accessed via :class:`BMesh.verts`, :class:`BMesh.edges`, :class:`BMesh.faces`\n"
-"there are also functions to create/remomove items.\n"
-);
+ "General sequence type used for accessing any sequence of\n"
+ ":class:`BMVert`, :class:`BMEdge`, :class:`BMFace`, :class:`BMLoop`.\n"
+ "\n"
+ "When accessed via :class:`BMesh.verts`, :class:`BMesh.edges`, :class:`BMesh.faces`\n"
+ "there are also functions to create/remomove items.\n");
PyDoc_STRVAR(bpy_bmiter_doc,
-"Internal BMesh type for looping over verts/faces/edges,\n"
-"used for iterating over :class:`BMElemSeq` types.\n"
-);
+ "Internal BMesh type for looping over verts/faces/edges,\n"
+ "used for iterating over :class:`BMElemSeq` types.\n");
static PyObject *bpy_bmesh_repr(BPy_BMesh *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- if (bm) {
- return PyUnicode_FromFormat("<BMesh(%p), totvert=%d, totedge=%d, totface=%d, totloop=%d>",
- bm, bm->totvert, bm->totedge, bm->totface, bm->totloop);
- }
- else {
- return PyUnicode_FromFormat("<BMesh dead at %p>", self);
- }
+ if (bm) {
+ return PyUnicode_FromFormat("<BMesh(%p), totvert=%d, totedge=%d, totface=%d, totloop=%d>",
+ bm,
+ bm->totvert,
+ bm->totedge,
+ bm->totface,
+ bm->totloop);
+ }
+ else {
+ return PyUnicode_FromFormat("<BMesh dead at %p>", self);
+ }
}
static PyObject *bpy_bmvert_repr(BPy_BMVert *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- if (bm) {
- BMVert *v = self->v;
- return PyUnicode_FromFormat("<BMVert(%p), index=%d>",
- v, BM_elem_index_get(v));
- }
- else {
- return PyUnicode_FromFormat("<BMVert dead at %p>", self);
- }
+ if (bm) {
+ BMVert *v = self->v;
+ return PyUnicode_FromFormat("<BMVert(%p), index=%d>", v, BM_elem_index_get(v));
+ }
+ else {
+ return PyUnicode_FromFormat("<BMVert dead at %p>", self);
+ }
}
static PyObject *bpy_bmedge_repr(BPy_BMEdge *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- if (bm) {
- BMEdge *e = self->e;
- return PyUnicode_FromFormat("<BMEdge(%p), index=%d, verts=(%p/%d, %p/%d)>",
- e, BM_elem_index_get(e),
- e->v1, BM_elem_index_get(e->v1),
- e->v2, BM_elem_index_get(e->v2));
- }
- else {
- return PyUnicode_FromFormat("<BMEdge dead at %p>", self);
- }
+ if (bm) {
+ BMEdge *e = self->e;
+ return PyUnicode_FromFormat("<BMEdge(%p), index=%d, verts=(%p/%d, %p/%d)>",
+ e,
+ BM_elem_index_get(e),
+ e->v1,
+ BM_elem_index_get(e->v1),
+ e->v2,
+ BM_elem_index_get(e->v2));
+ }
+ else {
+ return PyUnicode_FromFormat("<BMEdge dead at %p>", self);
+ }
}
static PyObject *bpy_bmface_repr(BPy_BMFace *self)
{
- BMesh *bm = self->bm;
+ BMesh *bm = self->bm;
- if (bm) {
- BMFace *f = self->f;
- return PyUnicode_FromFormat("<BMFace(%p), index=%d, totverts=%d>",
- f, BM_elem_index_get(f),
- f->len);
- }
- else {
- return PyUnicode_FromFormat("<BMFace dead at %p>", self);
- }
+ if (bm) {
+ BMFace *f = self->f;
+ return PyUnicode_FromFormat(
+ "<BMFace(%p), index=%d, totverts=%d>", f, BM_elem_index_get(f), f->len);
+ }
+ else {
+ return PyUnicode_FromFormat("<BMFace dead at %p>", self);
+ }
}
static PyObject *bpy_bmloop_repr(BPy_BMLoop *self)
{
- BMesh *bm = self->bm;
-
- if (bm) {
- BMLoop *l = self->l;
- return PyUnicode_FromFormat("<BMLoop(%p), index=%d, vert=%p/%d, edge=%p/%d, face=%p/%d>",
- l, BM_elem_index_get(l),
- l->v, BM_elem_index_get(l->v),
- l->e, BM_elem_index_get(l->e),
- l->f, BM_elem_index_get(l->f));
- }
- else {
- return PyUnicode_FromFormat("<BMLoop dead at %p>", self);
- }
+ BMesh *bm = self->bm;
+
+ if (bm) {
+ BMLoop *l = self->l;
+ return PyUnicode_FromFormat("<BMLoop(%p), index=%d, vert=%p/%d, edge=%p/%d, face=%p/%d>",
+ l,
+ BM_elem_index_get(l),
+ l->v,
+ BM_elem_index_get(l->v),
+ l->e,
+ BM_elem_index_get(l->e),
+ l->f,
+ BM_elem_index_get(l->f));
+ }
+ else {
+ return PyUnicode_FromFormat("<BMLoop dead at %p>", self);
+ }
}
/* Types
@@ -3398,220 +3644,213 @@ PyTypeObject BPy_BMFaceSeq_Type;
PyTypeObject BPy_BMLoopSeq_Type;
PyTypeObject BPy_BMIter_Type;
-
-
void BPy_BM_init_types(void)
{
- BPy_BMesh_Type.tp_basicsize = sizeof(BPy_BMesh);
- BPy_BMVert_Type.tp_basicsize = sizeof(BPy_BMVert);
- BPy_BMEdge_Type.tp_basicsize = sizeof(BPy_BMEdge);
- BPy_BMFace_Type.tp_basicsize = sizeof(BPy_BMFace);
- BPy_BMLoop_Type.tp_basicsize = sizeof(BPy_BMLoop);
- BPy_BMElemSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
- BPy_BMVertSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
- BPy_BMEdgeSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
- BPy_BMFaceSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
- BPy_BMLoopSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
- BPy_BMIter_Type.tp_basicsize = sizeof(BPy_BMIter);
-
-
- BPy_BMesh_Type.tp_name = "BMesh";
- BPy_BMVert_Type.tp_name = "BMVert";
- BPy_BMEdge_Type.tp_name = "BMEdge";
- BPy_BMFace_Type.tp_name = "BMFace";
- BPy_BMLoop_Type.tp_name = "BMLoop";
- BPy_BMElemSeq_Type.tp_name = "BMElemSeq";
- BPy_BMVertSeq_Type.tp_name = "BMVertSeq";
- BPy_BMEdgeSeq_Type.tp_name = "BMEdgeSeq";
- BPy_BMFaceSeq_Type.tp_name = "BMFaceSeq";
- BPy_BMLoopSeq_Type.tp_name = "BMLoopSeq";
- BPy_BMIter_Type.tp_name = "BMIter";
-
-
- BPy_BMesh_Type.tp_doc = bpy_bmesh_doc;
- BPy_BMVert_Type.tp_doc = bpy_bmvert_doc;
- BPy_BMEdge_Type.tp_doc = bpy_bmedge_doc;
- BPy_BMFace_Type.tp_doc = bpy_bmface_doc;
- BPy_BMLoop_Type.tp_doc = bpy_bmloop_doc;
- BPy_BMElemSeq_Type.tp_doc = bpy_bmelemseq_doc;
- BPy_BMVertSeq_Type.tp_doc = NULL;
- BPy_BMEdgeSeq_Type.tp_doc = NULL;
- BPy_BMFaceSeq_Type.tp_doc = NULL;
- BPy_BMLoopSeq_Type.tp_doc = NULL;
- BPy_BMIter_Type.tp_doc = bpy_bmiter_doc;
-
-
- BPy_BMesh_Type.tp_repr = (reprfunc)bpy_bmesh_repr;
- BPy_BMVert_Type.tp_repr = (reprfunc)bpy_bmvert_repr;
- BPy_BMEdge_Type.tp_repr = (reprfunc)bpy_bmedge_repr;
- BPy_BMFace_Type.tp_repr = (reprfunc)bpy_bmface_repr;
- BPy_BMLoop_Type.tp_repr = (reprfunc)bpy_bmloop_repr;
- BPy_BMElemSeq_Type.tp_repr = NULL;
- BPy_BMVertSeq_Type.tp_repr = NULL;
- BPy_BMEdgeSeq_Type.tp_repr = NULL;
- BPy_BMFaceSeq_Type.tp_repr = NULL;
- BPy_BMLoopSeq_Type.tp_repr = NULL;
- BPy_BMIter_Type.tp_repr = NULL;
-
-
- BPy_BMesh_Type.tp_getset = bpy_bmesh_getseters;
- BPy_BMVert_Type.tp_getset = bpy_bmvert_getseters;
- BPy_BMEdge_Type.tp_getset = bpy_bmedge_getseters;
- BPy_BMFace_Type.tp_getset = bpy_bmface_getseters;
- BPy_BMLoop_Type.tp_getset = bpy_bmloop_getseters;
- BPy_BMElemSeq_Type.tp_getset = NULL;
- BPy_BMVertSeq_Type.tp_getset = bpy_bmvertseq_getseters;
- BPy_BMEdgeSeq_Type.tp_getset = bpy_bmedgeseq_getseters;
- BPy_BMFaceSeq_Type.tp_getset = bpy_bmfaceseq_getseters;
- BPy_BMLoopSeq_Type.tp_getset = bpy_bmloopseq_getseters;
- BPy_BMIter_Type.tp_getset = NULL;
-
-
- BPy_BMesh_Type.tp_methods = bpy_bmesh_methods;
- BPy_BMVert_Type.tp_methods = bpy_bmvert_methods;
- BPy_BMEdge_Type.tp_methods = bpy_bmedge_methods;
- BPy_BMFace_Type.tp_methods = bpy_bmface_methods;
- BPy_BMLoop_Type.tp_methods = bpy_bmloop_methods;
- BPy_BMElemSeq_Type.tp_methods = bpy_bmelemseq_methods;
- BPy_BMVertSeq_Type.tp_methods = bpy_bmvertseq_methods;
- BPy_BMEdgeSeq_Type.tp_methods = bpy_bmedgeseq_methods;
- BPy_BMFaceSeq_Type.tp_methods = bpy_bmfaceseq_methods;
- BPy_BMLoopSeq_Type.tp_methods = bpy_bmloopseq_methods;
- BPy_BMIter_Type.tp_methods = NULL;
-
- /*BPy_BMElem_Check() uses bpy_bm_elem_hash() to check types.
- * if this changes update the macro */
- BPy_BMesh_Type.tp_hash = bpy_bm_hash;
- BPy_BMVert_Type.tp_hash = bpy_bm_elem_hash;
- BPy_BMEdge_Type.tp_hash = bpy_bm_elem_hash;
- BPy_BMFace_Type.tp_hash = bpy_bm_elem_hash;
- BPy_BMLoop_Type.tp_hash = bpy_bm_elem_hash;
- BPy_BMElemSeq_Type.tp_hash = NULL;
- BPy_BMVertSeq_Type.tp_hash = NULL;
- BPy_BMEdgeSeq_Type.tp_hash = NULL;
- BPy_BMFaceSeq_Type.tp_hash = NULL;
- BPy_BMLoopSeq_Type.tp_hash = NULL;
- BPy_BMIter_Type.tp_hash = NULL;
-
- BPy_BMElemSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
- BPy_BMVertSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
- BPy_BMEdgeSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
- BPy_BMFaceSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
- BPy_BMLoopSeq_Type.tp_as_sequence = NULL; /* this is not a seq really, only for layer access */
-
- BPy_BMElemSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
- BPy_BMVertSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
- BPy_BMEdgeSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
- BPy_BMFaceSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
- BPy_BMLoopSeq_Type.tp_as_mapping = NULL; /* this is not a seq really, only for layer access */
-
- /* layer access */
- BPy_BMVert_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
- BPy_BMEdge_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
- BPy_BMFace_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
- BPy_BMLoop_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
-
- BPy_BMElemSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
- BPy_BMVertSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
- BPy_BMEdgeSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
- BPy_BMFaceSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
- BPy_BMLoopSeq_Type.tp_iter = NULL; /* no mapping */
-
- /* only 1 iteratir so far */
- BPy_BMIter_Type.tp_iternext = (iternextfunc)bpy_bmiter_next;
- BPy_BMIter_Type.tp_iter = PyObject_SelfIter;
-
- BPy_BMesh_Type.tp_dealloc = (destructor)bpy_bmesh_dealloc;
- BPy_BMVert_Type.tp_dealloc = (destructor)bpy_bmvert_dealloc;
- BPy_BMEdge_Type.tp_dealloc = (destructor)bpy_bmedge_dealloc;
- BPy_BMFace_Type.tp_dealloc = (destructor)bpy_bmface_dealloc;
- BPy_BMLoop_Type.tp_dealloc = (destructor)bpy_bmloop_dealloc;
- BPy_BMElemSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
- BPy_BMVertSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
- BPy_BMEdgeSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
- BPy_BMFaceSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
- BPy_BMLoopSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
- BPy_BMIter_Type.tp_dealloc = NULL;
-
- BPy_BMesh_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMEdge_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMFace_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLoop_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMElemSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMVertSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMEdgeSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMFaceSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLoopSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMIter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
-
-
- PyType_Ready(&BPy_BMesh_Type);
- PyType_Ready(&BPy_BMVert_Type);
- PyType_Ready(&BPy_BMEdge_Type);
- PyType_Ready(&BPy_BMFace_Type);
- PyType_Ready(&BPy_BMLoop_Type);
- PyType_Ready(&BPy_BMElemSeq_Type);
- PyType_Ready(&BPy_BMVertSeq_Type);
- PyType_Ready(&BPy_BMEdgeSeq_Type);
- PyType_Ready(&BPy_BMFaceSeq_Type);
- PyType_Ready(&BPy_BMLoopSeq_Type);
- PyType_Ready(&BPy_BMIter_Type);
+ BPy_BMesh_Type.tp_basicsize = sizeof(BPy_BMesh);
+ BPy_BMVert_Type.tp_basicsize = sizeof(BPy_BMVert);
+ BPy_BMEdge_Type.tp_basicsize = sizeof(BPy_BMEdge);
+ BPy_BMFace_Type.tp_basicsize = sizeof(BPy_BMFace);
+ BPy_BMLoop_Type.tp_basicsize = sizeof(BPy_BMLoop);
+ BPy_BMElemSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
+ BPy_BMVertSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
+ BPy_BMEdgeSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
+ BPy_BMFaceSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
+ BPy_BMLoopSeq_Type.tp_basicsize = sizeof(BPy_BMElemSeq);
+ BPy_BMIter_Type.tp_basicsize = sizeof(BPy_BMIter);
+
+ BPy_BMesh_Type.tp_name = "BMesh";
+ BPy_BMVert_Type.tp_name = "BMVert";
+ BPy_BMEdge_Type.tp_name = "BMEdge";
+ BPy_BMFace_Type.tp_name = "BMFace";
+ BPy_BMLoop_Type.tp_name = "BMLoop";
+ BPy_BMElemSeq_Type.tp_name = "BMElemSeq";
+ BPy_BMVertSeq_Type.tp_name = "BMVertSeq";
+ BPy_BMEdgeSeq_Type.tp_name = "BMEdgeSeq";
+ BPy_BMFaceSeq_Type.tp_name = "BMFaceSeq";
+ BPy_BMLoopSeq_Type.tp_name = "BMLoopSeq";
+ BPy_BMIter_Type.tp_name = "BMIter";
+
+ BPy_BMesh_Type.tp_doc = bpy_bmesh_doc;
+ BPy_BMVert_Type.tp_doc = bpy_bmvert_doc;
+ BPy_BMEdge_Type.tp_doc = bpy_bmedge_doc;
+ BPy_BMFace_Type.tp_doc = bpy_bmface_doc;
+ BPy_BMLoop_Type.tp_doc = bpy_bmloop_doc;
+ BPy_BMElemSeq_Type.tp_doc = bpy_bmelemseq_doc;
+ BPy_BMVertSeq_Type.tp_doc = NULL;
+ BPy_BMEdgeSeq_Type.tp_doc = NULL;
+ BPy_BMFaceSeq_Type.tp_doc = NULL;
+ BPy_BMLoopSeq_Type.tp_doc = NULL;
+ BPy_BMIter_Type.tp_doc = bpy_bmiter_doc;
+
+ BPy_BMesh_Type.tp_repr = (reprfunc)bpy_bmesh_repr;
+ BPy_BMVert_Type.tp_repr = (reprfunc)bpy_bmvert_repr;
+ BPy_BMEdge_Type.tp_repr = (reprfunc)bpy_bmedge_repr;
+ BPy_BMFace_Type.tp_repr = (reprfunc)bpy_bmface_repr;
+ BPy_BMLoop_Type.tp_repr = (reprfunc)bpy_bmloop_repr;
+ BPy_BMElemSeq_Type.tp_repr = NULL;
+ BPy_BMVertSeq_Type.tp_repr = NULL;
+ BPy_BMEdgeSeq_Type.tp_repr = NULL;
+ BPy_BMFaceSeq_Type.tp_repr = NULL;
+ BPy_BMLoopSeq_Type.tp_repr = NULL;
+ BPy_BMIter_Type.tp_repr = NULL;
+
+ BPy_BMesh_Type.tp_getset = bpy_bmesh_getseters;
+ BPy_BMVert_Type.tp_getset = bpy_bmvert_getseters;
+ BPy_BMEdge_Type.tp_getset = bpy_bmedge_getseters;
+ BPy_BMFace_Type.tp_getset = bpy_bmface_getseters;
+ BPy_BMLoop_Type.tp_getset = bpy_bmloop_getseters;
+ BPy_BMElemSeq_Type.tp_getset = NULL;
+ BPy_BMVertSeq_Type.tp_getset = bpy_bmvertseq_getseters;
+ BPy_BMEdgeSeq_Type.tp_getset = bpy_bmedgeseq_getseters;
+ BPy_BMFaceSeq_Type.tp_getset = bpy_bmfaceseq_getseters;
+ BPy_BMLoopSeq_Type.tp_getset = bpy_bmloopseq_getseters;
+ BPy_BMIter_Type.tp_getset = NULL;
+
+ BPy_BMesh_Type.tp_methods = bpy_bmesh_methods;
+ BPy_BMVert_Type.tp_methods = bpy_bmvert_methods;
+ BPy_BMEdge_Type.tp_methods = bpy_bmedge_methods;
+ BPy_BMFace_Type.tp_methods = bpy_bmface_methods;
+ BPy_BMLoop_Type.tp_methods = bpy_bmloop_methods;
+ BPy_BMElemSeq_Type.tp_methods = bpy_bmelemseq_methods;
+ BPy_BMVertSeq_Type.tp_methods = bpy_bmvertseq_methods;
+ BPy_BMEdgeSeq_Type.tp_methods = bpy_bmedgeseq_methods;
+ BPy_BMFaceSeq_Type.tp_methods = bpy_bmfaceseq_methods;
+ BPy_BMLoopSeq_Type.tp_methods = bpy_bmloopseq_methods;
+ BPy_BMIter_Type.tp_methods = NULL;
+
+ /*BPy_BMElem_Check() uses bpy_bm_elem_hash() to check types.
+ * if this changes update the macro */
+ BPy_BMesh_Type.tp_hash = bpy_bm_hash;
+ BPy_BMVert_Type.tp_hash = bpy_bm_elem_hash;
+ BPy_BMEdge_Type.tp_hash = bpy_bm_elem_hash;
+ BPy_BMFace_Type.tp_hash = bpy_bm_elem_hash;
+ BPy_BMLoop_Type.tp_hash = bpy_bm_elem_hash;
+ BPy_BMElemSeq_Type.tp_hash = NULL;
+ BPy_BMVertSeq_Type.tp_hash = NULL;
+ BPy_BMEdgeSeq_Type.tp_hash = NULL;
+ BPy_BMFaceSeq_Type.tp_hash = NULL;
+ BPy_BMLoopSeq_Type.tp_hash = NULL;
+ BPy_BMIter_Type.tp_hash = NULL;
+
+ BPy_BMElemSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
+ BPy_BMVertSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
+ BPy_BMEdgeSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
+ BPy_BMFaceSeq_Type.tp_as_sequence = &bpy_bmelemseq_as_sequence;
+ BPy_BMLoopSeq_Type.tp_as_sequence = NULL; /* this is not a seq really, only for layer access */
+
+ BPy_BMElemSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
+ BPy_BMVertSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
+ BPy_BMEdgeSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
+ BPy_BMFaceSeq_Type.tp_as_mapping = &bpy_bmelemseq_as_mapping;
+ BPy_BMLoopSeq_Type.tp_as_mapping = NULL; /* this is not a seq really, only for layer access */
+
+ /* layer access */
+ BPy_BMVert_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
+ BPy_BMEdge_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
+ BPy_BMFace_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
+ BPy_BMLoop_Type.tp_as_mapping = &bpy_bm_elem_as_mapping;
+
+ BPy_BMElemSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
+ BPy_BMVertSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
+ BPy_BMEdgeSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
+ BPy_BMFaceSeq_Type.tp_iter = (getiterfunc)bpy_bmelemseq_iter;
+ BPy_BMLoopSeq_Type.tp_iter = NULL; /* no mapping */
+
+ /* only 1 iteratir so far */
+ BPy_BMIter_Type.tp_iternext = (iternextfunc)bpy_bmiter_next;
+ BPy_BMIter_Type.tp_iter = PyObject_SelfIter;
+
+ BPy_BMesh_Type.tp_dealloc = (destructor)bpy_bmesh_dealloc;
+ BPy_BMVert_Type.tp_dealloc = (destructor)bpy_bmvert_dealloc;
+ BPy_BMEdge_Type.tp_dealloc = (destructor)bpy_bmedge_dealloc;
+ BPy_BMFace_Type.tp_dealloc = (destructor)bpy_bmface_dealloc;
+ BPy_BMLoop_Type.tp_dealloc = (destructor)bpy_bmloop_dealloc;
+ BPy_BMElemSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
+ BPy_BMVertSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
+ BPy_BMEdgeSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
+ BPy_BMFaceSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
+ BPy_BMLoopSeq_Type.tp_dealloc = (destructor)bpy_bmelemseq_dealloc;
+ BPy_BMIter_Type.tp_dealloc = NULL;
+
+ BPy_BMesh_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMEdge_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMFace_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLoop_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMElemSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMVertSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMEdgeSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMFaceSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLoopSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMIter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+
+ PyType_Ready(&BPy_BMesh_Type);
+ PyType_Ready(&BPy_BMVert_Type);
+ PyType_Ready(&BPy_BMEdge_Type);
+ PyType_Ready(&BPy_BMFace_Type);
+ PyType_Ready(&BPy_BMLoop_Type);
+ PyType_Ready(&BPy_BMElemSeq_Type);
+ PyType_Ready(&BPy_BMVertSeq_Type);
+ PyType_Ready(&BPy_BMEdgeSeq_Type);
+ PyType_Ready(&BPy_BMFaceSeq_Type);
+ PyType_Ready(&BPy_BMLoopSeq_Type);
+ PyType_Ready(&BPy_BMIter_Type);
}
/* bmesh.types submodule
* ********************* */
static struct PyModuleDef BPy_BM_types_module_def = {
- PyModuleDef_HEAD_INIT,
- "bmesh.types", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bmesh.types", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit_bmesh_types(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPy_BM_types_module_def);
+ submodule = PyModule_Create(&BPy_BM_types_module_def);
#define MODULE_TYPE_ADD(s, t) \
- PyModule_AddObject(s, t.tp_name, (PyObject *)&t); Py_INCREF((PyObject *)&t)
-
- /* bmesh_py_types.c */
- MODULE_TYPE_ADD(submodule, BPy_BMesh_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMVert_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMEdge_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMFace_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLoop_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMElemSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMVertSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMEdgeSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMFaceSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLoopSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMIter_Type);
- /* bmesh_py_types_select.c */
- MODULE_TYPE_ADD(submodule, BPy_BMEditSelSeq_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMEditSelIter_Type);
- /* bmesh_py_types_customdata.c */
- MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessVert_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessEdge_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessFace_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessLoop_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLayerCollection_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMLayerItem_Type);
- /* bmesh_py_types_meshdata.c */
- MODULE_TYPE_ADD(submodule, BPy_BMLoopUV_Type);
- MODULE_TYPE_ADD(submodule, BPy_BMDeformVert_Type);
+ PyModule_AddObject(s, t.tp_name, (PyObject *)&t); \
+ Py_INCREF((PyObject *)&t)
+
+ /* bmesh_py_types.c */
+ MODULE_TYPE_ADD(submodule, BPy_BMesh_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMVert_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMEdge_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMFace_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLoop_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMElemSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMVertSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMEdgeSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMFaceSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLoopSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMIter_Type);
+ /* bmesh_py_types_select.c */
+ MODULE_TYPE_ADD(submodule, BPy_BMEditSelSeq_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMEditSelIter_Type);
+ /* bmesh_py_types_customdata.c */
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessVert_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessEdge_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessFace_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerAccessLoop_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerCollection_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMLayerItem_Type);
+ /* bmesh_py_types_meshdata.c */
+ MODULE_TYPE_ADD(submodule, BPy_BMLoopUV_Type);
+ MODULE_TYPE_ADD(submodule, BPy_BMDeformVert_Type);
#undef MODULE_TYPE_ADD
- return submodule;
+ return submodule;
}
/* Utility Functions
@@ -3619,272 +3858,273 @@ PyObject *BPyInit_bmesh_types(void)
PyObject *BPy_BMesh_CreatePyObject(BMesh *bm, int flag)
{
- BPy_BMesh *self;
+ BPy_BMesh *self;
- if (bm->py_handle) {
- self = bm->py_handle;
- Py_INCREF(self);
- }
- else {
- self = PyObject_New(BPy_BMesh, &BPy_BMesh_Type);
- self->bm = bm;
- self->flag = flag;
+ if (bm->py_handle) {
+ self = bm->py_handle;
+ Py_INCREF(self);
+ }
+ else {
+ self = PyObject_New(BPy_BMesh, &BPy_BMesh_Type);
+ self->bm = bm;
+ self->flag = flag;
- bm->py_handle = self; /* point back */
+ bm->py_handle = self; /* point back */
- /* avoid allocating layers when we don't have to */
+ /* avoid allocating layers when we don't have to */
#if 0
- BM_data_layer_add(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
- BM_data_layer_add(bm, &bm->edata, CD_BM_ELEM_PYPTR);
- BM_data_layer_add(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
- BM_data_layer_add(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
+ BM_data_layer_add(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
+ BM_data_layer_add(bm, &bm->edata, CD_BM_ELEM_PYPTR);
+ BM_data_layer_add(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
+ BM_data_layer_add(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
#endif
- }
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
-
-
PyObject *BPy_BMVert_CreatePyObject(BMesh *bm, BMVert *v)
{
- BPy_BMVert *self;
+ BPy_BMVert *self;
- void **ptr = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_BM_ELEM_PYPTR);
+ void **ptr = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_BM_ELEM_PYPTR);
- /* bmesh may free layers, ensure we have one to store ourself */
- if (UNLIKELY(ptr == NULL)) {
- BM_data_layer_add(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
- ptr = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_BM_ELEM_PYPTR);
- }
+ /* bmesh may free layers, ensure we have one to store ourself */
+ if (UNLIKELY(ptr == NULL)) {
+ BM_data_layer_add(bm, &bm->vdata, CD_BM_ELEM_PYPTR);
+ ptr = CustomData_bmesh_get(&bm->vdata, v->head.data, CD_BM_ELEM_PYPTR);
+ }
- if (*ptr != NULL) {
- self = *ptr;
- Py_INCREF(self);
- }
- else {
- self = PyObject_New(BPy_BMVert, &BPy_BMVert_Type);
- BLI_assert(v != NULL);
- self->bm = bm;
- self->v = v;
- *ptr = self;
- }
- return (PyObject *)self;
+ if (*ptr != NULL) {
+ self = *ptr;
+ Py_INCREF(self);
+ }
+ else {
+ self = PyObject_New(BPy_BMVert, &BPy_BMVert_Type);
+ BLI_assert(v != NULL);
+ self->bm = bm;
+ self->v = v;
+ *ptr = self;
+ }
+ return (PyObject *)self;
}
PyObject *BPy_BMEdge_CreatePyObject(BMesh *bm, BMEdge *e)
{
- BPy_BMEdge *self;
+ BPy_BMEdge *self;
- void **ptr = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BM_ELEM_PYPTR);
+ void **ptr = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BM_ELEM_PYPTR);
- /* bmesh may free layers, ensure we have one to store ourself */
- if (UNLIKELY(ptr == NULL)) {
- BM_data_layer_add(bm, &bm->edata, CD_BM_ELEM_PYPTR);
- ptr = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BM_ELEM_PYPTR);
- }
+ /* bmesh may free layers, ensure we have one to store ourself */
+ if (UNLIKELY(ptr == NULL)) {
+ BM_data_layer_add(bm, &bm->edata, CD_BM_ELEM_PYPTR);
+ ptr = CustomData_bmesh_get(&bm->edata, e->head.data, CD_BM_ELEM_PYPTR);
+ }
- if (*ptr != NULL) {
- self = *ptr;
- Py_INCREF(self);
- }
- else {
- self = PyObject_New(BPy_BMEdge, &BPy_BMEdge_Type);
- BLI_assert(e != NULL);
- self->bm = bm;
- self->e = e;
- *ptr = self;
- }
- return (PyObject *)self;
+ if (*ptr != NULL) {
+ self = *ptr;
+ Py_INCREF(self);
+ }
+ else {
+ self = PyObject_New(BPy_BMEdge, &BPy_BMEdge_Type);
+ BLI_assert(e != NULL);
+ self->bm = bm;
+ self->e = e;
+ *ptr = self;
+ }
+ return (PyObject *)self;
}
PyObject *BPy_BMFace_CreatePyObject(BMesh *bm, BMFace *f)
{
- BPy_BMFace *self;
+ BPy_BMFace *self;
- void **ptr = CustomData_bmesh_get(&bm->pdata, f->head.data, CD_BM_ELEM_PYPTR);
+ void **ptr = CustomData_bmesh_get(&bm->pdata, f->head.data, CD_BM_ELEM_PYPTR);
- /* bmesh may free layers, ensure we have one to store ourself */
- if (UNLIKELY(ptr == NULL)) {
- BM_data_layer_add(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
- ptr = CustomData_bmesh_get(&bm->pdata, f->head.data, CD_BM_ELEM_PYPTR);
- }
+ /* bmesh may free layers, ensure we have one to store ourself */
+ if (UNLIKELY(ptr == NULL)) {
+ BM_data_layer_add(bm, &bm->pdata, CD_BM_ELEM_PYPTR);
+ ptr = CustomData_bmesh_get(&bm->pdata, f->head.data, CD_BM_ELEM_PYPTR);
+ }
- if (*ptr != NULL) {
- self = *ptr;
- Py_INCREF(self);
- }
- else {
- self = PyObject_New(BPy_BMFace, &BPy_BMFace_Type);
- BLI_assert(f != NULL);
- self->bm = bm;
- self->f = f;
- *ptr = self;
- }
- return (PyObject *)self;
+ if (*ptr != NULL) {
+ self = *ptr;
+ Py_INCREF(self);
+ }
+ else {
+ self = PyObject_New(BPy_BMFace, &BPy_BMFace_Type);
+ BLI_assert(f != NULL);
+ self->bm = bm;
+ self->f = f;
+ *ptr = self;
+ }
+ return (PyObject *)self;
}
PyObject *BPy_BMLoop_CreatePyObject(BMesh *bm, BMLoop *l)
{
- BPy_BMLoop *self;
+ BPy_BMLoop *self;
- void **ptr = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_BM_ELEM_PYPTR);
+ void **ptr = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_BM_ELEM_PYPTR);
- /* bmesh may free layers, ensure we have one to store ourself */
- if (UNLIKELY(ptr == NULL)) {
- BM_data_layer_add(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
- ptr = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_BM_ELEM_PYPTR);
- }
+ /* bmesh may free layers, ensure we have one to store ourself */
+ if (UNLIKELY(ptr == NULL)) {
+ BM_data_layer_add(bm, &bm->ldata, CD_BM_ELEM_PYPTR);
+ ptr = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_BM_ELEM_PYPTR);
+ }
- if (*ptr != NULL) {
- self = *ptr;
- Py_INCREF(self);
- }
- else {
- self = PyObject_New(BPy_BMLoop, &BPy_BMLoop_Type);
- BLI_assert(l != NULL);
- self->bm = bm;
- self->l = l;
- *ptr = self;
- }
- return (PyObject *)self;
+ if (*ptr != NULL) {
+ self = *ptr;
+ Py_INCREF(self);
+ }
+ else {
+ self = PyObject_New(BPy_BMLoop, &BPy_BMLoop_Type);
+ BLI_assert(l != NULL);
+ self->bm = bm;
+ self->l = l;
+ *ptr = self;
+ }
+ return (PyObject *)self;
}
PyObject *BPy_BMElemSeq_CreatePyObject(BMesh *bm, BPy_BMElem *py_ele, const char itype)
{
- BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMElemSeq_Type);
- self->bm = bm;
- self->py_ele = py_ele; /* can be NULL */
- self->itype = itype;
- Py_XINCREF(py_ele);
- return (PyObject *)self;
+ BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMElemSeq_Type);
+ self->bm = bm;
+ self->py_ele = py_ele; /* can be NULL */
+ self->itype = itype;
+ Py_XINCREF(py_ele);
+ return (PyObject *)self;
}
PyObject *BPy_BMVertSeq_CreatePyObject(BMesh *bm)
{
- BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMVertSeq_Type);
- self->bm = bm;
- self->py_ele = NULL; /* unused */
- self->itype = BM_VERTS_OF_MESH;
- return (PyObject *)self;
+ BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMVertSeq_Type);
+ self->bm = bm;
+ self->py_ele = NULL; /* unused */
+ self->itype = BM_VERTS_OF_MESH;
+ return (PyObject *)self;
}
PyObject *BPy_BMEdgeSeq_CreatePyObject(BMesh *bm)
{
- BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMEdgeSeq_Type);
- self->bm = bm;
- self->py_ele = NULL; /* unused */
- self->itype = BM_EDGES_OF_MESH;
- return (PyObject *)self;
+ BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMEdgeSeq_Type);
+ self->bm = bm;
+ self->py_ele = NULL; /* unused */
+ self->itype = BM_EDGES_OF_MESH;
+ return (PyObject *)self;
}
PyObject *BPy_BMFaceSeq_CreatePyObject(BMesh *bm)
{
- BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMFaceSeq_Type);
- self->bm = bm;
- self->py_ele = NULL; /* unused */
- self->itype = BM_FACES_OF_MESH;
- return (PyObject *)self;
+ BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMFaceSeq_Type);
+ self->bm = bm;
+ self->py_ele = NULL; /* unused */
+ self->itype = BM_FACES_OF_MESH;
+ return (PyObject *)self;
}
PyObject *BPy_BMLoopSeq_CreatePyObject(BMesh *bm)
{
- BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMLoopSeq_Type);
- self->bm = bm;
- self->py_ele = NULL; /* unused */
- self->itype = 0; /* should never be passed to the iterator function */
- return (PyObject *)self;
+ BPy_BMElemSeq *self = PyObject_New(BPy_BMElemSeq, &BPy_BMLoopSeq_Type);
+ self->bm = bm;
+ self->py_ele = NULL; /* unused */
+ self->itype = 0; /* should never be passed to the iterator function */
+ return (PyObject *)self;
}
PyObject *BPy_BMIter_CreatePyObject(BMesh *bm)
{
- BPy_BMIter *self = PyObject_New(BPy_BMIter, &BPy_BMIter_Type);
- self->bm = bm;
- /* caller must initialize 'iter' member */
- return (PyObject *)self;
+ BPy_BMIter *self = PyObject_New(BPy_BMIter, &BPy_BMIter_Type);
+ self->bm = bm;
+ /* caller must initialize 'iter' member */
+ return (PyObject *)self;
}
/* this is just a helper func */
PyObject *BPy_BMElem_CreatePyObject(BMesh *bm, BMHeader *ele)
{
- switch (ele->htype) {
- case BM_VERT:
- return BPy_BMVert_CreatePyObject(bm, (BMVert *)ele);
- case BM_EDGE:
- return BPy_BMEdge_CreatePyObject(bm, (BMEdge *)ele);
- case BM_FACE:
- return BPy_BMFace_CreatePyObject(bm, (BMFace *)ele);
- case BM_LOOP:
- return BPy_BMLoop_CreatePyObject(bm, (BMLoop *)ele);
- default:
- BLI_assert(0);
- PyErr_SetString(PyExc_SystemError, "internal error");
- return NULL;
- }
+ switch (ele->htype) {
+ case BM_VERT:
+ return BPy_BMVert_CreatePyObject(bm, (BMVert *)ele);
+ case BM_EDGE:
+ return BPy_BMEdge_CreatePyObject(bm, (BMEdge *)ele);
+ case BM_FACE:
+ return BPy_BMFace_CreatePyObject(bm, (BMFace *)ele);
+ case BM_LOOP:
+ return BPy_BMLoop_CreatePyObject(bm, (BMLoop *)ele);
+ default:
+ BLI_assert(0);
+ PyErr_SetString(PyExc_SystemError, "internal error");
+ return NULL;
+ }
}
int bpy_bm_generic_valid_check(BPy_BMGeneric *self)
{
- if (LIKELY(self->bm)) {
+ if (LIKELY(self->bm)) {
- /* far too slow to enable by default but handy
- * to uncomment for debugging tricky errors,
- * note that this will throw error on entering a
- * function where the actual error will be caused by
- * the previous action. */
+ /* far too slow to enable by default but handy
+ * to uncomment for debugging tricky errors,
+ * note that this will throw error on entering a
+ * function where the actual error will be caused by
+ * the previous action. */
#if 0
- if (BM_mesh_validate(self->bm) == false) {
- PyErr_Format(PyExc_ReferenceError,
- "BMesh used by %.200s has become invalid",
- Py_TYPE(self)->tp_name);
- return -1;
- }
+ if (BM_mesh_validate(self->bm) == false) {
+ PyErr_Format(PyExc_ReferenceError,
+ "BMesh used by %.200s has become invalid",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
#endif
- return 0;
- }
- else {
- PyErr_Format(PyExc_ReferenceError,
- "BMesh data of type %.200s has been removed",
- Py_TYPE(self)->tp_name);
- return -1;
- }
-}
-
-int bpy_bm_generic_valid_check_source(BMesh *bm_source, const char *error_prefix, void **args, unsigned int args_tot)
-{
- int ret = 0;
-
- while (args_tot--) {
- BPy_BMGeneric *py_bm_elem = args[args_tot];
- if (py_bm_elem) {
-
- BLI_assert(BPy_BMesh_Check(py_bm_elem) ||
- BPy_BMElem_Check(py_bm_elem));
-
- ret = bpy_bm_generic_valid_check(py_bm_elem);
- if (UNLIKELY(ret == -1)) {
- break;
- }
- else {
- if (UNLIKELY(py_bm_elem->bm != bm_source)) {
- /* could give more info here */
- PyErr_Format(PyExc_ValueError,
- "%.200s: BMesh data of type %.200s is from another mesh",
- error_prefix, Py_TYPE(py_bm_elem)->tp_name);
- ret = -1;
- break;
- }
- }
- }
- }
-
- return ret;
+ return 0;
+ }
+ else {
+ PyErr_Format(PyExc_ReferenceError,
+ "BMesh data of type %.200s has been removed",
+ Py_TYPE(self)->tp_name);
+ return -1;
+ }
+}
+
+int bpy_bm_generic_valid_check_source(BMesh *bm_source,
+ const char *error_prefix,
+ void **args,
+ unsigned int args_tot)
+{
+ int ret = 0;
+
+ while (args_tot--) {
+ BPy_BMGeneric *py_bm_elem = args[args_tot];
+ if (py_bm_elem) {
+
+ BLI_assert(BPy_BMesh_Check(py_bm_elem) || BPy_BMElem_Check(py_bm_elem));
+
+ ret = bpy_bm_generic_valid_check(py_bm_elem);
+ if (UNLIKELY(ret == -1)) {
+ break;
+ }
+ else {
+ if (UNLIKELY(py_bm_elem->bm != bm_source)) {
+ /* could give more info here */
+ PyErr_Format(PyExc_ValueError,
+ "%.200s: BMesh data of type %.200s is from another mesh",
+ error_prefix,
+ Py_TYPE(py_bm_elem)->tp_name);
+ ret = -1;
+ break;
+ }
+ }
+ }
+ }
+
+ return ret;
}
void bpy_bm_generic_invalidate(BPy_BMGeneric *self)
{
- self->bm = NULL;
+ self->bm = NULL;
}
/* generic python seq as BMVert/Edge/Face array,
@@ -3892,186 +4132,196 @@ void bpy_bm_generic_invalidate(BPy_BMGeneric *self)
*
* The 'bm_r' value is assigned when empty, and used when set.
*/
-void *BPy_BMElem_PySeq_As_Array_FAST(
- BMesh **r_bm, PyObject *seq_fast, Py_ssize_t min, Py_ssize_t max, Py_ssize_t *r_size,
- const char htype,
- const bool do_unique_check, const bool do_bm_check,
- const char *error_prefix)
-{
- BMesh *bm = (r_bm && *r_bm) ? *r_bm : NULL;
- PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
- const Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq_fast);
- Py_ssize_t i, i_last_dirty = PY_SSIZE_T_MAX;
-
- BPy_BMElem *item;
- BMElem **alloc;
-
- *r_size = 0;
-
- if (seq_len < min || seq_len > max) {
- PyErr_Format(PyExc_TypeError,
- "%s: sequence incorrect size, expected [%d - %d], given %d",
- error_prefix, min, max, seq_len);
- return NULL;
- }
-
- /* from now on, use goto */
- alloc = PyMem_MALLOC(seq_len * sizeof(BPy_BMElem **));
-
- for (i = 0; i < seq_len; i++) {
- item = (BPy_BMElem *)seq_fast_items[i];
-
- if (!BPy_BMElem_CheckHType(Py_TYPE(item), htype)) {
- PyErr_Format(PyExc_TypeError,
- "%s: expected %.200s, not '%.200s'",
- error_prefix, BPy_BMElem_StringFromHType(htype), Py_TYPE(item)->tp_name);
- goto err_cleanup;
- }
- else if (!BPY_BM_IS_VALID(item)) {
- PyErr_Format(PyExc_TypeError,
- "%s: %d %s has been removed",
- error_prefix, i, Py_TYPE(item)->tp_name);
- goto err_cleanup;
- }
- /* trick so we can ensure all items have the same mesh,
- * and allows us to pass the 'bm' as NULL. */
- else if (do_bm_check && (bm && bm != item->bm)) {
- PyErr_Format(PyExc_ValueError,
- "%s: %d %s is from another mesh",
- error_prefix, i, BPy_BMElem_StringFromHType(htype));
- goto err_cleanup;
- }
-
- if (bm == NULL) {
- bm = item->bm;
- }
-
- alloc[i] = item->ele;
-
- if (do_unique_check) {
- BM_elem_flag_enable(item->ele, BM_ELEM_INTERNAL_TAG);
- i_last_dirty = i;
- }
- }
-
- if (do_unique_check) {
- /* check for double verts! */
- bool ok = true;
- for (i = 0; i < seq_len; i++) {
- if (UNLIKELY(BM_elem_flag_test(alloc[i], BM_ELEM_INTERNAL_TAG) == false)) {
- ok = false;
- }
-
- /* ensure we don't leave this enabled */
- BM_elem_flag_disable(alloc[i], BM_ELEM_INTERNAL_TAG);
- }
-
- if (ok == false) {
- /* Cleared above. */
- i_last_dirty = PY_SSIZE_T_MAX;
- PyErr_Format(PyExc_ValueError,
- "%s: found the same %.200s used multiple times",
- error_prefix, BPy_BMElem_StringFromHType(htype));
- goto err_cleanup;
- }
- }
-
- *r_size = seq_len;
- if (r_bm) {
- *r_bm = bm;
- }
- return alloc;
+void *BPy_BMElem_PySeq_As_Array_FAST(BMesh **r_bm,
+ PyObject *seq_fast,
+ Py_ssize_t min,
+ Py_ssize_t max,
+ Py_ssize_t *r_size,
+ const char htype,
+ const bool do_unique_check,
+ const bool do_bm_check,
+ const char *error_prefix)
+{
+ BMesh *bm = (r_bm && *r_bm) ? *r_bm : NULL;
+ PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
+ const Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq_fast);
+ Py_ssize_t i, i_last_dirty = PY_SSIZE_T_MAX;
+
+ BPy_BMElem *item;
+ BMElem **alloc;
+
+ *r_size = 0;
+
+ if (seq_len < min || seq_len > max) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: sequence incorrect size, expected [%d - %d], given %d",
+ error_prefix,
+ min,
+ max,
+ seq_len);
+ return NULL;
+ }
+
+ /* from now on, use goto */
+ alloc = PyMem_MALLOC(seq_len * sizeof(BPy_BMElem **));
+
+ for (i = 0; i < seq_len; i++) {
+ item = (BPy_BMElem *)seq_fast_items[i];
+
+ if (!BPy_BMElem_CheckHType(Py_TYPE(item), htype)) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: expected %.200s, not '%.200s'",
+ error_prefix,
+ BPy_BMElem_StringFromHType(htype),
+ Py_TYPE(item)->tp_name);
+ goto err_cleanup;
+ }
+ else if (!BPY_BM_IS_VALID(item)) {
+ PyErr_Format(
+ PyExc_TypeError, "%s: %d %s has been removed", error_prefix, i, Py_TYPE(item)->tp_name);
+ goto err_cleanup;
+ }
+ /* trick so we can ensure all items have the same mesh,
+ * and allows us to pass the 'bm' as NULL. */
+ else if (do_bm_check && (bm && bm != item->bm)) {
+ PyErr_Format(PyExc_ValueError,
+ "%s: %d %s is from another mesh",
+ error_prefix,
+ i,
+ BPy_BMElem_StringFromHType(htype));
+ goto err_cleanup;
+ }
+
+ if (bm == NULL) {
+ bm = item->bm;
+ }
+
+ alloc[i] = item->ele;
+
+ if (do_unique_check) {
+ BM_elem_flag_enable(item->ele, BM_ELEM_INTERNAL_TAG);
+ i_last_dirty = i;
+ }
+ }
+
+ if (do_unique_check) {
+ /* check for double verts! */
+ bool ok = true;
+ for (i = 0; i < seq_len; i++) {
+ if (UNLIKELY(BM_elem_flag_test(alloc[i], BM_ELEM_INTERNAL_TAG) == false)) {
+ ok = false;
+ }
+
+ /* ensure we don't leave this enabled */
+ BM_elem_flag_disable(alloc[i], BM_ELEM_INTERNAL_TAG);
+ }
+
+ if (ok == false) {
+ /* Cleared above. */
+ i_last_dirty = PY_SSIZE_T_MAX;
+ PyErr_Format(PyExc_ValueError,
+ "%s: found the same %.200s used multiple times",
+ error_prefix,
+ BPy_BMElem_StringFromHType(htype));
+ goto err_cleanup;
+ }
+ }
+
+ *r_size = seq_len;
+ if (r_bm) {
+ *r_bm = bm;
+ }
+ return alloc;
err_cleanup:
- if (do_unique_check && (i_last_dirty != PY_SSIZE_T_MAX)) {
- for (i = 0; i <= i_last_dirty; i++) {
- BM_elem_flag_disable(alloc[i], BM_ELEM_INTERNAL_TAG);
- }
- }
- PyMem_FREE(alloc);
- return NULL;
-
+ if (do_unique_check && (i_last_dirty != PY_SSIZE_T_MAX)) {
+ for (i = 0; i <= i_last_dirty; i++) {
+ BM_elem_flag_disable(alloc[i], BM_ELEM_INTERNAL_TAG);
+ }
+ }
+ PyMem_FREE(alloc);
+ return NULL;
}
-void *BPy_BMElem_PySeq_As_Array(
- BMesh **r_bm, PyObject *seq, Py_ssize_t min, Py_ssize_t max, Py_ssize_t *r_size,
- const char htype,
- const bool do_unique_check, const bool do_bm_check,
- const char *error_prefix)
+void *BPy_BMElem_PySeq_As_Array(BMesh **r_bm,
+ PyObject *seq,
+ Py_ssize_t min,
+ Py_ssize_t max,
+ Py_ssize_t *r_size,
+ const char htype,
+ const bool do_unique_check,
+ const bool do_bm_check,
+ const char *error_prefix)
{
- PyObject *seq_fast;
- PyObject *ret;
+ PyObject *seq_fast;
+ PyObject *ret;
- if (!(seq_fast = PySequence_Fast(seq, error_prefix))) {
- return NULL;
- }
+ if (!(seq_fast = PySequence_Fast(seq, error_prefix))) {
+ return NULL;
+ }
- ret = BPy_BMElem_PySeq_As_Array_FAST(
- r_bm, seq_fast, min, max, r_size,
- htype,
- do_unique_check, do_bm_check,
- error_prefix);
+ ret = BPy_BMElem_PySeq_As_Array_FAST(
+ r_bm, seq_fast, min, max, r_size, htype, do_unique_check, do_bm_check, error_prefix);
- Py_DECREF(seq_fast);
- return ret;
+ Py_DECREF(seq_fast);
+ return ret;
}
-
PyObject *BPy_BMElem_Array_As_Tuple(BMesh *bm, BMHeader **elem, Py_ssize_t elem_len)
{
- Py_ssize_t i;
- PyObject *ret = PyTuple_New(elem_len);
- for (i = 0; i < elem_len; i++) {
- PyTuple_SET_ITEM(ret, i, BPy_BMElem_CreatePyObject(bm, elem[i]));
- }
- return ret;
+ Py_ssize_t i;
+ PyObject *ret = PyTuple_New(elem_len);
+ for (i = 0; i < elem_len; i++) {
+ PyTuple_SET_ITEM(ret, i, BPy_BMElem_CreatePyObject(bm, elem[i]));
+ }
+ return ret;
}
PyObject *BPy_BMVert_Array_As_Tuple(BMesh *bm, BMVert **elem, Py_ssize_t elem_len)
{
- Py_ssize_t i;
- PyObject *ret = PyTuple_New(elem_len);
- for (i = 0; i < elem_len; i++) {
- PyTuple_SET_ITEM(ret, i, BPy_BMVert_CreatePyObject(bm, elem[i]));
- }
- return ret;
+ Py_ssize_t i;
+ PyObject *ret = PyTuple_New(elem_len);
+ for (i = 0; i < elem_len; i++) {
+ PyTuple_SET_ITEM(ret, i, BPy_BMVert_CreatePyObject(bm, elem[i]));
+ }
+ return ret;
}
PyObject *BPy_BMEdge_Array_As_Tuple(BMesh *bm, BMEdge **elem, Py_ssize_t elem_len)
{
- Py_ssize_t i;
- PyObject *ret = PyTuple_New(elem_len);
- for (i = 0; i < elem_len; i++) {
- PyTuple_SET_ITEM(ret, i, BPy_BMEdge_CreatePyObject(bm, elem[i]));
- }
+ Py_ssize_t i;
+ PyObject *ret = PyTuple_New(elem_len);
+ for (i = 0; i < elem_len; i++) {
+ PyTuple_SET_ITEM(ret, i, BPy_BMEdge_CreatePyObject(bm, elem[i]));
+ }
- return ret;
+ return ret;
}
PyObject *BPy_BMFace_Array_As_Tuple(BMesh *bm, BMFace **elem, Py_ssize_t elem_len)
{
- Py_ssize_t i;
- PyObject *ret = PyTuple_New(elem_len);
- for (i = 0; i < elem_len; i++) {
- PyTuple_SET_ITEM(ret, i, BPy_BMFace_CreatePyObject(bm, elem[i]));
- }
+ Py_ssize_t i;
+ PyObject *ret = PyTuple_New(elem_len);
+ for (i = 0; i < elem_len; i++) {
+ PyTuple_SET_ITEM(ret, i, BPy_BMFace_CreatePyObject(bm, elem[i]));
+ }
- return ret;
+ return ret;
}
PyObject *BPy_BMLoop_Array_As_Tuple(BMesh *bm, BMLoop **elem, Py_ssize_t elem_len)
{
- Py_ssize_t i;
- PyObject *ret = PyTuple_New(elem_len);
- for (i = 0; i < elem_len; i++) {
- PyTuple_SET_ITEM(ret, i, BPy_BMLoop_CreatePyObject(bm, elem[i]));
- }
+ Py_ssize_t i;
+ PyObject *ret = PyTuple_New(elem_len);
+ for (i = 0; i < elem_len; i++) {
+ PyTuple_SET_ITEM(ret, i, BPy_BMLoop_CreatePyObject(bm, elem[i]));
+ }
- return ret;
+ return ret;
}
int BPy_BMElem_CheckHType(PyTypeObject *type, const char htype)
{
- return (((htype & BM_VERT) && (type == &BPy_BMVert_Type)) ||
- ((htype & BM_EDGE) && (type == &BPy_BMEdge_Type)) ||
- ((htype & BM_FACE) && (type == &BPy_BMFace_Type)) ||
- ((htype & BM_LOOP) && (type == &BPy_BMLoop_Type)));
+ return (((htype & BM_VERT) && (type == &BPy_BMVert_Type)) ||
+ ((htype & BM_EDGE) && (type == &BPy_BMEdge_Type)) ||
+ ((htype & BM_FACE) && (type == &BPy_BMFace_Type)) ||
+ ((htype & BM_LOOP) && (type == &BPy_BMLoop_Type)));
}
/**
@@ -4081,32 +4331,39 @@ int BPy_BMElem_CheckHType(PyTypeObject *type, const char htype)
*/
char *BPy_BMElem_StringFromHType_ex(const char htype, char ret[32])
{
- /* zero to ensure string is always NULL terminated */
- char *ret_ptr = ret;
- if (htype & BM_VERT) { ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMVert_Type.tp_name); }
- if (htype & BM_EDGE) { ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMEdge_Type.tp_name); }
- if (htype & BM_FACE) { ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMFace_Type.tp_name); }
- if (htype & BM_LOOP) { ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMLoop_Type.tp_name); }
- ret[0] = '(';
- *ret_ptr++ = ')';
- *ret_ptr = '\0';
- return ret;
+ /* zero to ensure string is always NULL terminated */
+ char *ret_ptr = ret;
+ if (htype & BM_VERT) {
+ ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMVert_Type.tp_name);
+ }
+ if (htype & BM_EDGE) {
+ ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMEdge_Type.tp_name);
+ }
+ if (htype & BM_FACE) {
+ ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMFace_Type.tp_name);
+ }
+ if (htype & BM_LOOP) {
+ ret_ptr += sprintf(ret_ptr, "/%s", BPy_BMLoop_Type.tp_name);
+ }
+ ret[0] = '(';
+ *ret_ptr++ = ')';
+ *ret_ptr = '\0';
+ return ret;
}
char *BPy_BMElem_StringFromHType(const char htype)
{
- /* zero to ensure string is always NULL terminated */
- static char ret[32];
- return BPy_BMElem_StringFromHType_ex(htype, ret);
+ /* zero to ensure string is always NULL terminated */
+ static char ret[32];
+ return BPy_BMElem_StringFromHType_ex(htype, ret);
}
-
/* -------------------------------------------------------------------- */
/* keep at bottom */
/* this function is called on free, it should stay quite fast */
static void bm_dealloc_editmode_warn(BPy_BMesh *self)
{
- if (self->flag & BPY_BMFLAG_IS_WRAPPED) {
- /* currently nop - this works without warnings now */
- }
+ if (self->flag & BPY_BMFLAG_IS_WRAPPED) {
+ /* currently nop - this works without warnings now */
+ }
}
diff --git a/source/blender/python/bmesh/bmesh_py_types.h b/source/blender/python/bmesh/bmesh_py_types.h
index 80646b7eb16..460e7f82222 100644
--- a/source/blender/python/bmesh/bmesh_py_types.h
+++ b/source/blender/python/bmesh/bmesh_py_types.h
@@ -38,65 +38,57 @@ extern PyTypeObject BPy_BMLoopSeq_Type;
extern PyTypeObject BPy_BMIter_Type;
-#define BPy_BMesh_Check(v) (Py_TYPE(v) == &BPy_BMesh_Type)
-#define BPy_BMVert_Check(v) (Py_TYPE(v) == &BPy_BMVert_Type)
-#define BPy_BMEdge_Check(v) (Py_TYPE(v) == &BPy_BMEdge_Type)
-#define BPy_BMFace_Check(v) (Py_TYPE(v) == &BPy_BMFace_Type)
-#define BPy_BMLoop_Check(v) (Py_TYPE(v) == &BPy_BMLoop_Type)
-#define BPy_BMElemSeq_Check(v) (Py_TYPE(v) == &BPy_BMElemSeq_Type)
-#define BPy_BMVertSeq_Check(v) (Py_TYPE(v) == &BPy_BMVertSeq_Type)
-#define BPy_BMEdgeSeq_Check(v) (Py_TYPE(v) == &BPy_BMEdgeSeq_Type)
-#define BPy_BMFaceSeq_Check(v) (Py_TYPE(v) == &BPy_BMFaceSeq_Type)
-#define BPy_BMLoopSeq_Check(v) (Py_TYPE(v) == &BPy_BMLoopSeq_Type)
-#define BPy_BMIter_Check(v) (Py_TYPE(v) == &BPy_BMIter_Type)
+#define BPy_BMesh_Check(v) (Py_TYPE(v) == &BPy_BMesh_Type)
+#define BPy_BMVert_Check(v) (Py_TYPE(v) == &BPy_BMVert_Type)
+#define BPy_BMEdge_Check(v) (Py_TYPE(v) == &BPy_BMEdge_Type)
+#define BPy_BMFace_Check(v) (Py_TYPE(v) == &BPy_BMFace_Type)
+#define BPy_BMLoop_Check(v) (Py_TYPE(v) == &BPy_BMLoop_Type)
+#define BPy_BMElemSeq_Check(v) (Py_TYPE(v) == &BPy_BMElemSeq_Type)
+#define BPy_BMVertSeq_Check(v) (Py_TYPE(v) == &BPy_BMVertSeq_Type)
+#define BPy_BMEdgeSeq_Check(v) (Py_TYPE(v) == &BPy_BMEdgeSeq_Type)
+#define BPy_BMFaceSeq_Check(v) (Py_TYPE(v) == &BPy_BMFaceSeq_Type)
+#define BPy_BMLoopSeq_Check(v) (Py_TYPE(v) == &BPy_BMLoopSeq_Type)
+#define BPy_BMIter_Check(v) (Py_TYPE(v) == &BPy_BMIter_Type)
/* trick since we know they share a hash function */
-#define BPy_BMElem_Check(v) (Py_TYPE(v)->tp_hash == BPy_BMVert_Type.tp_hash)
+#define BPy_BMElem_Check(v) (Py_TYPE(v)->tp_hash == BPy_BMVert_Type.tp_hash)
/* cast from _any_ bmesh type - they all have BMesh first */
typedef struct BPy_BMGeneric {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
} BPy_BMGeneric;
/* BPy_BMVert/BPy_BMEdge/BPy_BMFace/BPy_BMLoop can cast to this */
typedef struct BPy_BMElem {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMElem *ele;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMElem *ele;
} BPy_BMElem;
typedef struct BPy_BMesh {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- int flag;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ int flag;
} BPy_BMesh;
/* element types */
typedef struct BPy_BMVert {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMVert *v;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMVert *v;
} BPy_BMVert;
typedef struct BPy_BMEdge {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMEdge *e;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMEdge *e;
} BPy_BMEdge;
typedef struct BPy_BMFace {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMFace *f;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMFace *f;
} BPy_BMFace;
typedef struct BPy_BMLoop {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMLoop *l;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMLoop *l;
} BPy_BMLoop;
-
/* iterators */
/* used for ...
@@ -107,26 +99,24 @@ typedef struct BPy_BMLoop {
* - BPy_BMLoopSeq_Type
*/
typedef struct BPy_BMElemSeq {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
- /* if this is a sequence on an existing element,
- * loops of faces for eg.
- * If this variable is set, it will be used */
+ /* if this is a sequence on an existing element,
+ * loops of faces for eg.
+ * If this variable is set, it will be used */
- /* we hold a reference to this.
- * check in case the owner becomes invalid on access */
- /* TODO - make this a GC'd object!, will function OK without this though */
- BPy_BMElem *py_ele;
+ /* we hold a reference to this.
+ * check in case the owner becomes invalid on access */
+ /* TODO - make this a GC'd object!, will function OK without this though */
+ BPy_BMElem *py_ele;
- /* iterator type */
- short itype;
+ /* iterator type */
+ short itype;
} BPy_BMElemSeq;
typedef struct BPy_BMIter {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- BMIter iter;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ BMIter iter;
} BPy_BMIter;
void BPy_BM_init_types(void);
@@ -134,8 +124,8 @@ void BPy_BM_init_types(void);
PyObject *BPyInit_bmesh_types(void);
enum {
- BPY_BMFLAG_NOP = 0, /* do nothing */
- BPY_BMFLAG_IS_WRAPPED = 1, /* the mesh is owned by editmode */
+ BPY_BMFLAG_NOP = 0, /* do nothing */
+ BPY_BMFLAG_IS_WRAPPED = 1, /* the mesh is owned by editmode */
};
PyObject *BPy_BMesh_CreatePyObject(BMesh *bm, int flag);
@@ -150,18 +140,27 @@ PyObject *BPy_BMFaceSeq_CreatePyObject(BMesh *bm);
PyObject *BPy_BMLoopSeq_CreatePyObject(BMesh *bm);
PyObject *BPy_BMIter_CreatePyObject(BMesh *bm);
-PyObject *BPy_BMElem_CreatePyObject(BMesh *bm, BMHeader *ele); /* just checks type and creates v/e/f/l */
-
-void *BPy_BMElem_PySeq_As_Array_FAST(
- BMesh **r_bm, PyObject *seq_fast, Py_ssize_t min, Py_ssize_t max, Py_ssize_t *r_size,
- const char htype,
- const bool do_unique_check, const bool do_bm_check,
- const char *error_prefix);
-void *BPy_BMElem_PySeq_As_Array(
- BMesh **r_bm, PyObject *seq, Py_ssize_t min, Py_ssize_t max, Py_ssize_t *r_size,
- const char htype,
- const bool do_unique_check, const bool do_bm_check,
- const char *error_prefix);
+PyObject *BPy_BMElem_CreatePyObject(BMesh *bm,
+ BMHeader *ele); /* just checks type and creates v/e/f/l */
+
+void *BPy_BMElem_PySeq_As_Array_FAST(BMesh **r_bm,
+ PyObject *seq_fast,
+ Py_ssize_t min,
+ Py_ssize_t max,
+ Py_ssize_t *r_size,
+ const char htype,
+ const bool do_unique_check,
+ const bool do_bm_check,
+ const char *error_prefix);
+void *BPy_BMElem_PySeq_As_Array(BMesh **r_bm,
+ PyObject *seq,
+ Py_ssize_t min,
+ Py_ssize_t max,
+ Py_ssize_t *r_size,
+ const char htype,
+ const bool do_unique_check,
+ const bool do_bm_check,
+ const char *error_prefix);
PyObject *BPy_BMElem_Array_As_Tuple(BMesh *bm, BMHeader **elem, Py_ssize_t elem_len);
PyObject *BPy_BMVert_Array_As_Tuple(BMesh *bm, BMVert **elem, Py_ssize_t elem_len);
@@ -169,47 +168,58 @@ PyObject *BPy_BMEdge_Array_As_Tuple(BMesh *bm, BMEdge **elem, Py_ssize_t elem_le
PyObject *BPy_BMFace_Array_As_Tuple(BMesh *bm, BMFace **elem, Py_ssize_t elem_len);
PyObject *BPy_BMLoop_Array_As_Tuple(BMesh *bm, BMLoop **elem, Py_ssize_t elem_len);
-int BPy_BMElem_CheckHType(PyTypeObject *type, const char htype);
-char *BPy_BMElem_StringFromHType_ex(const char htype, char ret[32]);
-char *BPy_BMElem_StringFromHType(const char htype);
+int BPy_BMElem_CheckHType(PyTypeObject *type, const char htype);
+char *BPy_BMElem_StringFromHType_ex(const char htype, char ret[32]);
+char *BPy_BMElem_StringFromHType(const char htype);
// void bpy_bm_generic_invalidate(BPy_BMGeneric *self);
-int bpy_bm_generic_valid_check(BPy_BMGeneric *self);
-int bpy_bm_generic_valid_check_source(BMesh *bm_source, const char *error_prefix, void **args, unsigned int args_n) ATTR_NONNULL(1, 2);
+int bpy_bm_generic_valid_check(BPy_BMGeneric *self);
+int bpy_bm_generic_valid_check_source(BMesh *bm_source,
+ const char *error_prefix,
+ void **args,
+ unsigned int args_n) ATTR_NONNULL(1, 2);
#define BPY_BM_CHECK_OBJ(obj) \
- if (UNLIKELY(bpy_bm_generic_valid_check((BPy_BMGeneric *)obj) == -1)) { return NULL; } (void)0
+ if (UNLIKELY(bpy_bm_generic_valid_check((BPy_BMGeneric *)obj) == -1)) { \
+ return NULL; \
+ } \
+ (void)0
#define BPY_BM_CHECK_INT(obj) \
- if (UNLIKELY(bpy_bm_generic_valid_check((BPy_BMGeneric *)obj) == -1)) { return -1; } (void)0
+ if (UNLIKELY(bpy_bm_generic_valid_check((BPy_BMGeneric *)obj) == -1)) { \
+ return -1; \
+ } \
+ (void)0
/* macros like BPY_BM_CHECK_OBJ/BPY_BM_CHECK_INT that ensure we're from the right BMesh */
-#define BPY_BM_CHECK_SOURCE_OBJ(bm, errmsg, ...) { \
- void *_args[] = {__VA_ARGS__}; \
- if (UNLIKELY(bpy_bm_generic_valid_check_source(bm, errmsg, _args, ARRAY_SIZE(_args)) == -1)) { \
- return NULL; \
- } \
-} (void)0
-#define BPY_BM_CHECK_SOURCE_INT(bm, errmsg, ...) { \
- void *_args[] = {__VA_ARGS__}; \
- if (UNLIKELY(bpy_bm_generic_valid_check_source(bm, errmsg, _args, ARRAY_SIZE(_args)) == -1)) { \
- return -1; \
- } \
-} (void)0
+#define BPY_BM_CHECK_SOURCE_OBJ(bm, errmsg, ...) \
+ { \
+ void *_args[] = {__VA_ARGS__}; \
+ if (UNLIKELY(bpy_bm_generic_valid_check_source(bm, errmsg, _args, ARRAY_SIZE(_args)) == \
+ -1)) { \
+ return NULL; \
+ } \
+ } \
+ (void)0
+#define BPY_BM_CHECK_SOURCE_INT(bm, errmsg, ...) \
+ { \
+ void *_args[] = {__VA_ARGS__}; \
+ if (UNLIKELY(bpy_bm_generic_valid_check_source(bm, errmsg, _args, ARRAY_SIZE(_args)) == \
+ -1)) { \
+ return -1; \
+ } \
+ } \
+ (void)0
#define BPY_BM_IS_VALID(obj) (LIKELY((obj)->bm != NULL))
-#define BM_ITER_BPY_BM_SEQ(ele, iter, bpy_bmelemseq) \
- for (BM_CHECK_TYPE_ELEM_ASSIGN(ele) = BM_iter_new( \
- iter, \
- (bpy_bmelemseq)->bm, \
- (bpy_bmelemseq)->itype, \
- (bpy_bmelemseq)->py_ele ? \
- ((BPy_BMElem *)(bpy_bmelemseq)->py_ele)->ele : \
- NULL \
- ); \
- ele; \
- BM_CHECK_TYPE_ELEM_ASSIGN(ele) = BM_iter_step(iter))
-
+#define BM_ITER_BPY_BM_SEQ(ele, iter, bpy_bmelemseq) \
+ for (BM_CHECK_TYPE_ELEM_ASSIGN(ele) = BM_iter_new( \
+ iter, \
+ (bpy_bmelemseq)->bm, \
+ (bpy_bmelemseq)->itype, \
+ (bpy_bmelemseq)->py_ele ? ((BPy_BMElem *)(bpy_bmelemseq)->py_ele)->ele : NULL); \
+ ele; \
+ BM_CHECK_TYPE_ELEM_ASSIGN(ele) = BM_iter_step(iter))
#ifdef __PY_CAPI_UTILS_H__
struct PyC_FlagSet;
diff --git a/source/blender/python/bmesh/bmesh_py_types_customdata.c b/source/blender/python/bmesh/bmesh_py_types_customdata.c
index abe146f2581..56c25edb7e4 100644
--- a/source/blender/python/bmesh/bmesh_py_types_customdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_customdata.c
@@ -45,29 +45,32 @@
static CustomData *bpy_bm_customdata_get(BMesh *bm, char htype)
{
- switch (htype) {
- case BM_VERT: return &bm->vdata;
- case BM_EDGE: return &bm->edata;
- case BM_FACE: return &bm->pdata;
- case BM_LOOP: return &bm->ldata;
- }
-
- BLI_assert(0);
- return NULL;
+ switch (htype) {
+ case BM_VERT:
+ return &bm->vdata;
+ case BM_EDGE:
+ return &bm->edata;
+ case BM_FACE:
+ return &bm->pdata;
+ case BM_LOOP:
+ return &bm->ldata;
+ }
+
+ BLI_assert(0);
+ return NULL;
}
static CustomDataLayer *bpy_bmlayeritem_get(BPy_BMLayerItem *self)
{
- CustomData *data = bpy_bm_customdata_get(self->bm, self->htype);
- const int index_absolute = CustomData_get_layer_index_n(data, self->type, self->index);
- if (index_absolute != -1) {
- return &data->layers[index_absolute];
- }
- else {
- PyErr_SetString(PyExc_RuntimeError,
- "layer has become invalid");
- return NULL;
- }
+ CustomData *data = bpy_bm_customdata_get(self->bm, self->htype);
+ const int index_absolute = CustomData_get_layer_index_n(data, self->type, self->index);
+ if (index_absolute != -1) {
+ return &data->layers[index_absolute];
+ }
+ else {
+ PyErr_SetString(PyExc_RuntimeError, "layer has become invalid");
+ return NULL;
+ }
}
/* py-type definitions
@@ -79,180 +82,273 @@ static CustomDataLayer *bpy_bmlayeritem_get(BPy_BMLayerItem *self)
/* used for many different types */
PyDoc_STRVAR(bpy_bmlayeraccess_collection__float_doc,
-"Generic float custom-data layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Generic float custom-data layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__int_doc,
-"Generic int custom-data layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Generic int custom-data layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__string_doc,
-"Generic string custom-data layer (exposed as bytes, 255 max length).\n\ntype: :class:`BMLayerCollection`"
-);
+ "Generic string custom-data layer (exposed as bytes, 255 max length).\n\ntype: "
+ ":class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__deform_doc,
-"Vertex deform weight :class:`BMDeformVert` (TODO).\n\ntype: :class:`BMLayerCollection`" // TYPE DOESN'T EXIST YET
-);
-PyDoc_STRVAR(bpy_bmlayeraccess_collection__shape_doc,
-"Vertex shapekey absolute location (as a 3D Vector).\n\n:type: :class:`BMLayerCollection`"
+ "Vertex deform weight :class:`BMDeformVert` (TODO).\n\ntype: "
+ ":class:`BMLayerCollection`" // TYPE DOESN'T EXIST YET
);
+PyDoc_STRVAR(
+ bpy_bmlayeraccess_collection__shape_doc,
+ "Vertex shapekey absolute location (as a 3D Vector).\n\n:type: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__bevel_weight_doc,
-"Bevel weight float in [0 - 1].\n\n:type: :class:`BMLayerCollection`"
-);
+ "Bevel weight float in [0 - 1].\n\n:type: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__crease_doc,
-"Edge crease for subsurf - float in [0 - 1].\n\n:type: :class:`BMLayerCollection`"
-);
-PyDoc_STRVAR(bpy_bmlayeraccess_collection__uv_doc,
-"Accessor for :class:`BMLoopUV` UV (as a 2D Vector).\n\ntype: :class:`BMLayerCollection`"
-);
+ "Edge crease for subsurf - float in [0 - 1].\n\n:type: :class:`BMLayerCollection`");
+PyDoc_STRVAR(
+ bpy_bmlayeraccess_collection__uv_doc,
+ "Accessor for :class:`BMLoopUV` UV (as a 2D Vector).\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__color_doc,
-"Accessor for vertex color layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Accessor for vertex color layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__skin_doc,
-"Accessor for skin layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Accessor for skin layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__paint_mask_doc,
-"Accessor for paint mask layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Accessor for paint mask layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__face_map_doc,
-"FaceMap custom-data layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "FaceMap custom-data layer.\n\ntype: :class:`BMLayerCollection`");
#ifdef WITH_FREESTYLE
PyDoc_STRVAR(bpy_bmlayeraccess_collection__freestyle_edge_doc,
-"Accessor for Freestyle edge layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Accessor for Freestyle edge layer.\n\ntype: :class:`BMLayerCollection`");
PyDoc_STRVAR(bpy_bmlayeraccess_collection__freestyle_face_doc,
-"Accessor for Freestyle face layer.\n\ntype: :class:`BMLayerCollection`"
-);
+ "Accessor for Freestyle face layer.\n\ntype: :class:`BMLayerCollection`");
#endif
static PyObject *bpy_bmlayeraccess_collection_get(BPy_BMLayerAccess *self, void *flag)
{
- const int type = (int)POINTER_AS_INT(flag);
+ const int type = (int)POINTER_AS_INT(flag);
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return BPy_BMLayerCollection_CreatePyObject(self->bm, self->htype, type);
+ return BPy_BMLayerCollection_CreatePyObject(self->bm, self->htype, type);
}
-
PyDoc_STRVAR(bpy_bmlayercollection_active_doc,
-"The active layer of this type (read-only).\n\n:type: :class:`BMLayerItem`"
-);
+ "The active layer of this type (read-only).\n\n:type: :class:`BMLayerItem`");
static PyObject *bpy_bmlayercollection_active_get(BPy_BMLayerItem *self, void *UNUSED(flag))
{
- CustomData *data;
- int index;
+ CustomData *data;
+ int index;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_active_layer(data, self->type); /* type relative */
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_active_layer(data, self->type); /* type relative */
- if (index != -1) {
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
- }
- else {
- Py_RETURN_NONE;
- }
+ if (index != -1) {
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
-PyDoc_STRVAR(bpy_bmlayercollection_is_singleton_doc,
-"True if there can exists only one layer of this type (read-only).\n\n:type: boolean"
-);
+PyDoc_STRVAR(
+ bpy_bmlayercollection_is_singleton_doc,
+ "True if there can exists only one layer of this type (read-only).\n\n:type: boolean");
static PyObject *bpy_bmlayercollection_is_singleton_get(BPy_BMLayerItem *self, void *UNUSED(flag))
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- return PyBool_FromLong(CustomData_layertype_is_singleton(self->type));
+ return PyBool_FromLong(CustomData_layertype_is_singleton(self->type));
}
PyDoc_STRVAR(bpy_bmlayercollection_name_doc,
-"The layers unique name (read-only).\n\n:type: string"
-);
+ "The layers unique name (read-only).\n\n:type: string");
static PyObject *bpy_bmlayeritem_name_get(BPy_BMLayerItem *self, void *UNUSED(flag))
{
- CustomDataLayer *layer;
+ CustomDataLayer *layer;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- layer = bpy_bmlayeritem_get(self);
- if (layer) {
- return PyUnicode_FromString(layer->name);
- }
- else {
- return NULL;
- }
+ layer = bpy_bmlayeritem_get(self);
+ if (layer) {
+ return PyUnicode_FromString(layer->name);
+ }
+ else {
+ return NULL;
+ }
}
static PyGetSetDef bpy_bmlayeraccess_vert_getseters[] = {
- {(char *)"deform", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__deform_doc, (void *)CD_MDEFORMVERT},
-
- {(char *)"float", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__float_doc, (void *)CD_PROP_FLT},
- {(char *)"int", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__int_doc, (void *)CD_PROP_INT},
- {(char *)"string", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__string_doc, (void *)CD_PROP_STR},
-
- {(char *)"shape", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__shape_doc, (void *)CD_SHAPEKEY},
- {(char *)"bevel_weight", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__bevel_weight_doc, (void *)CD_BWEIGHT},
- {(char *)"skin", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__skin_doc, (void *)CD_MVERT_SKIN},
- {(char *)"paint_mask", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__paint_mask_doc, (void *)CD_PAINT_MASK},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"deform",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__deform_doc,
+ (void *)CD_MDEFORMVERT},
+
+ {(char *)"float",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__float_doc,
+ (void *)CD_PROP_FLT},
+ {(char *)"int",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__int_doc,
+ (void *)CD_PROP_INT},
+ {(char *)"string",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__string_doc,
+ (void *)CD_PROP_STR},
+
+ {(char *)"shape",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__shape_doc,
+ (void *)CD_SHAPEKEY},
+ {(char *)"bevel_weight",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__bevel_weight_doc,
+ (void *)CD_BWEIGHT},
+ {(char *)"skin",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__skin_doc,
+ (void *)CD_MVERT_SKIN},
+ {(char *)"paint_mask",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__paint_mask_doc,
+ (void *)CD_PAINT_MASK},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmlayeraccess_edge_getseters[] = {
- {(char *)"float", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__float_doc, (void *)CD_PROP_FLT},
- {(char *)"int", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__int_doc, (void *)CD_PROP_INT},
- {(char *)"string", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__string_doc, (void *)CD_PROP_STR},
-
- {(char *)"bevel_weight", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__bevel_weight_doc, (void *)CD_BWEIGHT},
- {(char *)"crease", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__crease_doc, (void *)CD_CREASE},
+ {(char *)"float",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__float_doc,
+ (void *)CD_PROP_FLT},
+ {(char *)"int",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__int_doc,
+ (void *)CD_PROP_INT},
+ {(char *)"string",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__string_doc,
+ (void *)CD_PROP_STR},
+
+ {(char *)"bevel_weight",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__bevel_weight_doc,
+ (void *)CD_BWEIGHT},
+ {(char *)"crease",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__crease_doc,
+ (void *)CD_CREASE},
#ifdef WITH_FREESTYLE
- {(char *)"freestyle", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__freestyle_edge_doc, (void *)CD_FREESTYLE_EDGE},
+ {(char *)"freestyle",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__freestyle_edge_doc,
+ (void *)CD_FREESTYLE_EDGE},
#endif
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmlayeraccess_face_getseters[] = {
- {(char *)"float", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__float_doc, (void *)CD_PROP_FLT},
- {(char *)"int", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__int_doc, (void *)CD_PROP_INT},
- {(char *)"string", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__string_doc, (void *)CD_PROP_STR},
- {(char *)"face_map", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__face_map_doc, (void *)CD_FACEMAP},
+ {(char *)"float",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__float_doc,
+ (void *)CD_PROP_FLT},
+ {(char *)"int",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__int_doc,
+ (void *)CD_PROP_INT},
+ {(char *)"string",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__string_doc,
+ (void *)CD_PROP_STR},
+ {(char *)"face_map",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__face_map_doc,
+ (void *)CD_FACEMAP},
#ifdef WITH_FREESTYLE
- {(char *)"freestyle", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__freestyle_face_doc, (void *)CD_FREESTYLE_FACE},
+ {(char *)"freestyle",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__freestyle_face_doc,
+ (void *)CD_FREESTYLE_FACE},
#endif
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmlayeraccess_loop_getseters[] = {
- {(char *)"float", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__float_doc, (void *)CD_PROP_FLT},
- {(char *)"int", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__int_doc, (void *)CD_PROP_INT},
- {(char *)"string", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__string_doc, (void *)CD_PROP_STR},
-
- {(char *)"uv", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__uv_doc, (void *)CD_MLOOPUV},
- {(char *)"color", (getter)bpy_bmlayeraccess_collection_get, (setter)NULL, (char *)bpy_bmlayeraccess_collection__color_doc, (void *)CD_MLOOPCOL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"float",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__float_doc,
+ (void *)CD_PROP_FLT},
+ {(char *)"int",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__int_doc,
+ (void *)CD_PROP_INT},
+ {(char *)"string",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__string_doc,
+ (void *)CD_PROP_STR},
+
+ {(char *)"uv",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__uv_doc,
+ (void *)CD_MLOOPUV},
+ {(char *)"color",
+ (getter)bpy_bmlayeraccess_collection_get,
+ (setter)NULL,
+ (char *)bpy_bmlayeraccess_collection__color_doc,
+ (void *)CD_MLOOPCOL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
static PyGetSetDef bpy_bmlayercollection_getseters[] = {
- /* BMESH_TODO, make writeable */
- {(char *)"active", (getter)bpy_bmlayercollection_active_get, (setter)NULL, (char *)bpy_bmlayercollection_active_doc, NULL},
- {(char *)"is_singleton", (getter)bpy_bmlayercollection_is_singleton_get, (setter)NULL, (char *)bpy_bmlayercollection_is_singleton_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* BMESH_TODO, make writeable */
+ {(char *)"active",
+ (getter)bpy_bmlayercollection_active_get,
+ (setter)NULL,
+ (char *)bpy_bmlayercollection_active_doc,
+ NULL},
+ {(char *)"is_singleton",
+ (getter)bpy_bmlayercollection_is_singleton_get,
+ (setter)NULL,
+ (char *)bpy_bmlayercollection_is_singleton_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef bpy_bmlayeritem_getseters[] = {
- /* BMESH_TODO, make writeable */
- {(char *)"name", (getter)bpy_bmlayeritem_name_get, (setter)NULL, (char *)bpy_bmlayercollection_name_doc, NULL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* BMESH_TODO, make writeable */
+ {(char *)"name",
+ (getter)bpy_bmlayeritem_name_get,
+ (setter)NULL,
+ (char *)bpy_bmlayercollection_name_doc,
+ NULL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
/* Methods
* ======= */
@@ -260,318 +356,310 @@ static PyGetSetDef bpy_bmlayeritem_getseters[] = {
* ----------------- */
PyDoc_STRVAR(bpy_bmlayeritem_copy_from_doc,
-".. method:: copy_from(other)\n"
-"\n"
-" Return a copy of the layer\n"
-"\n"
-" :arg other: Another layer to copy from.\n"
-" :arg other: :class:`BMLayerItem`\n"
-);
+ ".. method:: copy_from(other)\n"
+ "\n"
+ " Return a copy of the layer\n"
+ "\n"
+ " :arg other: Another layer to copy from.\n"
+ " :arg other: :class:`BMLayerItem`\n");
static PyObject *bpy_bmlayeritem_copy_from(BPy_BMLayerItem *self, BPy_BMLayerItem *value)
{
- CustomData *data;
+ CustomData *data;
- if (!BPy_BMLayerItem_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "layer.copy_from(x): expected BMLayerItem, not '%.200s'",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if (!BPy_BMLayerItem_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "layer.copy_from(x): expected BMLayerItem, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(self);
- BPY_BM_CHECK_SOURCE_OBJ(self->bm, "layer.copy_from()", value);
+ BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_SOURCE_OBJ(self->bm, "layer.copy_from()", value);
- if ((self->htype != value->htype) ||
- (self->type != value->type))
- {
- PyErr_SetString(PyExc_ValueError,
- "layer.copy_from(other): layer type mismatch");
- }
+ if ((self->htype != value->htype) || (self->type != value->type)) {
+ PyErr_SetString(PyExc_ValueError, "layer.copy_from(other): layer type mismatch");
+ }
- else if (self->index == value->index) {
- Py_RETURN_NONE;
- }
+ else if (self->index == value->index) {
+ Py_RETURN_NONE;
+ }
- data = bpy_bm_customdata_get(self->bm, self->htype);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
- if ((bpy_bmlayeritem_get(self) == NULL) ||
- (bpy_bmlayeritem_get(value) == NULL))
- {
- return NULL;
- }
+ if ((bpy_bmlayeritem_get(self) == NULL) || (bpy_bmlayeritem_get(value) == NULL)) {
+ return NULL;
+ }
- BM_data_layer_copy(self->bm, data, self->type, value->index, self->index);
+ BM_data_layer_copy(self->bm, data, self->type, value->index, self->index);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/* similar to new(), but no name arg. */
PyDoc_STRVAR(bpy_bmlayercollection_verify_doc,
-".. method:: verify()\n"
-"\n"
-" Create a new layer or return an existing active layer\n"
-"\n"
-" :return: The newly verified layer.\n"
-" :rtype: :class:`BMLayerItem`\n"
-);
+ ".. method:: verify()\n"
+ "\n"
+ " Create a new layer or return an existing active layer\n"
+ "\n"
+ " :return: The newly verified layer.\n"
+ " :rtype: :class:`BMLayerItem`\n");
static PyObject *bpy_bmlayercollection_verify(BPy_BMLayerCollection *self)
{
- int index;
- CustomData *data;
+ int index;
+ CustomData *data;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_active_layer(data, self->type); /* type relative */
+ index = CustomData_get_active_layer(data, self->type); /* type relative */
- if (index == -1) {
- BM_data_layer_add(self->bm, data, self->type);
- index = 0;
- }
+ if (index == -1) {
+ BM_data_layer_add(self->bm, data, self->type);
+ index = 0;
+ }
- BLI_assert(index >= 0);
+ BLI_assert(index >= 0);
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
}
PyDoc_STRVAR(bpy_bmlayercollection_new_doc,
-".. method:: new(name)\n"
-"\n"
-" Create a new layer\n"
-"\n"
-" :arg name: Optional name argument (will be made unique).\n"
-" :type name: string\n"
-" :return: The newly created layer.\n"
-" :rtype: :class:`BMLayerItem`\n"
-);
+ ".. method:: new(name)\n"
+ "\n"
+ " Create a new layer\n"
+ "\n"
+ " :arg name: Optional name argument (will be made unique).\n"
+ " :type name: string\n"
+ " :return: The newly created layer.\n"
+ " :rtype: :class:`BMLayerItem`\n");
static PyObject *bpy_bmlayercollection_new(BPy_BMLayerCollection *self, PyObject *args)
{
- const char *name = NULL;
- int index;
- CustomData *data;
+ const char *name = NULL;
+ int index;
+ CustomData *data;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "|s:new", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "|s:new", &name)) {
+ return NULL;
+ }
- data = bpy_bm_customdata_get(self->bm, self->htype);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
- if (CustomData_layertype_is_singleton(self->type) &&
- CustomData_has_layer(data, self->type))
- {
- PyErr_SetString(PyExc_ValueError,
- "layers.new(): is a singleton, use verify() instead");
- return NULL;
- }
+ if (CustomData_layertype_is_singleton(self->type) && CustomData_has_layer(data, self->type)) {
+ PyErr_SetString(PyExc_ValueError, "layers.new(): is a singleton, use verify() instead");
+ return NULL;
+ }
- if (name) {
- BM_data_layer_add_named(self->bm, data, self->type, name);
- }
- else {
- BM_data_layer_add(self->bm, data, self->type);
- }
+ if (name) {
+ BM_data_layer_add_named(self->bm, data, self->type, name);
+ }
+ else {
+ BM_data_layer_add(self->bm, data, self->type);
+ }
- index = CustomData_number_of_layers(data, self->type) - 1;
- BLI_assert(index >= 0);
+ index = CustomData_number_of_layers(data, self->type) - 1;
+ BLI_assert(index >= 0);
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
}
PyDoc_STRVAR(bpy_bmlayercollection_remove_doc,
-".. method:: remove(layer)\n"
-"\n"
-" Remove a layer\n"
-"\n"
-" :arg layer: The layer to remove.\n"
-" :type layer: :class:`BMLayerItem`\n"
-);
+ ".. method:: remove(layer)\n"
+ "\n"
+ " Remove a layer\n"
+ "\n"
+ " :arg layer: The layer to remove.\n"
+ " :type layer: :class:`BMLayerItem`\n");
static PyObject *bpy_bmlayercollection_remove(BPy_BMLayerCollection *self, BPy_BMLayerItem *value)
{
- CustomData *data;
+ CustomData *data;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!BPy_BMLayerItem_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "layers.remove(x): expected BMLayerItem, not '%.200s'",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if (!BPy_BMLayerItem_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "layers.remove(x): expected BMLayerItem, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(value);
+ BPY_BM_CHECK_OBJ(value);
- if ((self->bm != value->bm) ||
- (self->type != value->type) ||
- (self->htype != value->htype))
- {
- PyErr_SetString(PyExc_ValueError,
- "layers.remove(x): x not in layers");
- }
+ if ((self->bm != value->bm) || (self->type != value->type) || (self->htype != value->htype)) {
+ PyErr_SetString(PyExc_ValueError, "layers.remove(x): x not in layers");
+ }
- data = bpy_bm_customdata_get(self->bm, self->htype);
- BM_data_layer_free_n(self->bm, data, self->type, value->index);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ BM_data_layer_free_n(self->bm, data, self->type, value->index);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(bpy_bmlayercollection_keys_doc,
-".. method:: keys()\n"
-"\n"
-" Return the identifiers of collection members\n"
-" (matching pythons dict.keys() functionality).\n"
-"\n"
-" :return: the identifiers for each member of this collection.\n"
-" :rtype: list of strings\n"
-);
+ ".. method:: keys()\n"
+ "\n"
+ " Return the identifiers of collection members\n"
+ " (matching pythons dict.keys() functionality).\n"
+ "\n"
+ " :return: the identifiers for each member of this collection.\n"
+ " :rtype: list of strings\n");
static PyObject *bpy_bmlayercollection_keys(BPy_BMLayerCollection *self)
{
- PyObject *ret;
- PyObject *item;
- int index;
- CustomData *data;
- int tot, i;
+ PyObject *ret;
+ PyObject *item;
+ int index;
+ CustomData *data;
+ int tot, i;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_layer_index(data, self->type); /* absolute, but no need to make relative */
- tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_layer_index(data,
+ self->type); /* absolute, but no need to make relative */
+ tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
- ret = PyList_New(tot);
+ ret = PyList_New(tot);
- for (i = 0; tot-- > 0; index++) {
- item = PyUnicode_FromString(data->layers[index].name);
- PyList_SET_ITEM(ret, i++, item);
- }
+ for (i = 0; tot-- > 0; index++) {
+ item = PyUnicode_FromString(data->layers[index].name);
+ PyList_SET_ITEM(ret, i++, item);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmlayercollection_items_doc,
-".. method:: items()\n"
-"\n"
-" Return the identifiers of collection members\n"
-" (matching pythons dict.items() functionality).\n"
-"\n"
-" :return: (key, value) pairs for each member of this collection.\n"
-" :rtype: list of tuples\n"
-);
+ ".. method:: items()\n"
+ "\n"
+ " Return the identifiers of collection members\n"
+ " (matching pythons dict.items() functionality).\n"
+ "\n"
+ " :return: (key, value) pairs for each member of this collection.\n"
+ " :rtype: list of tuples\n");
static PyObject *bpy_bmlayercollection_items(BPy_BMLayerCollection *self)
{
- PyObject *ret;
- PyObject *item;
- int index;
- CustomData *data;
- int tot, i;
+ PyObject *ret;
+ PyObject *item;
+ int index;
+ CustomData *data;
+ int tot, i;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_layer_index(data, self->type);
- tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_layer_index(data, self->type);
+ tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
- ret = PyList_New(tot);
+ ret = PyList_New(tot);
- for (i = 0; tot-- > 0; index++) {
- item = PyTuple_New(2);
- PyTuple_SET_ITEMS(item,
- PyUnicode_FromString(data->layers[index].name),
- BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, i));
- PyList_SET_ITEM(ret, i++, item);
- }
+ for (i = 0; tot-- > 0; index++) {
+ item = PyTuple_New(2);
+ PyTuple_SET_ITEMS(item,
+ PyUnicode_FromString(data->layers[index].name),
+ BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, i));
+ PyList_SET_ITEM(ret, i++, item);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmlayercollection_values_doc,
-".. method:: values()\n"
-"\n"
-" Return the values of collection\n"
-" (matching pythons dict.values() functionality).\n"
-"\n"
-" :return: the members of this collection.\n"
-" :rtype: list\n"
-);
+ ".. method:: values()\n"
+ "\n"
+ " Return the values of collection\n"
+ " (matching pythons dict.values() functionality).\n"
+ "\n"
+ " :return: the members of this collection.\n"
+ " :rtype: list\n");
static PyObject *bpy_bmlayercollection_values(BPy_BMLayerCollection *self)
{
- PyObject *ret;
- PyObject *item;
- int index;
- CustomData *data;
- int tot, i;
+ PyObject *ret;
+ PyObject *item;
+ int index;
+ CustomData *data;
+ int tot, i;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_layer_index(data, self->type);
- tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_layer_index(data, self->type);
+ tot = (index != -1) ? CustomData_number_of_layers(data, self->type) : 0;
- ret = PyList_New(tot);
+ ret = PyList_New(tot);
- for (i = 0; tot-- > 0; index++) {
- item = BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, i);
- PyList_SET_ITEM(ret, i++, item);
- }
+ for (i = 0; tot-- > 0; index++) {
+ item = BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, i);
+ PyList_SET_ITEM(ret, i++, item);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmlayercollection_get_doc,
-".. method:: get(key, default=None)\n"
-"\n"
-" Returns the value of the layer matching the key or default\n"
-" when not found (matches pythons dictionary function of the same name).\n"
-"\n"
-" :arg key: The key associated with the layer.\n"
-" :type key: string\n"
-" :arg default: Optional argument for the value to return if\n"
-" *key* is not found.\n"
-" :type default: Undefined\n"
-);
+ ".. method:: get(key, default=None)\n"
+ "\n"
+ " Returns the value of the layer matching the key or default\n"
+ " when not found (matches pythons dictionary function of the same name).\n"
+ "\n"
+ " :arg key: The key associated with the layer.\n"
+ " :type key: string\n"
+ " :arg default: Optional argument for the value to return if\n"
+ " *key* is not found.\n"
+ " :type default: Undefined\n");
static PyObject *bpy_bmlayercollection_get(BPy_BMLayerCollection *self, PyObject *args)
{
- const char *key;
- PyObject *def = Py_None;
+ const char *key;
+ PyObject *def = Py_None;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
- return NULL;
- }
- else {
- CustomData *data;
- int index;
+ if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
+ return NULL;
+ }
+ else {
+ CustomData *data;
+ int index;
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_named_layer(data, self->type, key); /* type relative */
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_named_layer(data, self->type, key); /* type relative */
- if (index != -1) {
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
- }
- }
+ if (index != -1) {
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
+ }
+ }
- return Py_INCREF_RET(def);
+ return Py_INCREF_RET(def);
}
static struct PyMethodDef bpy_bmlayeritem_methods[] = {
- {"copy_from", (PyCFunction)bpy_bmlayeritem_copy_from, METH_O, bpy_bmlayeritem_copy_from_doc},
- {NULL, NULL, 0, NULL},
+ {"copy_from", (PyCFunction)bpy_bmlayeritem_copy_from, METH_O, bpy_bmlayeritem_copy_from_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef bpy_bmelemseq_methods[] = {
- {"verify", (PyCFunction)bpy_bmlayercollection_verify, METH_NOARGS, bpy_bmlayercollection_verify_doc},
- {"new", (PyCFunction)bpy_bmlayercollection_new, METH_VARARGS, bpy_bmlayercollection_new_doc},
- {"remove", (PyCFunction)bpy_bmlayercollection_remove, METH_O, bpy_bmlayercollection_remove_doc},
-
- {"keys", (PyCFunction)bpy_bmlayercollection_keys, METH_NOARGS, bpy_bmlayercollection_keys_doc},
- {"values", (PyCFunction)bpy_bmlayercollection_values, METH_NOARGS, bpy_bmlayercollection_values_doc},
- {"items", (PyCFunction)bpy_bmlayercollection_items, METH_NOARGS, bpy_bmlayercollection_items_doc},
- {"get", (PyCFunction)bpy_bmlayercollection_get, METH_VARARGS, bpy_bmlayercollection_get_doc},
- {NULL, NULL, 0, NULL},
+ {"verify",
+ (PyCFunction)bpy_bmlayercollection_verify,
+ METH_NOARGS,
+ bpy_bmlayercollection_verify_doc},
+ {"new", (PyCFunction)bpy_bmlayercollection_new, METH_VARARGS, bpy_bmlayercollection_new_doc},
+ {"remove",
+ (PyCFunction)bpy_bmlayercollection_remove,
+ METH_O,
+ bpy_bmlayercollection_remove_doc},
+
+ {"keys", (PyCFunction)bpy_bmlayercollection_keys, METH_NOARGS, bpy_bmlayercollection_keys_doc},
+ {"values",
+ (PyCFunction)bpy_bmlayercollection_values,
+ METH_NOARGS,
+ bpy_bmlayercollection_values_doc},
+ {"items",
+ (PyCFunction)bpy_bmlayercollection_items,
+ METH_NOARGS,
+ bpy_bmlayercollection_items_doc},
+ {"get", (PyCFunction)bpy_bmlayercollection_get, METH_VARARGS, bpy_bmlayercollection_get_doc},
+ {NULL, NULL, 0, NULL},
};
/* Sequences
@@ -579,183 +667,185 @@ static struct PyMethodDef bpy_bmelemseq_methods[] = {
static Py_ssize_t bpy_bmlayercollection_length(BPy_BMLayerCollection *self)
{
- CustomData *data;
+ CustomData *data;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- data = bpy_bm_customdata_get(self->bm, self->htype);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
- return CustomData_number_of_layers(data, self->type);
+ return CustomData_number_of_layers(data, self->type);
}
-static PyObject *bpy_bmlayercollection_subscript_str(BPy_BMLayerCollection *self, const char *keyname)
+static PyObject *bpy_bmlayercollection_subscript_str(BPy_BMLayerCollection *self,
+ const char *keyname)
{
- CustomData *data;
- int index;
-
- BPY_BM_CHECK_OBJ(self);
-
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_named_layer(data, self->type, keyname); /* type relative */
-
- if (index != -1) {
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
- }
- else {
- PyErr_Format(PyExc_KeyError,
- "BMLayerCollection[key]: key \"%.200s\" not found", keyname);
- return NULL;
- }
+ CustomData *data;
+ int index;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_named_layer(data, self->type, keyname); /* type relative */
+
+ if (index != -1) {
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, index);
+ }
+ else {
+ PyErr_Format(PyExc_KeyError, "BMLayerCollection[key]: key \"%.200s\" not found", keyname);
+ return NULL;
+ }
}
static PyObject *bpy_bmlayercollection_subscript_int(BPy_BMLayerCollection *self, int keynum)
{
- Py_ssize_t len;
- BPY_BM_CHECK_OBJ(self);
-
- len = bpy_bmlayercollection_length(self);
-
- if (keynum < 0) {
- keynum += len;
- }
- if (keynum >= 0) {
- if (keynum < len) {
- return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, keynum);
- }
- }
-
- PyErr_Format(PyExc_IndexError,
- "BMLayerCollection[index]: index %d out of range", keynum);
- return NULL;
+ Py_ssize_t len;
+ BPY_BM_CHECK_OBJ(self);
+
+ len = bpy_bmlayercollection_length(self);
+
+ if (keynum < 0) {
+ keynum += len;
+ }
+ if (keynum >= 0) {
+ if (keynum < len) {
+ return BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, keynum);
+ }
+ }
+
+ PyErr_Format(PyExc_IndexError, "BMLayerCollection[index]: index %d out of range", keynum);
+ return NULL;
}
-static PyObject *bpy_bmlayercollection_subscript_slice(BPy_BMLayerCollection *self, Py_ssize_t start, Py_ssize_t stop)
+static PyObject *bpy_bmlayercollection_subscript_slice(BPy_BMLayerCollection *self,
+ Py_ssize_t start,
+ Py_ssize_t stop)
{
- Py_ssize_t len = bpy_bmlayercollection_length(self);
- int count = 0;
+ Py_ssize_t len = bpy_bmlayercollection_length(self);
+ int count = 0;
- PyObject *tuple;
+ PyObject *tuple;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if (start >= len) {
- start = len - 1;
- }
- if (stop >= len) {
- stop = len - 1;
- }
+ if (start >= len) {
+ start = len - 1;
+ }
+ if (stop >= len) {
+ stop = len - 1;
+ }
- tuple = PyTuple_New(stop - start);
+ tuple = PyTuple_New(stop - start);
- for (count = start; count < stop; count++) {
- PyTuple_SET_ITEM(tuple, count - start, BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, count));
- }
+ for (count = start; count < stop; count++) {
+ PyTuple_SET_ITEM(tuple,
+ count - start,
+ BPy_BMLayerItem_CreatePyObject(self->bm, self->htype, self->type, count));
+ }
- return tuple;
+ return tuple;
}
static PyObject *bpy_bmlayercollection_subscript(BPy_BMLayerCollection *self, PyObject *key)
{
- /* don't need error check here */
- if (PyUnicode_Check(key)) {
- return bpy_bmlayercollection_subscript_str(self, _PyUnicode_AsString(key));
- }
- else if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- return bpy_bmlayercollection_subscript_int(self, i);
- }
- else if (PySlice_Check(key)) {
- PySliceObject *key_slice = (PySliceObject *)key;
- Py_ssize_t step = 1;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError,
- "BMLayerCollection[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- return bpy_bmlayercollection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
- }
- else {
- Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
-
- /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
- if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
- return NULL;
- }
- if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
- return NULL;
- }
-
- if (start < 0 || stop < 0) {
- /* only get the length for negative values */
- Py_ssize_t len = bpy_bmlayercollection_length(self);
- if (start < 0) {
- start += len;
- }
- if (stop < 0) {
- stop += len;
- }
- }
-
- if (stop - start <= 0) {
- return PyTuple_New(0);
- }
- else {
- return bpy_bmlayercollection_subscript_slice(self, start, stop);
- }
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "BMLayerCollection[key]: invalid key, key must be an int");
- return NULL;
- }
+ /* don't need error check here */
+ if (PyUnicode_Check(key)) {
+ return bpy_bmlayercollection_subscript_str(self, _PyUnicode_AsString(key));
+ }
+ else if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ return bpy_bmlayercollection_subscript_int(self, i);
+ }
+ else if (PySlice_Check(key)) {
+ PySliceObject *key_slice = (PySliceObject *)key;
+ Py_ssize_t step = 1;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "BMLayerCollection[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ return bpy_bmlayercollection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ }
+ else {
+ Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
+
+ /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
+ if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
+ return NULL;
+ }
+ if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
+ return NULL;
+ }
+
+ if (start < 0 || stop < 0) {
+ /* only get the length for negative values */
+ Py_ssize_t len = bpy_bmlayercollection_length(self);
+ if (start < 0) {
+ start += len;
+ }
+ if (stop < 0) {
+ stop += len;
+ }
+ }
+
+ if (stop - start <= 0) {
+ return PyTuple_New(0);
+ }
+ else {
+ return bpy_bmlayercollection_subscript_slice(self, start, stop);
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError,
+ "BMLayerCollection[key]: invalid key, key must be an int");
+ return NULL;
+ }
}
static int bpy_bmlayercollection_contains(BPy_BMLayerCollection *self, PyObject *value)
{
- const char *keyname = _PyUnicode_AsString(value);
- CustomData *data;
- int index;
+ const char *keyname = _PyUnicode_AsString(value);
+ CustomData *data;
+ int index;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- if (keyname == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "BMLayerCollection.__contains__: expected a string");
- return -1;
- }
+ if (keyname == NULL) {
+ PyErr_SetString(PyExc_TypeError, "BMLayerCollection.__contains__: expected a string");
+ return -1;
+ }
- data = bpy_bm_customdata_get(self->bm, self->htype);
- index = CustomData_get_named_layer_index(data, self->type, keyname);
+ data = bpy_bm_customdata_get(self->bm, self->htype);
+ index = CustomData_get_named_layer_index(data, self->type, keyname);
- return (index != -1) ? 1 : 0;
+ return (index != -1) ? 1 : 0;
}
static PySequenceMethods bpy_bmlayercollection_as_sequence = {
- (lenfunc)bpy_bmlayercollection_length, /* sq_length */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- (ssizeargfunc)bpy_bmlayercollection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* sq_slice */
- (ssizeobjargproc)NULL, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)bpy_bmlayercollection_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)bpy_bmlayercollection_length, /* sq_length */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ (ssizeargfunc)bpy_bmlayercollection_subscript_int,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* sq_slice */
+ (ssizeobjargproc)NULL, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)bpy_bmlayercollection_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyMappingMethods bpy_bmlayercollection_as_mapping = {
- (lenfunc)bpy_bmlayercollection_length, /* mp_length */
- (binaryfunc)bpy_bmlayercollection_subscript, /* mp_subscript */
- (objobjargproc)NULL, /* mp_ass_subscript */
+ (lenfunc)bpy_bmlayercollection_length, /* mp_length */
+ (binaryfunc)bpy_bmlayercollection_subscript, /* mp_subscript */
+ (objobjargproc)NULL, /* mp_ass_subscript */
};
/* Iterator
@@ -763,36 +853,33 @@ static PyMappingMethods bpy_bmlayercollection_as_mapping = {
static PyObject *bpy_bmlayercollection_iter(BPy_BMLayerCollection *self)
{
- /* fake it with a list iterator */
- PyObject *ret;
- PyObject *iter = NULL;
+ /* fake it with a list iterator */
+ PyObject *ret;
+ PyObject *iter = NULL;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- ret = bpy_bmlayercollection_subscript_slice(self, 0, PY_SSIZE_T_MIN);
+ ret = bpy_bmlayercollection_subscript_slice(self, 0, PY_SSIZE_T_MIN);
- if (ret) {
- iter = PyObject_GetIter(ret);
- Py_DECREF(ret);
- }
+ if (ret) {
+ iter = PyObject_GetIter(ret);
+ Py_DECREF(ret);
+ }
- return iter;
+ return iter;
}
-PyDoc_STRVAR(bpy_bmlayeraccess_type_doc,
-"Exposes custom-data layer attributes."
-);
+PyDoc_STRVAR(bpy_bmlayeraccess_type_doc, "Exposes custom-data layer attributes.");
PyDoc_STRVAR(bpy_bmlayercollection_type_doc,
-"Gives access to a collection of custom-data layers of the same type and behaves like python dictionaries, "
-"except for the ability to do list like index access."
-);
+ "Gives access to a collection of custom-data layers of the same type and behaves "
+ "like python dictionaries, "
+ "except for the ability to do list like index access.");
PyDoc_STRVAR(bpy_bmlayeritem_type_doc,
-"Exposes a single custom data layer, "
-"their main purpose is for use as item accessors to custom-data when used with vert/edge/face/loop data."
-);
-
+ "Exposes a single custom data layer, "
+ "their main purpose is for use as item accessors to custom-data when used with "
+ "vert/edge/face/loop data.");
PyTypeObject BPy_BMLayerAccessVert_Type; /* bm.verts.layers */
PyTypeObject BPy_BMLayerAccessEdge_Type; /* bm.edges.layers */
@@ -801,125 +888,126 @@ PyTypeObject BPy_BMLayerAccessLoop_Type; /* bm.loops.layers */
PyTypeObject BPy_BMLayerCollection_Type; /* bm.loops.layers.uv */
PyTypeObject BPy_BMLayerItem_Type; /* bm.loops.layers.uv["UVMap"] */
-
PyObject *BPy_BMLayerAccess_CreatePyObject(BMesh *bm, const char htype)
{
- BPy_BMLayerAccess *self;
- PyTypeObject *type;
-
- switch (htype) {
- case BM_VERT: type = &BPy_BMLayerAccessVert_Type; break;
- case BM_EDGE: type = &BPy_BMLayerAccessEdge_Type; break;
- case BM_FACE: type = &BPy_BMLayerAccessFace_Type; break;
- case BM_LOOP: type = &BPy_BMLayerAccessLoop_Type; break;
- default:
- {
- BLI_assert(0);
- type = NULL;
- break;
- }
- }
-
- self = PyObject_New(BPy_BMLayerAccess, type);
- self->bm = bm;
- self->htype = htype;
- return (PyObject *)self;
+ BPy_BMLayerAccess *self;
+ PyTypeObject *type;
+
+ switch (htype) {
+ case BM_VERT:
+ type = &BPy_BMLayerAccessVert_Type;
+ break;
+ case BM_EDGE:
+ type = &BPy_BMLayerAccessEdge_Type;
+ break;
+ case BM_FACE:
+ type = &BPy_BMLayerAccessFace_Type;
+ break;
+ case BM_LOOP:
+ type = &BPy_BMLayerAccessLoop_Type;
+ break;
+ default: {
+ BLI_assert(0);
+ type = NULL;
+ break;
+ }
+ }
+
+ self = PyObject_New(BPy_BMLayerAccess, type);
+ self->bm = bm;
+ self->htype = htype;
+ return (PyObject *)self;
}
PyObject *BPy_BMLayerCollection_CreatePyObject(BMesh *bm, const char htype, int type)
{
- BPy_BMLayerCollection *self = PyObject_New(BPy_BMLayerCollection, &BPy_BMLayerCollection_Type);
- self->bm = bm;
- self->htype = htype;
- self->type = type;
- return (PyObject *)self;
+ BPy_BMLayerCollection *self = PyObject_New(BPy_BMLayerCollection, &BPy_BMLayerCollection_Type);
+ self->bm = bm;
+ self->htype = htype;
+ self->type = type;
+ return (PyObject *)self;
}
PyObject *BPy_BMLayerItem_CreatePyObject(BMesh *bm, const char htype, int type, int index)
{
- BPy_BMLayerItem *self = PyObject_New(BPy_BMLayerItem, &BPy_BMLayerItem_Type);
- self->bm = bm;
- self->htype = htype;
- self->type = type;
- self->index = index;
- return (PyObject *)self;
+ BPy_BMLayerItem *self = PyObject_New(BPy_BMLayerItem, &BPy_BMLayerItem_Type);
+ self->bm = bm;
+ self->htype = htype;
+ self->type = type;
+ self->index = index;
+ return (PyObject *)self;
}
-
void BPy_BM_init_types_customdata(void)
{
- BPy_BMLayerAccessVert_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
- BPy_BMLayerAccessEdge_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
- BPy_BMLayerAccessFace_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
- BPy_BMLayerAccessLoop_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
- BPy_BMLayerCollection_Type.tp_basicsize = sizeof(BPy_BMLayerCollection);
- BPy_BMLayerItem_Type.tp_basicsize = sizeof(BPy_BMLayerItem);
-
- BPy_BMLayerAccessVert_Type.tp_name = "BMLayerAccessVert";
- BPy_BMLayerAccessEdge_Type.tp_name = "BMLayerAccessEdge";
- BPy_BMLayerAccessFace_Type.tp_name = "BMLayerAccessFace";
- BPy_BMLayerAccessLoop_Type.tp_name = "BMLayerAccessLoop";
- BPy_BMLayerCollection_Type.tp_name = "BMLayerCollection";
- BPy_BMLayerItem_Type.tp_name = "BMLayerItem";
-
- /* todo */
- BPy_BMLayerAccessVert_Type.tp_doc = bpy_bmlayeraccess_type_doc;
- BPy_BMLayerAccessEdge_Type.tp_doc = bpy_bmlayeraccess_type_doc;
- BPy_BMLayerAccessFace_Type.tp_doc = bpy_bmlayeraccess_type_doc;
- BPy_BMLayerAccessLoop_Type.tp_doc = bpy_bmlayeraccess_type_doc;
- BPy_BMLayerCollection_Type.tp_doc = bpy_bmlayercollection_type_doc;
- BPy_BMLayerItem_Type.tp_doc = bpy_bmlayeritem_type_doc;
-
- BPy_BMLayerAccessVert_Type.tp_repr = (reprfunc)NULL;
- BPy_BMLayerAccessEdge_Type.tp_repr = (reprfunc)NULL;
- BPy_BMLayerAccessFace_Type.tp_repr = (reprfunc)NULL;
- BPy_BMLayerAccessLoop_Type.tp_repr = (reprfunc)NULL;
- BPy_BMLayerCollection_Type.tp_repr = (reprfunc)NULL;
- BPy_BMLayerItem_Type.tp_repr = (reprfunc)NULL;
-
- BPy_BMLayerAccessVert_Type.tp_getset = bpy_bmlayeraccess_vert_getseters;
- BPy_BMLayerAccessEdge_Type.tp_getset = bpy_bmlayeraccess_edge_getseters;
- BPy_BMLayerAccessFace_Type.tp_getset = bpy_bmlayeraccess_face_getseters;
- BPy_BMLayerAccessLoop_Type.tp_getset = bpy_bmlayeraccess_loop_getseters;
- BPy_BMLayerCollection_Type.tp_getset = bpy_bmlayercollection_getseters;
- BPy_BMLayerItem_Type.tp_getset = bpy_bmlayeritem_getseters;
-
-
-// BPy_BMLayerAccess_Type.tp_methods = bpy_bmeditselseq_methods;
- BPy_BMLayerCollection_Type.tp_methods = bpy_bmelemseq_methods;
- BPy_BMLayerItem_Type.tp_methods = bpy_bmlayeritem_methods;
-
- BPy_BMLayerCollection_Type.tp_as_sequence = &bpy_bmlayercollection_as_sequence;
-
- BPy_BMLayerCollection_Type.tp_as_mapping = &bpy_bmlayercollection_as_mapping;
-
- BPy_BMLayerCollection_Type.tp_iter = (getiterfunc)bpy_bmlayercollection_iter;
-
- BPy_BMLayerAccessVert_Type.tp_dealloc = NULL;
- BPy_BMLayerAccessEdge_Type.tp_dealloc = NULL;
- BPy_BMLayerAccessFace_Type.tp_dealloc = NULL;
- BPy_BMLayerAccessLoop_Type.tp_dealloc = NULL;
- BPy_BMLayerCollection_Type.tp_dealloc = NULL;
- BPy_BMLayerItem_Type.tp_dealloc = NULL;
-
-
-
- BPy_BMLayerAccessVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLayerAccessEdge_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLayerAccessFace_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLayerAccessLoop_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLayerCollection_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMLayerItem_Type.tp_flags = Py_TPFLAGS_DEFAULT;
-
- PyType_Ready(&BPy_BMLayerAccessVert_Type);
- PyType_Ready(&BPy_BMLayerAccessEdge_Type);
- PyType_Ready(&BPy_BMLayerAccessFace_Type);
- PyType_Ready(&BPy_BMLayerAccessLoop_Type);
- PyType_Ready(&BPy_BMLayerCollection_Type);
- PyType_Ready(&BPy_BMLayerItem_Type);
+ BPy_BMLayerAccessVert_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
+ BPy_BMLayerAccessEdge_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
+ BPy_BMLayerAccessFace_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
+ BPy_BMLayerAccessLoop_Type.tp_basicsize = sizeof(BPy_BMLayerAccess);
+ BPy_BMLayerCollection_Type.tp_basicsize = sizeof(BPy_BMLayerCollection);
+ BPy_BMLayerItem_Type.tp_basicsize = sizeof(BPy_BMLayerItem);
+
+ BPy_BMLayerAccessVert_Type.tp_name = "BMLayerAccessVert";
+ BPy_BMLayerAccessEdge_Type.tp_name = "BMLayerAccessEdge";
+ BPy_BMLayerAccessFace_Type.tp_name = "BMLayerAccessFace";
+ BPy_BMLayerAccessLoop_Type.tp_name = "BMLayerAccessLoop";
+ BPy_BMLayerCollection_Type.tp_name = "BMLayerCollection";
+ BPy_BMLayerItem_Type.tp_name = "BMLayerItem";
+
+ /* todo */
+ BPy_BMLayerAccessVert_Type.tp_doc = bpy_bmlayeraccess_type_doc;
+ BPy_BMLayerAccessEdge_Type.tp_doc = bpy_bmlayeraccess_type_doc;
+ BPy_BMLayerAccessFace_Type.tp_doc = bpy_bmlayeraccess_type_doc;
+ BPy_BMLayerAccessLoop_Type.tp_doc = bpy_bmlayeraccess_type_doc;
+ BPy_BMLayerCollection_Type.tp_doc = bpy_bmlayercollection_type_doc;
+ BPy_BMLayerItem_Type.tp_doc = bpy_bmlayeritem_type_doc;
+
+ BPy_BMLayerAccessVert_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMLayerAccessEdge_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMLayerAccessFace_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMLayerAccessLoop_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMLayerCollection_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMLayerItem_Type.tp_repr = (reprfunc)NULL;
+
+ BPy_BMLayerAccessVert_Type.tp_getset = bpy_bmlayeraccess_vert_getseters;
+ BPy_BMLayerAccessEdge_Type.tp_getset = bpy_bmlayeraccess_edge_getseters;
+ BPy_BMLayerAccessFace_Type.tp_getset = bpy_bmlayeraccess_face_getseters;
+ BPy_BMLayerAccessLoop_Type.tp_getset = bpy_bmlayeraccess_loop_getseters;
+ BPy_BMLayerCollection_Type.tp_getset = bpy_bmlayercollection_getseters;
+ BPy_BMLayerItem_Type.tp_getset = bpy_bmlayeritem_getseters;
+
+ // BPy_BMLayerAccess_Type.tp_methods = bpy_bmeditselseq_methods;
+ BPy_BMLayerCollection_Type.tp_methods = bpy_bmelemseq_methods;
+ BPy_BMLayerItem_Type.tp_methods = bpy_bmlayeritem_methods;
+
+ BPy_BMLayerCollection_Type.tp_as_sequence = &bpy_bmlayercollection_as_sequence;
+
+ BPy_BMLayerCollection_Type.tp_as_mapping = &bpy_bmlayercollection_as_mapping;
+
+ BPy_BMLayerCollection_Type.tp_iter = (getiterfunc)bpy_bmlayercollection_iter;
+
+ BPy_BMLayerAccessVert_Type.tp_dealloc = NULL;
+ BPy_BMLayerAccessEdge_Type.tp_dealloc = NULL;
+ BPy_BMLayerAccessFace_Type.tp_dealloc = NULL;
+ BPy_BMLayerAccessLoop_Type.tp_dealloc = NULL;
+ BPy_BMLayerCollection_Type.tp_dealloc = NULL;
+ BPy_BMLayerItem_Type.tp_dealloc = NULL;
+
+ BPy_BMLayerAccessVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLayerAccessEdge_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLayerAccessFace_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLayerAccessLoop_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLayerCollection_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLayerItem_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+
+ PyType_Ready(&BPy_BMLayerAccessVert_Type);
+ PyType_Ready(&BPy_BMLayerAccessEdge_Type);
+ PyType_Ready(&BPy_BMLayerAccessFace_Type);
+ PyType_Ready(&BPy_BMLayerAccessLoop_Type);
+ PyType_Ready(&BPy_BMLayerCollection_Type);
+ PyType_Ready(&BPy_BMLayerItem_Type);
}
-
/* Per Element Get/Set
* ******************* */
@@ -928,46 +1016,42 @@ void BPy_BM_init_types_customdata(void)
*/
static void *bpy_bmlayeritem_ptr_get(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer)
{
- void *value;
- BMElem *ele = py_ele->ele;
- CustomData *data;
-
- /* error checking */
- if (UNLIKELY(!BPy_BMLayerItem_Check(py_layer))) {
- PyErr_SetString(PyExc_AttributeError,
- "BMElem[key]: invalid key, must be a BMLayerItem");
- return NULL;
- }
- else if (UNLIKELY(py_ele->bm != py_layer->bm)) {
- PyErr_SetString(PyExc_ValueError,
- "BMElem[layer]: layer is from another mesh");
- return NULL;
- }
- else if (UNLIKELY(ele->head.htype != py_layer->htype)) {
- char namestr_1[32], namestr_2[32];
- PyErr_Format(PyExc_ValueError,
- "Layer/Element type mismatch, expected %.200s got layer type %.200s",
- BPy_BMElem_StringFromHType_ex(ele->head.htype, namestr_1),
- BPy_BMElem_StringFromHType_ex(py_layer->htype, namestr_2));
- return NULL;
- }
-
- data = bpy_bm_customdata_get(py_layer->bm, py_layer->htype);
-
- value = CustomData_bmesh_get_n(data, ele->head.data, py_layer->type, py_layer->index);
-
- if (UNLIKELY(value == NULL)) {
- /* this should be fairly unlikely but possible if layers move about after we get them */
- PyErr_SetString(PyExc_KeyError,
- "BMElem[key]: layer not found");
- return NULL;
- }
- else {
- return value;
- }
+ void *value;
+ BMElem *ele = py_ele->ele;
+ CustomData *data;
+
+ /* error checking */
+ if (UNLIKELY(!BPy_BMLayerItem_Check(py_layer))) {
+ PyErr_SetString(PyExc_AttributeError, "BMElem[key]: invalid key, must be a BMLayerItem");
+ return NULL;
+ }
+ else if (UNLIKELY(py_ele->bm != py_layer->bm)) {
+ PyErr_SetString(PyExc_ValueError, "BMElem[layer]: layer is from another mesh");
+ return NULL;
+ }
+ else if (UNLIKELY(ele->head.htype != py_layer->htype)) {
+ char namestr_1[32], namestr_2[32];
+ PyErr_Format(PyExc_ValueError,
+ "Layer/Element type mismatch, expected %.200s got layer type %.200s",
+ BPy_BMElem_StringFromHType_ex(ele->head.htype, namestr_1),
+ BPy_BMElem_StringFromHType_ex(py_layer->htype, namestr_2));
+ return NULL;
+ }
+
+ data = bpy_bm_customdata_get(py_layer->bm, py_layer->htype);
+
+ value = CustomData_bmesh_get_n(data, ele->head.data, py_layer->type, py_layer->index);
+
+ if (UNLIKELY(value == NULL)) {
+ /* this should be fairly unlikely but possible if layers move about after we get them */
+ PyErr_SetString(PyExc_KeyError, "BMElem[key]: layer not found");
+ return NULL;
+ }
+ else {
+ return value;
+ }
}
-
/**
*\brief BMElem.__getitem__()
*
@@ -977,194 +1061,176 @@ static void *bpy_bmlayeritem_ptr_get(BPy_BMElem *py_ele, BPy_BMLayerItem *py_lay
*/
PyObject *BPy_BMLayerItem_GetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer)
{
- void *value = bpy_bmlayeritem_ptr_get(py_ele, py_layer);
- PyObject *ret;
-
- if (UNLIKELY(value == NULL)) {
- return NULL;
- }
-
- switch (py_layer->type) {
- case CD_MDEFORMVERT:
- {
- ret = BPy_BMDeformVert_CreatePyObject(value);
- break;
- }
- case CD_PROP_FLT:
- case CD_PAINT_MASK:
- {
- ret = PyFloat_FromDouble(*(float *)value);
- break;
- }
- case CD_PROP_INT:
- case CD_FACEMAP:
- {
- ret = PyLong_FromLong(*(int *)value);
- break;
- }
- case CD_PROP_STR:
- {
- MStringProperty *mstring = value;
- ret = PyBytes_FromStringAndSize(mstring->s, mstring->s_len);
- break;
- }
- case CD_MLOOPUV:
- {
- ret = BPy_BMLoopUV_CreatePyObject(value);
- break;
- }
- case CD_MLOOPCOL:
- {
- ret = BPy_BMLoopColor_CreatePyObject(value);
- break;
- }
- case CD_SHAPEKEY:
- {
- ret = Vector_CreatePyObject_wrap((float *)value, 3, NULL);
- break;
- }
- case CD_BWEIGHT:
- {
- ret = PyFloat_FromDouble(*(float *)value);
- break;
- }
- case CD_CREASE:
- {
- ret = PyFloat_FromDouble(*(float *)value);
- break;
- }
- case CD_MVERT_SKIN:
- {
- ret = BPy_BMVertSkin_CreatePyObject(value);
- break;
- }
- default:
- {
- ret = Py_NotImplemented; /* TODO */
- Py_INCREF(ret);
- break;
- }
- }
-
- return ret;
+ void *value = bpy_bmlayeritem_ptr_get(py_ele, py_layer);
+ PyObject *ret;
+
+ if (UNLIKELY(value == NULL)) {
+ return NULL;
+ }
+
+ switch (py_layer->type) {
+ case CD_MDEFORMVERT: {
+ ret = BPy_BMDeformVert_CreatePyObject(value);
+ break;
+ }
+ case CD_PROP_FLT:
+ case CD_PAINT_MASK: {
+ ret = PyFloat_FromDouble(*(float *)value);
+ break;
+ }
+ case CD_PROP_INT:
+ case CD_FACEMAP: {
+ ret = PyLong_FromLong(*(int *)value);
+ break;
+ }
+ case CD_PROP_STR: {
+ MStringProperty *mstring = value;
+ ret = PyBytes_FromStringAndSize(mstring->s, mstring->s_len);
+ break;
+ }
+ case CD_MLOOPUV: {
+ ret = BPy_BMLoopUV_CreatePyObject(value);
+ break;
+ }
+ case CD_MLOOPCOL: {
+ ret = BPy_BMLoopColor_CreatePyObject(value);
+ break;
+ }
+ case CD_SHAPEKEY: {
+ ret = Vector_CreatePyObject_wrap((float *)value, 3, NULL);
+ break;
+ }
+ case CD_BWEIGHT: {
+ ret = PyFloat_FromDouble(*(float *)value);
+ break;
+ }
+ case CD_CREASE: {
+ ret = PyFloat_FromDouble(*(float *)value);
+ break;
+ }
+ case CD_MVERT_SKIN: {
+ ret = BPy_BMVertSkin_CreatePyObject(value);
+ break;
+ }
+ default: {
+ ret = Py_NotImplemented; /* TODO */
+ Py_INCREF(ret);
+ break;
+ }
+ }
+
+ return ret;
}
int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObject *py_value)
{
- int ret = 0;
- void *value = bpy_bmlayeritem_ptr_get(py_ele, py_layer);
-
- if (UNLIKELY(value == NULL)) {
- return -1;
- }
-
- switch (py_layer->type) {
- case CD_MDEFORMVERT:
- {
- ret = BPy_BMDeformVert_AssignPyObject(value, py_value);
- break;
- }
- case CD_PROP_FLT:
- case CD_PAINT_MASK:
- {
- float tmp_val = PyFloat_AsDouble(py_value);
- if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
- PyErr_Format(PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
- ret = -1;
- }
- else {
- *(float *)value = tmp_val;
- }
- break;
- }
- case CD_PROP_INT:
- case CD_FACEMAP:
- {
- int tmp_val = PyC_Long_AsI32(py_value);
- if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
- /* error is set */
- ret = -1;
- }
- else {
- *(int *)value = tmp_val;
- }
- break;
- }
- case CD_PROP_STR:
- {
- MStringProperty *mstring = value;
- char *tmp_val;
- Py_ssize_t tmp_val_len;
- if (UNLIKELY(PyBytes_AsStringAndSize(py_value, &tmp_val, &tmp_val_len) == -1)) {
- PyErr_Format(PyExc_TypeError, "expected bytes, not a %.200s", Py_TYPE(py_value)->tp_name);
- ret = -1;
- }
- else {
- if (tmp_val_len > sizeof(mstring->s)) {
- tmp_val_len = sizeof(mstring->s);
- }
- memcpy(mstring->s, tmp_val, tmp_val_len);
- mstring->s_len = tmp_val_len;
- }
- break;
- }
- case CD_MLOOPUV:
- {
- ret = BPy_BMLoopUV_AssignPyObject(value, py_value);
- break;
- }
- case CD_MLOOPCOL:
- {
- ret = BPy_BMLoopColor_AssignPyObject(value, py_value);
- break;
- }
- case CD_SHAPEKEY:
- {
- float tmp_val[3];
- if (UNLIKELY(mathutils_array_parse(tmp_val, 3, 3, py_value, "BMVert[shape] = value") == -1)) {
- ret = -1;
- }
- else {
- copy_v3_v3((float *)value, tmp_val);
- }
- break;
- }
- case CD_BWEIGHT:
- {
- float tmp_val = PyFloat_AsDouble(py_value);
- if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
- PyErr_Format(PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
- ret = -1;
- }
- else {
- *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f);
- }
- break;
- }
- case CD_CREASE:
- {
- float tmp_val = PyFloat_AsDouble(py_value);
- if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
- PyErr_Format(PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
- ret = -1;
- }
- else {
- *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f);
- }
- break;
- }
- case CD_MVERT_SKIN:
- {
- ret = BPy_BMVertSkin_AssignPyObject(value, py_value);
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_AttributeError, "readonly / unsupported type");
- ret = -1;
- break;
- }
- }
-
- return ret;
+ int ret = 0;
+ void *value = bpy_bmlayeritem_ptr_get(py_ele, py_layer);
+
+ if (UNLIKELY(value == NULL)) {
+ return -1;
+ }
+
+ switch (py_layer->type) {
+ case CD_MDEFORMVERT: {
+ ret = BPy_BMDeformVert_AssignPyObject(value, py_value);
+ break;
+ }
+ case CD_PROP_FLT:
+ case CD_PAINT_MASK: {
+ float tmp_val = PyFloat_AsDouble(py_value);
+ if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
+ PyErr_Format(
+ PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
+ ret = -1;
+ }
+ else {
+ *(float *)value = tmp_val;
+ }
+ break;
+ }
+ case CD_PROP_INT:
+ case CD_FACEMAP: {
+ int tmp_val = PyC_Long_AsI32(py_value);
+ if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
+ /* error is set */
+ ret = -1;
+ }
+ else {
+ *(int *)value = tmp_val;
+ }
+ break;
+ }
+ case CD_PROP_STR: {
+ MStringProperty *mstring = value;
+ char *tmp_val;
+ Py_ssize_t tmp_val_len;
+ if (UNLIKELY(PyBytes_AsStringAndSize(py_value, &tmp_val, &tmp_val_len) == -1)) {
+ PyErr_Format(PyExc_TypeError, "expected bytes, not a %.200s", Py_TYPE(py_value)->tp_name);
+ ret = -1;
+ }
+ else {
+ if (tmp_val_len > sizeof(mstring->s)) {
+ tmp_val_len = sizeof(mstring->s);
+ }
+ memcpy(mstring->s, tmp_val, tmp_val_len);
+ mstring->s_len = tmp_val_len;
+ }
+ break;
+ }
+ case CD_MLOOPUV: {
+ ret = BPy_BMLoopUV_AssignPyObject(value, py_value);
+ break;
+ }
+ case CD_MLOOPCOL: {
+ ret = BPy_BMLoopColor_AssignPyObject(value, py_value);
+ break;
+ }
+ case CD_SHAPEKEY: {
+ float tmp_val[3];
+ if (UNLIKELY(mathutils_array_parse(tmp_val, 3, 3, py_value, "BMVert[shape] = value") ==
+ -1)) {
+ ret = -1;
+ }
+ else {
+ copy_v3_v3((float *)value, tmp_val);
+ }
+ break;
+ }
+ case CD_BWEIGHT: {
+ float tmp_val = PyFloat_AsDouble(py_value);
+ if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
+ PyErr_Format(
+ PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
+ ret = -1;
+ }
+ else {
+ *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f);
+ }
+ break;
+ }
+ case CD_CREASE: {
+ float tmp_val = PyFloat_AsDouble(py_value);
+ if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
+ PyErr_Format(
+ PyExc_TypeError, "expected a float, not a %.200s", Py_TYPE(py_value)->tp_name);
+ ret = -1;
+ }
+ else {
+ *(float *)value = clamp_f(tmp_val, 0.0f, 1.0f);
+ }
+ break;
+ }
+ case CD_MVERT_SKIN: {
+ ret = BPy_BMVertSkin_AssignPyObject(value, py_value);
+ break;
+ }
+ default: {
+ PyErr_SetString(PyExc_AttributeError, "readonly / unsupported type");
+ ret = -1;
+ break;
+ }
+ }
+
+ return ret;
}
diff --git a/source/blender/python/bmesh/bmesh_py_types_customdata.h b/source/blender/python/bmesh/bmesh_py_types_customdata.h
index 39cac7885cd..95836707e3d 100644
--- a/source/blender/python/bmesh/bmesh_py_types_customdata.h
+++ b/source/blender/python/bmesh/bmesh_py_types_customdata.h
@@ -33,32 +33,29 @@ extern PyTypeObject BPy_BMLayerAccessLoop_Type;
extern PyTypeObject BPy_BMLayerCollection_Type;
extern PyTypeObject BPy_BMLayerItem_Type;
-#define BPy_BMLayerAccess_Check(v) (Py_TYPE(v) == &BPy_BMLayerAccess_Type)
-#define BPy_BMLayerCollection_Check(v) (Py_TYPE(v) == &BPy_BMLayerCollection_Type)
-#define BPy_BMLayerItem_Check(v) (Py_TYPE(v) == &BPy_BMLayerItem_Type)
+#define BPy_BMLayerAccess_Check(v) (Py_TYPE(v) == &BPy_BMLayerAccess_Type)
+#define BPy_BMLayerCollection_Check(v) (Py_TYPE(v) == &BPy_BMLayerCollection_Type)
+#define BPy_BMLayerItem_Check(v) (Py_TYPE(v) == &BPy_BMLayerItem_Type)
/* all layers for vert/edge/face/loop */
typedef struct BPy_BMLayerAccess {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- char htype;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ char htype;
} BPy_BMLayerAccess;
/* access different layer types deform/uv/vertexcolor */
typedef struct BPy_BMLayerCollection {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- char htype;
- int type; /* customdata type - CD_XXX */
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ char htype;
+ int type; /* customdata type - CD_XXX */
} BPy_BMLayerCollection;
/* access a specific layer directly */
typedef struct BPy_BMLayerItem {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- char htype;
- int type; /* customdata type - CD_XXX */
- int index; /* index of this layer type */
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ char htype;
+ int type; /* customdata type - CD_XXX */
+ int index; /* index of this layer type */
} BPy_BMLayerItem;
PyObject *BPy_BMLayerAccess_CreatePyObject(BMesh *bm, const char htype);
@@ -69,7 +66,6 @@ void BPy_BM_init_types_customdata(void);
/* __getitem__ / __setitem__ */
PyObject *BPy_BMLayerItem_GetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer);
-int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObject *value);
-
+int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObject *value);
#endif /* __BMESH_PY_TYPES_CUSTOMDATA_H__ */
diff --git a/source/blender/python/bmesh/bmesh_py_types_meshdata.c b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
index 604b55de6e6..34a4ec3b1ed 100644
--- a/source/blender/python/bmesh/bmesh_py_types_meshdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
@@ -45,111 +45,118 @@
/* Mesh Loop UV
* ************ */
-#define BPy_BMLoopUV_Check(v) (Py_TYPE(v) == &BPy_BMLoopUV_Type)
+#define BPy_BMLoopUV_Check(v) (Py_TYPE(v) == &BPy_BMLoopUV_Type)
typedef struct BPy_BMLoopUV {
- PyObject_VAR_HEAD
- MLoopUV *data;
+ PyObject_VAR_HEAD MLoopUV *data;
} BPy_BMLoopUV;
PyDoc_STRVAR(bpy_bmloopuv_uv_doc,
-"Loops UV (as a 2D Vector).\n\n:type: :class:`mathutils.Vector`"
-);
+ "Loops UV (as a 2D Vector).\n\n:type: :class:`mathutils.Vector`");
static PyObject *bpy_bmloopuv_uv_get(BPy_BMLoopUV *self, void *UNUSED(closure))
{
- return Vector_CreatePyObject_wrap(self->data->uv, 2, NULL);
+ return Vector_CreatePyObject_wrap(self->data->uv, 2, NULL);
}
static int bpy_bmloopuv_uv_set(BPy_BMLoopUV *self, PyObject *value, void *UNUSED(closure))
{
- float tvec[2];
- if (mathutils_array_parse(tvec, 2, 2, value, "BMLoopUV.uv") != -1) {
- copy_v2_v2(self->data->uv, tvec);
- return 0;
- }
- else {
- return -1;
- }
+ float tvec[2];
+ if (mathutils_array_parse(tvec, 2, 2, value, "BMLoopUV.uv") != -1) {
+ copy_v2_v2(self->data->uv, tvec);
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
-PyDoc_STRVAR(bpy_bmloopuv_flag__pin_uv_doc,
-"UV pin state.\n\n:type: boolean"
-);
-PyDoc_STRVAR(bpy_bmloopuv_flag__select_doc,
-"UV select state.\n\n:type: boolean"
-);
-PyDoc_STRVAR(bpy_bmloopuv_flag__select_edge_doc,
-"UV edge select state.\n\n:type: boolean"
-);
-
+PyDoc_STRVAR(bpy_bmloopuv_flag__pin_uv_doc, "UV pin state.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bmloopuv_flag__select_doc, "UV select state.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bmloopuv_flag__select_edge_doc, "UV edge select state.\n\n:type: boolean");
static PyObject *bpy_bmloopuv_flag_get(BPy_BMLoopUV *self, void *flag_p)
{
- const int flag = POINTER_AS_INT(flag_p);
- return PyBool_FromLong(self->data->flag & flag);
+ const int flag = POINTER_AS_INT(flag_p);
+ return PyBool_FromLong(self->data->flag & flag);
}
static int bpy_bmloopuv_flag_set(BPy_BMLoopUV *self, PyObject *value, void *flag_p)
{
- const int flag = POINTER_AS_INT(flag_p);
+ const int flag = POINTER_AS_INT(flag_p);
- switch (PyC_Long_AsBool(value)) {
- case true:
- self->data->flag |= flag;
- return 0;
- case false:
- self->data->flag &= ~flag;
- return 0;
- default:
- /* error is set */
- return -1;
- }
+ switch (PyC_Long_AsBool(value)) {
+ case true:
+ self->data->flag |= flag;
+ return 0;
+ case false:
+ self->data->flag &= ~flag;
+ return 0;
+ default:
+ /* error is set */
+ return -1;
+ }
}
static PyGetSetDef bpy_bmloopuv_getseters[] = {
- /* attributes match rna_def_mloopuv */
- {(char *)"uv", (getter)bpy_bmloopuv_uv_get, (setter)bpy_bmloopuv_uv_set, (char *)bpy_bmloopuv_uv_doc, NULL},
- {(char *)"pin_uv", (getter)bpy_bmloopuv_flag_get, (setter)bpy_bmloopuv_flag_set, (char *)bpy_bmloopuv_flag__pin_uv_doc, (void *)MLOOPUV_PINNED},
- {(char *)"select", (getter)bpy_bmloopuv_flag_get, (setter)bpy_bmloopuv_flag_set, (char *)bpy_bmloopuv_flag__select_doc, (void *)MLOOPUV_VERTSEL},
- {(char *)"select_edge", (getter)bpy_bmloopuv_flag_get, (setter)bpy_bmloopuv_flag_set, (char *)bpy_bmloopuv_flag__select_edge_doc, (void *)MLOOPUV_EDGESEL},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* attributes match rna_def_mloopuv */
+ {(char *)"uv",
+ (getter)bpy_bmloopuv_uv_get,
+ (setter)bpy_bmloopuv_uv_set,
+ (char *)bpy_bmloopuv_uv_doc,
+ NULL},
+ {(char *)"pin_uv",
+ (getter)bpy_bmloopuv_flag_get,
+ (setter)bpy_bmloopuv_flag_set,
+ (char *)bpy_bmloopuv_flag__pin_uv_doc,
+ (void *)MLOOPUV_PINNED},
+ {(char *)"select",
+ (getter)bpy_bmloopuv_flag_get,
+ (setter)bpy_bmloopuv_flag_set,
+ (char *)bpy_bmloopuv_flag__select_doc,
+ (void *)MLOOPUV_VERTSEL},
+ {(char *)"select_edge",
+ (getter)bpy_bmloopuv_flag_get,
+ (setter)bpy_bmloopuv_flag_set,
+ (char *)bpy_bmloopuv_flag__select_edge_doc,
+ (void *)MLOOPUV_EDGESEL},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
PyTypeObject BPy_BMLoopUV_Type; /* bm.loops.layers.uv.active */
static void bm_init_types_bmloopuv(void)
{
- BPy_BMLoopUV_Type.tp_basicsize = sizeof(BPy_BMLoopUV);
+ BPy_BMLoopUV_Type.tp_basicsize = sizeof(BPy_BMLoopUV);
- BPy_BMLoopUV_Type.tp_name = "BMLoopUV";
+ BPy_BMLoopUV_Type.tp_name = "BMLoopUV";
- BPy_BMLoopUV_Type.tp_doc = NULL; // todo
+ BPy_BMLoopUV_Type.tp_doc = NULL; // todo
- BPy_BMLoopUV_Type.tp_getset = bpy_bmloopuv_getseters;
+ BPy_BMLoopUV_Type.tp_getset = bpy_bmloopuv_getseters;
- BPy_BMLoopUV_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMLoopUV_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- PyType_Ready(&BPy_BMLoopUV_Type);
+ PyType_Ready(&BPy_BMLoopUV_Type);
}
int BPy_BMLoopUV_AssignPyObject(struct MLoopUV *mloopuv, PyObject *value)
{
- if (UNLIKELY(!BPy_BMLoopUV_Check(value))) {
- PyErr_Format(PyExc_TypeError, "expected BMLoopUV, not a %.200s", Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- *((MLoopUV *)mloopuv) = *(((BPy_BMLoopUV *)value)->data);
- return 0;
- }
+ if (UNLIKELY(!BPy_BMLoopUV_Check(value))) {
+ PyErr_Format(PyExc_TypeError, "expected BMLoopUV, not a %.200s", Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ *((MLoopUV *)mloopuv) = *(((BPy_BMLoopUV *)value)->data);
+ return 0;
+ }
}
PyObject *BPy_BMLoopUV_CreatePyObject(struct MLoopUV *mloopuv)
{
- BPy_BMLoopUV *self = PyObject_New(BPy_BMLoopUV, &BPy_BMLoopUV_Type);
- self->data = mloopuv;
- return (PyObject *)self;
+ BPy_BMLoopUV *self = PyObject_New(BPy_BMLoopUV, &BPy_BMLoopUV_Type);
+ self->data = mloopuv;
+ return (PyObject *)self;
}
/* --- End Mesh Loop UV --- */
@@ -157,106 +164,114 @@ PyObject *BPy_BMLoopUV_CreatePyObject(struct MLoopUV *mloopuv)
/* Mesh Vert Skin
* ************ */
-#define BPy_BMVertSkin_Check(v) (Py_TYPE(v) == &BPy_BMVertSkin_Type)
+#define BPy_BMVertSkin_Check(v) (Py_TYPE(v) == &BPy_BMVertSkin_Type)
typedef struct BPy_BMVertSkin {
- PyObject_VAR_HEAD
- MVertSkin *data;
+ PyObject_VAR_HEAD MVertSkin *data;
} BPy_BMVertSkin;
PyDoc_STRVAR(bpy_bmvertskin_radius_doc,
-"Vert skin radii (as a 2D Vector).\n\n:type: :class:`mathutils.Vector`"
-);
+ "Vert skin radii (as a 2D Vector).\n\n:type: :class:`mathutils.Vector`");
static PyObject *bpy_bmvertskin_radius_get(BPy_BMVertSkin *self, void *UNUSED(closure))
{
- return Vector_CreatePyObject_wrap(self->data->radius, 2, NULL);
+ return Vector_CreatePyObject_wrap(self->data->radius, 2, NULL);
}
static int bpy_bmvertskin_radius_set(BPy_BMVertSkin *self, PyObject *value, void *UNUSED(closure))
{
- float tvec[2];
- if (mathutils_array_parse(tvec, 2, 2, value, "BMVertSkin.radius") != -1) {
- copy_v2_v2(self->data->radius, tvec);
- return 0;
- }
- else {
- return -1;
- }
+ float tvec[2];
+ if (mathutils_array_parse(tvec, 2, 2, value, "BMVertSkin.radius") != -1) {
+ copy_v2_v2(self->data->radius, tvec);
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
PyDoc_STRVAR(bpy_bmvertskin_flag__use_root_doc,
-"Use as root vertex. Setting this flag does not clear other roots in the same mesh island.\n\n:type: boolean"
-);
-PyDoc_STRVAR(bpy_bmvertskin_flag__use_loose_doc,
-"Use loose vertex.\n\n:type: boolean"
-);
+ "Use as root vertex. Setting this flag does not clear other roots in the same mesh "
+ "island.\n\n:type: boolean");
+PyDoc_STRVAR(bpy_bmvertskin_flag__use_loose_doc, "Use loose vertex.\n\n:type: boolean");
static PyObject *bpy_bmvertskin_flag_get(BPy_BMVertSkin *self, void *flag_p)
{
- const int flag = POINTER_AS_INT(flag_p);
- return PyBool_FromLong(self->data->flag & flag);
+ const int flag = POINTER_AS_INT(flag_p);
+ return PyBool_FromLong(self->data->flag & flag);
}
static int bpy_bmvertskin_flag_set(BPy_BMVertSkin *self, PyObject *value, void *flag_p)
{
- const int flag = POINTER_AS_INT(flag_p);
+ const int flag = POINTER_AS_INT(flag_p);
- switch (PyC_Long_AsBool(value)) {
- case true:
- self->data->flag |= flag;
- return 0;
- case false:
- self->data->flag &= ~flag;
- return 0;
- default:
- /* error is set */
- return -1;
- }
+ switch (PyC_Long_AsBool(value)) {
+ case true:
+ self->data->flag |= flag;
+ return 0;
+ case false:
+ self->data->flag &= ~flag;
+ return 0;
+ default:
+ /* error is set */
+ return -1;
+ }
}
static PyGetSetDef bpy_bmvertskin_getseters[] = {
- /* attributes match rna_mesh_gen */
- {(char *)"radius", (getter)bpy_bmvertskin_radius_get, (setter)bpy_bmvertskin_radius_set, (char *)bpy_bmvertskin_radius_doc, NULL},
- {(char *)"use_root", (getter)bpy_bmvertskin_flag_get, (setter)bpy_bmvertskin_flag_set, (char *)bpy_bmvertskin_flag__use_root_doc, (void *)MVERT_SKIN_ROOT},
- {(char *)"use_loose", (getter)bpy_bmvertskin_flag_get, (setter)bpy_bmvertskin_flag_set, (char *)bpy_bmvertskin_flag__use_loose_doc, (void *)MVERT_SKIN_LOOSE},
-
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ /* attributes match rna_mesh_gen */
+ {(char *)"radius",
+ (getter)bpy_bmvertskin_radius_get,
+ (setter)bpy_bmvertskin_radius_set,
+ (char *)bpy_bmvertskin_radius_doc,
+ NULL},
+ {(char *)"use_root",
+ (getter)bpy_bmvertskin_flag_get,
+ (setter)bpy_bmvertskin_flag_set,
+ (char *)bpy_bmvertskin_flag__use_root_doc,
+ (void *)MVERT_SKIN_ROOT},
+ {(char *)"use_loose",
+ (getter)bpy_bmvertskin_flag_get,
+ (setter)bpy_bmvertskin_flag_set,
+ (char *)bpy_bmvertskin_flag__use_loose_doc,
+ (void *)MVERT_SKIN_LOOSE},
+
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyTypeObject BPy_BMVertSkin_Type; /* bm.loops.layers.skin.active */
static void bm_init_types_bmvertskin(void)
{
- BPy_BMVertSkin_Type.tp_basicsize = sizeof(BPy_BMVertSkin);
+ BPy_BMVertSkin_Type.tp_basicsize = sizeof(BPy_BMVertSkin);
- BPy_BMVertSkin_Type.tp_name = "BMVertSkin";
+ BPy_BMVertSkin_Type.tp_name = "BMVertSkin";
- BPy_BMVertSkin_Type.tp_doc = NULL; // todo
+ BPy_BMVertSkin_Type.tp_doc = NULL; // todo
- BPy_BMVertSkin_Type.tp_getset = bpy_bmvertskin_getseters;
+ BPy_BMVertSkin_Type.tp_getset = bpy_bmvertskin_getseters;
- BPy_BMVertSkin_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMVertSkin_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- PyType_Ready(&BPy_BMVertSkin_Type);
+ PyType_Ready(&BPy_BMVertSkin_Type);
}
int BPy_BMVertSkin_AssignPyObject(struct MVertSkin *mvertskin, PyObject *value)
{
- if (UNLIKELY(!BPy_BMVertSkin_Check(value))) {
- PyErr_Format(PyExc_TypeError, "expected BMVertSkin, not a %.200s", Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- *((MVertSkin *)mvertskin) = *(((BPy_BMVertSkin *)value)->data);
- return 0;
- }
+ if (UNLIKELY(!BPy_BMVertSkin_Check(value))) {
+ PyErr_Format(PyExc_TypeError, "expected BMVertSkin, not a %.200s", Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ *((MVertSkin *)mvertskin) = *(((BPy_BMVertSkin *)value)->data);
+ return 0;
+ }
}
PyObject *BPy_BMVertSkin_CreatePyObject(struct MVertSkin *mvertskin)
{
- BPy_BMVertSkin *self = PyObject_New(BPy_BMVertSkin, &BPy_BMVertSkin_Type);
- self->data = mvertskin;
- return (PyObject *)self;
+ BPy_BMVertSkin *self = PyObject_New(BPy_BMVertSkin, &BPy_BMVertSkin_Type);
+ self->data = mvertskin;
+ return (PyObject *)self;
}
/* --- End Mesh Vert Skin --- */
@@ -268,101 +283,100 @@ PyObject *BPy_BMVertSkin_CreatePyObject(struct MVertSkin *mvertskin)
* color which uses mathutils callbacks for mathutils.Color
*/
-#define MLOOPCOL_FROM_CAPSULE(color_capsule) \
- ((MLoopCol *)PyCapsule_GetPointer(color_capsule, NULL))
+#define MLOOPCOL_FROM_CAPSULE(color_capsule) \
+ ((MLoopCol *)PyCapsule_GetPointer(color_capsule, NULL))
static void mloopcol_to_float(const MLoopCol *mloopcol, float r_col[3])
{
- rgba_uchar_to_float(r_col, (const unsigned char *)&mloopcol->r);
+ rgba_uchar_to_float(r_col, (const unsigned char *)&mloopcol->r);
}
static void mloopcol_from_float(MLoopCol *mloopcol, const float col[3])
{
- rgba_float_to_uchar((unsigned char *)&mloopcol->r, col);
+ rgba_float_to_uchar((unsigned char *)&mloopcol->r, col);
}
static unsigned char mathutils_bmloopcol_cb_index = -1;
static int mathutils_bmloopcol_check(BaseMathObject *UNUSED(bmo))
{
- /* always ok */
- return 0;
+ /* always ok */
+ return 0;
}
static int mathutils_bmloopcol_get(BaseMathObject *bmo, int UNUSED(subtype))
{
- MLoopCol *mloopcol = MLOOPCOL_FROM_CAPSULE(bmo->cb_user);
- mloopcol_to_float(mloopcol, bmo->data);
- return 0;
+ MLoopCol *mloopcol = MLOOPCOL_FROM_CAPSULE(bmo->cb_user);
+ mloopcol_to_float(mloopcol, bmo->data);
+ return 0;
}
static int mathutils_bmloopcol_set(BaseMathObject *bmo, int UNUSED(subtype))
{
- MLoopCol *mloopcol = MLOOPCOL_FROM_CAPSULE(bmo->cb_user);
- mloopcol_from_float(mloopcol, bmo->data);
- return 0;
+ MLoopCol *mloopcol = MLOOPCOL_FROM_CAPSULE(bmo->cb_user);
+ mloopcol_from_float(mloopcol, bmo->data);
+ return 0;
}
static int mathutils_bmloopcol_get_index(BaseMathObject *bmo, int subtype, int UNUSED(index))
{
- /* lazy, avoid repeteing the case statement */
- if (mathutils_bmloopcol_get(bmo, subtype) == -1) {
- return -1;
- }
- return 0;
+ /* lazy, avoid repeteing the case statement */
+ if (mathutils_bmloopcol_get(bmo, subtype) == -1) {
+ return -1;
+ }
+ return 0;
}
static int mathutils_bmloopcol_set_index(BaseMathObject *bmo, int subtype, int index)
{
- const float f = bmo->data[index];
+ const float f = bmo->data[index];
- /* lazy, avoid repeteing the case statement */
- if (mathutils_bmloopcol_get(bmo, subtype) == -1) {
- return -1;
- }
+ /* lazy, avoid repeteing the case statement */
+ if (mathutils_bmloopcol_get(bmo, subtype) == -1) {
+ return -1;
+ }
- bmo->data[index] = f;
- return mathutils_bmloopcol_set(bmo, subtype);
+ bmo->data[index] = f;
+ return mathutils_bmloopcol_set(bmo, subtype);
}
static Mathutils_Callback mathutils_bmloopcol_cb = {
- mathutils_bmloopcol_check,
- mathutils_bmloopcol_get,
- mathutils_bmloopcol_set,
- mathutils_bmloopcol_get_index,
- mathutils_bmloopcol_set_index,
+ mathutils_bmloopcol_check,
+ mathutils_bmloopcol_get,
+ mathutils_bmloopcol_set,
+ mathutils_bmloopcol_get_index,
+ mathutils_bmloopcol_set_index,
};
static void bm_init_types_bmloopcol(void)
{
- /* pass */
- mathutils_bmloopcol_cb_index = Mathutils_RegisterCallback(&mathutils_bmloopcol_cb);
+ /* pass */
+ mathutils_bmloopcol_cb_index = Mathutils_RegisterCallback(&mathutils_bmloopcol_cb);
}
int BPy_BMLoopColor_AssignPyObject(struct MLoopCol *mloopcol, PyObject *value)
{
- float tvec[4];
- if (mathutils_array_parse(tvec, 4, 4, value, "BMLoopCol") != -1) {
- mloopcol_from_float(mloopcol, tvec);
- return 0;
- }
- else {
- return -1;
- }
+ float tvec[4];
+ if (mathutils_array_parse(tvec, 4, 4, value, "BMLoopCol") != -1) {
+ mloopcol_from_float(mloopcol, tvec);
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
PyObject *BPy_BMLoopColor_CreatePyObject(struct MLoopCol *data)
{
- PyObject *color_capsule;
- color_capsule = PyCapsule_New(data, NULL, NULL);
- return Vector_CreatePyObject_cb(color_capsule, 4, mathutils_bmloopcol_cb_index, 0);
+ PyObject *color_capsule;
+ color_capsule = PyCapsule_New(data, NULL, NULL);
+ return Vector_CreatePyObject_cb(color_capsule, 4, mathutils_bmloopcol_cb_index, 0);
}
#undef MLOOPCOL_FROM_CAPSULE
/* --- End Mesh Loop Color --- */
-
/* Mesh Deform Vert
* **************** */
@@ -388,322 +402,310 @@ PyObject *BPy_BMLoopColor_CreatePyObject(struct MLoopCol *data)
* only expose as mapping, not a sequence.
*/
-#define BPy_BMDeformVert_Check(v) (Py_TYPE(v) == &BPy_BMDeformVert_Type)
+#define BPy_BMDeformVert_Check(v) (Py_TYPE(v) == &BPy_BMDeformVert_Type)
typedef struct BPy_BMDeformVert {
- PyObject_VAR_HEAD
- MDeformVert *data;
+ PyObject_VAR_HEAD MDeformVert *data;
} BPy_BMDeformVert;
-
/* Mapping Protocols
* ================= */
static int bpy_bmdeformvert_len(BPy_BMDeformVert *self)
{
- return self->data->totweight;
+ return self->data->totweight;
}
static PyObject *bpy_bmdeformvert_subscript(BPy_BMDeformVert *self, PyObject *key)
{
- if (PyIndex_Check(key)) {
- int i;
- i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- else {
- MDeformWeight *dw = defvert_find_index(self->data, i);
-
- if (dw == NULL) {
- PyErr_SetString(PyExc_KeyError, "BMDeformVert[key] = x: "
- "key not found");
- return NULL;
- }
- else {
- return PyFloat_FromDouble(dw->weight);
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "BMDeformVert keys must be integers, not %.200s",
- Py_TYPE(key)->tp_name);
- return NULL;
- }
+ if (PyIndex_Check(key)) {
+ int i;
+ i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ else {
+ MDeformWeight *dw = defvert_find_index(self->data, i);
+
+ if (dw == NULL) {
+ PyErr_SetString(PyExc_KeyError,
+ "BMDeformVert[key] = x: "
+ "key not found");
+ return NULL;
+ }
+ else {
+ return PyFloat_FromDouble(dw->weight);
+ }
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "BMDeformVert keys must be integers, not %.200s", Py_TYPE(key)->tp_name);
+ return NULL;
+ }
}
static int bpy_bmdeformvert_ass_subscript(BPy_BMDeformVert *self, PyObject *key, PyObject *value)
{
- if (PyIndex_Check(key)) {
- int i;
-
- i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return -1;
- }
-
- if (value) {
- /* dvert[group_index] = 0.5 */
- if (i < 0) {
- PyErr_SetString(PyExc_KeyError, "BMDeformVert[key] = x: "
- "weight keys can't be negative");
- return -1;
- }
- else {
- MDeformWeight *dw = defvert_verify_index(self->data, i);
- const float f = PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) { // parsed key not a number
- PyErr_SetString(PyExc_TypeError,
- "BMDeformVert[key] = x: "
- "assigned value not a number");
- return -1;
- }
-
- dw->weight = clamp_f(f, 0.0f, 1.0f);
- }
- }
- else {
- /* del dvert[group_index] */
- MDeformWeight *dw = defvert_find_index(self->data, i);
-
- if (dw == NULL) {
- PyErr_SetString(PyExc_KeyError, "del BMDeformVert[key]: "
- "key not found");
- }
- defvert_remove_group(self->data, dw);
- }
-
- return 0;
-
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "BMDeformVert keys must be integers, not %.200s",
- Py_TYPE(key)->tp_name);
- return -1;
- }
+ if (PyIndex_Check(key)) {
+ int i;
+
+ i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+
+ if (value) {
+ /* dvert[group_index] = 0.5 */
+ if (i < 0) {
+ PyErr_SetString(PyExc_KeyError,
+ "BMDeformVert[key] = x: "
+ "weight keys can't be negative");
+ return -1;
+ }
+ else {
+ MDeformWeight *dw = defvert_verify_index(self->data, i);
+ const float f = PyFloat_AsDouble(value);
+ if (f == -1 && PyErr_Occurred()) { // parsed key not a number
+ PyErr_SetString(PyExc_TypeError,
+ "BMDeformVert[key] = x: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ dw->weight = clamp_f(f, 0.0f, 1.0f);
+ }
+ }
+ else {
+ /* del dvert[group_index] */
+ MDeformWeight *dw = defvert_find_index(self->data, i);
+
+ if (dw == NULL) {
+ PyErr_SetString(PyExc_KeyError,
+ "del BMDeformVert[key]: "
+ "key not found");
+ }
+ defvert_remove_group(self->data, dw);
+ }
+
+ return 0;
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "BMDeformVert keys must be integers, not %.200s", Py_TYPE(key)->tp_name);
+ return -1;
+ }
}
static int bpy_bmdeformvert_contains(BPy_BMDeformVert *self, PyObject *value)
{
- const int key = PyLong_AsSsize_t(value);
+ const int key = PyLong_AsSsize_t(value);
- if (key == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "BMDeformVert.__contains__: expected an int");
- return -1;
- }
+ if (key == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "BMDeformVert.__contains__: expected an int");
+ return -1;
+ }
- return (defvert_find_index(self->data, key) != NULL) ? 1 : 0;
+ return (defvert_find_index(self->data, key) != NULL) ? 1 : 0;
}
/* only defined for __contains__ */
static PySequenceMethods bpy_bmdeformvert_as_sequence = {
- (lenfunc)bpy_bmdeformvert_len, /* sq_length */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
-
- /* note: if this is set PySequence_Check() returns True,
- * but in this case we dont want to be treated as a seq */
- NULL, /* sq_item */
-
- NULL, /* sq_slice */
- NULL, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)bpy_bmdeformvert_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)bpy_bmdeformvert_len, /* sq_length */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+
+ /* note: if this is set PySequence_Check() returns True,
+ * but in this case we dont want to be treated as a seq */
+ NULL, /* sq_item */
+
+ NULL, /* sq_slice */
+ NULL, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)bpy_bmdeformvert_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyMappingMethods bpy_bmdeformvert_as_mapping = {
- (lenfunc)bpy_bmdeformvert_len,
- (binaryfunc)bpy_bmdeformvert_subscript,
- (objobjargproc)bpy_bmdeformvert_ass_subscript,
+ (lenfunc)bpy_bmdeformvert_len,
+ (binaryfunc)bpy_bmdeformvert_subscript,
+ (objobjargproc)bpy_bmdeformvert_ass_subscript,
};
/* Methods
* ======= */
PyDoc_STRVAR(bpy_bmdeformvert_keys_doc,
-".. method:: keys()\n"
-"\n"
-" Return the group indices used by this vertex\n"
-" (matching pythons dict.keys() functionality).\n"
-"\n"
-" :return: the deform group this vertex uses\n"
-" :rtype: list of ints\n"
-);
+ ".. method:: keys()\n"
+ "\n"
+ " Return the group indices used by this vertex\n"
+ " (matching pythons dict.keys() functionality).\n"
+ "\n"
+ " :return: the deform group this vertex uses\n"
+ " :rtype: list of ints\n");
static PyObject *bpy_bmdeformvert_keys(BPy_BMDeformVert *self)
{
- PyObject *ret;
- int i;
- MDeformWeight *dw = self->data->dw;
+ PyObject *ret;
+ int i;
+ MDeformWeight *dw = self->data->dw;
- ret = PyList_New(self->data->totweight);
- for (i = 0; i < self->data->totweight; i++, dw++) {
- PyList_SET_ITEM(ret, i, PyLong_FromLong(dw->def_nr));
- }
+ ret = PyList_New(self->data->totweight);
+ for (i = 0; i < self->data->totweight; i++, dw++) {
+ PyList_SET_ITEM(ret, i, PyLong_FromLong(dw->def_nr));
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmdeformvert_values_doc,
-".. method:: values()\n"
-"\n"
-" Return the weights of the deform vertex\n"
-" (matching pythons dict.values() functionality).\n"
-"\n"
-" :return: The weights that influence this vertex\n"
-" :rtype: list of floats\n"
-);
+ ".. method:: values()\n"
+ "\n"
+ " Return the weights of the deform vertex\n"
+ " (matching pythons dict.values() functionality).\n"
+ "\n"
+ " :return: The weights that influence this vertex\n"
+ " :rtype: list of floats\n");
static PyObject *bpy_bmdeformvert_values(BPy_BMDeformVert *self)
{
- PyObject *ret;
- int i;
- MDeformWeight *dw = self->data->dw;
+ PyObject *ret;
+ int i;
+ MDeformWeight *dw = self->data->dw;
- ret = PyList_New(self->data->totweight);
- for (i = 0; i < self->data->totweight; i++, dw++) {
- PyList_SET_ITEM(ret, i, PyFloat_FromDouble(dw->weight));
- }
+ ret = PyList_New(self->data->totweight);
+ for (i = 0; i < self->data->totweight; i++, dw++) {
+ PyList_SET_ITEM(ret, i, PyFloat_FromDouble(dw->weight));
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmdeformvert_items_doc,
-".. method:: items()\n"
-"\n"
-" Return (group, weight) pairs for this vertex\n"
-" (matching pythons dict.items() functionality).\n"
-"\n"
-" :return: (key, value) pairs for each deform weight of this vertex.\n"
-" :rtype: list of tuples\n"
-);
+ ".. method:: items()\n"
+ "\n"
+ " Return (group, weight) pairs for this vertex\n"
+ " (matching pythons dict.items() functionality).\n"
+ "\n"
+ " :return: (key, value) pairs for each deform weight of this vertex.\n"
+ " :rtype: list of tuples\n");
static PyObject *bpy_bmdeformvert_items(BPy_BMDeformVert *self)
{
- PyObject *ret;
- PyObject *item;
- int i;
- MDeformWeight *dw = self->data->dw;
+ PyObject *ret;
+ PyObject *item;
+ int i;
+ MDeformWeight *dw = self->data->dw;
- ret = PyList_New(self->data->totweight);
- for (i = 0; i < self->data->totweight; i++, dw++) {
- item = PyTuple_New(2);
- PyTuple_SET_ITEMS(item,
- PyLong_FromLong(dw->def_nr),
- PyFloat_FromDouble(dw->weight));
- PyList_SET_ITEM(ret, i, item);
- }
+ ret = PyList_New(self->data->totweight);
+ for (i = 0; i < self->data->totweight; i++, dw++) {
+ item = PyTuple_New(2);
+ PyTuple_SET_ITEMS(item, PyLong_FromLong(dw->def_nr), PyFloat_FromDouble(dw->weight));
+ PyList_SET_ITEM(ret, i, item);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_bmdeformvert_get_doc,
-".. method:: get(key, default=None)\n"
-"\n"
-" Returns the deform weight matching the key or default\n"
-" when not found (matches pythons dictionary function of the same name).\n"
-"\n"
-" :arg key: The key associated with deform weight.\n"
-" :type key: int\n"
-" :arg default: Optional argument for the value to return if\n"
-" *key* is not found.\n"
-" :type default: Undefined\n"
-);
+ ".. method:: get(key, default=None)\n"
+ "\n"
+ " Returns the deform weight matching the key or default\n"
+ " when not found (matches pythons dictionary function of the same name).\n"
+ "\n"
+ " :arg key: The key associated with deform weight.\n"
+ " :type key: int\n"
+ " :arg default: Optional argument for the value to return if\n"
+ " *key* is not found.\n"
+ " :type default: Undefined\n");
static PyObject *bpy_bmdeformvert_get(BPy_BMDeformVert *self, PyObject *args)
{
- int key;
- PyObject *def = Py_None;
+ int key;
+ PyObject *def = Py_None;
- if (!PyArg_ParseTuple(args, "i|O:get", &key, &def)) {
- return NULL;
- }
- else {
- MDeformWeight *dw = defvert_find_index(self->data, key);
+ if (!PyArg_ParseTuple(args, "i|O:get", &key, &def)) {
+ return NULL;
+ }
+ else {
+ MDeformWeight *dw = defvert_find_index(self->data, key);
- if (dw) {
- return PyFloat_FromDouble(dw->weight);
- }
- else {
- return Py_INCREF_RET(def);
- }
- }
+ if (dw) {
+ return PyFloat_FromDouble(dw->weight);
+ }
+ else {
+ return Py_INCREF_RET(def);
+ }
+ }
}
-
PyDoc_STRVAR(bpy_bmdeformvert_clear_doc,
-".. method:: clear()\n"
-"\n"
-" Clears all weights.\n"
-);
+ ".. method:: clear()\n"
+ "\n"
+ " Clears all weights.\n");
static PyObject *bpy_bmdeformvert_clear(BPy_BMDeformVert *self)
{
- defvert_clear(self->data);
+ defvert_clear(self->data);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef bpy_bmdeformvert_methods[] = {
- {"keys", (PyCFunction)bpy_bmdeformvert_keys, METH_NOARGS, bpy_bmdeformvert_keys_doc},
- {"values", (PyCFunction)bpy_bmdeformvert_values, METH_NOARGS, bpy_bmdeformvert_values_doc},
- {"items", (PyCFunction)bpy_bmdeformvert_items, METH_NOARGS, bpy_bmdeformvert_items_doc},
- {"get", (PyCFunction)bpy_bmdeformvert_get, METH_VARARGS, bpy_bmdeformvert_get_doc},
- /* BMESH_TODO pop, popitem, update */
- {"clear", (PyCFunction)bpy_bmdeformvert_clear, METH_NOARGS, bpy_bmdeformvert_clear_doc},
- {NULL, NULL, 0, NULL},
+ {"keys", (PyCFunction)bpy_bmdeformvert_keys, METH_NOARGS, bpy_bmdeformvert_keys_doc},
+ {"values", (PyCFunction)bpy_bmdeformvert_values, METH_NOARGS, bpy_bmdeformvert_values_doc},
+ {"items", (PyCFunction)bpy_bmdeformvert_items, METH_NOARGS, bpy_bmdeformvert_items_doc},
+ {"get", (PyCFunction)bpy_bmdeformvert_get, METH_VARARGS, bpy_bmdeformvert_get_doc},
+ /* BMESH_TODO pop, popitem, update */
+ {"clear", (PyCFunction)bpy_bmdeformvert_clear, METH_NOARGS, bpy_bmdeformvert_clear_doc},
+ {NULL, NULL, 0, NULL},
};
PyTypeObject BPy_BMDeformVert_Type; /* bm.loops.layers.uv.active */
static void bm_init_types_bmdvert(void)
{
- BPy_BMDeformVert_Type.tp_basicsize = sizeof(BPy_BMDeformVert);
+ BPy_BMDeformVert_Type.tp_basicsize = sizeof(BPy_BMDeformVert);
- BPy_BMDeformVert_Type.tp_name = "BMDeformVert";
+ BPy_BMDeformVert_Type.tp_name = "BMDeformVert";
- BPy_BMDeformVert_Type.tp_doc = NULL; // todo
+ BPy_BMDeformVert_Type.tp_doc = NULL; // todo
- BPy_BMDeformVert_Type.tp_as_sequence = &bpy_bmdeformvert_as_sequence;
- BPy_BMDeformVert_Type.tp_as_mapping = &bpy_bmdeformvert_as_mapping;
+ BPy_BMDeformVert_Type.tp_as_sequence = &bpy_bmdeformvert_as_sequence;
+ BPy_BMDeformVert_Type.tp_as_mapping = &bpy_bmdeformvert_as_mapping;
- BPy_BMDeformVert_Type.tp_methods = bpy_bmdeformvert_methods;
+ BPy_BMDeformVert_Type.tp_methods = bpy_bmdeformvert_methods;
- BPy_BMDeformVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMDeformVert_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- PyType_Ready(&BPy_BMDeformVert_Type);
+ PyType_Ready(&BPy_BMDeformVert_Type);
}
int BPy_BMDeformVert_AssignPyObject(struct MDeformVert *dvert, PyObject *value)
{
- if (UNLIKELY(!BPy_BMDeformVert_Check(value))) {
- PyErr_Format(PyExc_TypeError, "expected BMDeformVert, not a %.200s", Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- MDeformVert *dvert_src = ((BPy_BMDeformVert *)value)->data;
- if (LIKELY(dvert != dvert_src)) {
- defvert_copy(dvert, dvert_src);
- }
- return 0;
- }
+ if (UNLIKELY(!BPy_BMDeformVert_Check(value))) {
+ PyErr_Format(PyExc_TypeError, "expected BMDeformVert, not a %.200s", Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ MDeformVert *dvert_src = ((BPy_BMDeformVert *)value)->data;
+ if (LIKELY(dvert != dvert_src)) {
+ defvert_copy(dvert, dvert_src);
+ }
+ return 0;
+ }
}
PyObject *BPy_BMDeformVert_CreatePyObject(struct MDeformVert *dvert)
{
- BPy_BMDeformVert *self = PyObject_New(BPy_BMDeformVert, &BPy_BMDeformVert_Type);
- self->data = dvert;
- return (PyObject *)self;
+ BPy_BMDeformVert *self = PyObject_New(BPy_BMDeformVert, &BPy_BMDeformVert_Type);
+ self->data = dvert;
+ return (PyObject *)self;
}
/* --- End Mesh Deform Vert --- */
-
/* call to init all types */
void BPy_BM_init_types_meshdata(void)
{
- bm_init_types_bmloopuv();
- bm_init_types_bmloopcol();
- bm_init_types_bmdvert();
- bm_init_types_bmvertskin();
+ bm_init_types_bmloopuv();
+ bm_init_types_bmloopcol();
+ bm_init_types_bmdvert();
+ bm_init_types_bmvertskin();
}
diff --git a/source/blender/python/bmesh/bmesh_py_types_meshdata.h b/source/blender/python/bmesh/bmesh_py_types_meshdata.h
index 66cdb9c119d..5211c30ec7e 100644
--- a/source/blender/python/bmesh/bmesh_py_types_meshdata.h
+++ b/source/blender/python/bmesh/bmesh_py_types_meshdata.h
@@ -27,11 +27,10 @@
extern PyTypeObject BPy_BMLoopUV_Type;
extern PyTypeObject BPy_BMDeformVert_Type;
-#define BPy_BMLoopUV_Check(v) (Py_TYPE(v) == &BPy_BMLoopUV_Type)
+#define BPy_BMLoopUV_Check(v) (Py_TYPE(v) == &BPy_BMLoopUV_Type)
typedef struct BPy_BMGenericMeshData {
- PyObject_VAR_HEAD
- void *data;
+ PyObject_VAR_HEAD void *data;
} BPy_BMGenericMeshData;
struct MDeformVert;
@@ -39,19 +38,18 @@ struct MLoopCol;
struct MLoopUV;
struct MVertSkin;
-int BPy_BMLoopUV_AssignPyObject(struct MLoopUV *data, PyObject *value);
+int BPy_BMLoopUV_AssignPyObject(struct MLoopUV *data, PyObject *value);
PyObject *BPy_BMLoopUV_CreatePyObject(struct MLoopUV *data);
-int BPy_BMVertSkin_AssignPyObject(struct MVertSkin *data, PyObject *value);
+int BPy_BMVertSkin_AssignPyObject(struct MVertSkin *data, PyObject *value);
PyObject *BPy_BMVertSkin_CreatePyObject(struct MVertSkin *data);
-int BPy_BMLoopColor_AssignPyObject(struct MLoopCol *data, PyObject *value);
+int BPy_BMLoopColor_AssignPyObject(struct MLoopCol *data, PyObject *value);
PyObject *BPy_BMLoopColor_CreatePyObject(struct MLoopCol *data);
-int BPy_BMDeformVert_AssignPyObject(struct MDeformVert *dvert, PyObject *value);
+int BPy_BMDeformVert_AssignPyObject(struct MDeformVert *dvert, PyObject *value);
PyObject *BPy_BMDeformVert_CreatePyObject(struct MDeformVert *dvert);
-
void BPy_BM_init_types_meshdata(void);
#endif /* __BMESH_PY_TYPES_MESHDATA_H__ */
diff --git a/source/blender/python/bmesh/bmesh_py_types_select.c b/source/blender/python/bmesh/bmesh_py_types_select.c
index e257c1bff4b..228874a86e3 100644
--- a/source/blender/python/bmesh/bmesh_py_types_select.c
+++ b/source/blender/python/bmesh/bmesh_py_types_select.c
@@ -41,397 +41,387 @@
#include "../generic/python_utildefines.h"
PyDoc_STRVAR(bpy_bmeditselseq_active_doc,
-"The last selected element or None (read-only).\n\n:type: :class:`BMVert`, :class:`BMEdge` or :class:`BMFace`"
-);
+ "The last selected element or None (read-only).\n\n:type: :class:`BMVert`, "
+ ":class:`BMEdge` or :class:`BMFace`");
static PyObject *bpy_bmeditselseq_active_get(BPy_BMEditSelSeq *self, void *UNUSED(closure))
{
- BMEditSelection *ese;
- BPY_BM_CHECK_OBJ(self);
-
- if ((ese = self->bm->selected.last)) {
- return BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
- }
- else {
- Py_RETURN_NONE;
- }
+ BMEditSelection *ese;
+ BPY_BM_CHECK_OBJ(self);
+
+ if ((ese = self->bm->selected.last)) {
+ return BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
static PyGetSetDef bpy_bmeditselseq_getseters[] = {
- {(char *)"active", (getter)bpy_bmeditselseq_active_get, (setter)NULL, (char *)bpy_bmeditselseq_active_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"active",
+ (getter)bpy_bmeditselseq_active_get,
+ (setter)NULL,
+ (char *)bpy_bmeditselseq_active_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
PyDoc_STRVAR(bpy_bmeditselseq_validate_doc,
-".. method:: validate()\n"
-"\n"
-" Ensures all elements in the selection history are selected.\n"
-);
+ ".. method:: validate()\n"
+ "\n"
+ " Ensures all elements in the selection history are selected.\n");
static PyObject *bpy_bmeditselseq_validate(BPy_BMEditSelSeq *self)
{
- BPY_BM_CHECK_OBJ(self);
- BM_select_history_validate(self->bm);
- Py_RETURN_NONE;
+ BPY_BM_CHECK_OBJ(self);
+ BM_select_history_validate(self->bm);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bmeditselseq_clear_doc,
-".. method:: clear()\n"
-"\n"
-" Empties the selection history.\n"
-);
+ ".. method:: clear()\n"
+ "\n"
+ " Empties the selection history.\n");
static PyObject *bpy_bmeditselseq_clear(BPy_BMEditSelSeq *self)
{
- BPY_BM_CHECK_OBJ(self);
- BM_select_history_clear(self->bm);
- Py_RETURN_NONE;
+ BPY_BM_CHECK_OBJ(self);
+ BM_select_history_clear(self->bm);
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpy_bmeditselseq_add_doc,
-".. method:: add(element)\n"
-"\n"
-" Add an element to the selection history (no action taken if its already added).\n"
-);
+PyDoc_STRVAR(
+ bpy_bmeditselseq_add_doc,
+ ".. method:: add(element)\n"
+ "\n"
+ " Add an element to the selection history (no action taken if its already added).\n");
static PyObject *bpy_bmeditselseq_add(BPy_BMEditSelSeq *self, BPy_BMElem *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if ((BPy_BMVert_Check(value) ||
- BPy_BMEdge_Check(value) ||
- BPy_BMFace_Check(value)) == false)
- {
- PyErr_Format(PyExc_TypeError,
- "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if ((BPy_BMVert_Check(value) || BPy_BMEdge_Check(value) || BPy_BMFace_Check(value)) == false) {
+ PyErr_Format(
+ PyExc_TypeError, "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.add()", value);
+ BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.add()", value);
- BM_select_history_store(self->bm, value->ele);
+ BM_select_history_store(self->bm, value->ele);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bmeditselseq_remove_doc,
-".. method:: remove(element)\n"
-"\n"
-" Remove an element from the selection history.\n"
-);
+ ".. method:: remove(element)\n"
+ "\n"
+ " Remove an element from the selection history.\n");
static PyObject *bpy_bmeditselseq_remove(BPy_BMEditSelSeq *self, BPy_BMElem *value)
{
- BPY_BM_CHECK_OBJ(self);
-
- if ((BPy_BMVert_Check(value) ||
- BPy_BMEdge_Check(value) ||
- BPy_BMFace_Check(value)) == false)
- {
- PyErr_Format(PyExc_TypeError,
- "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
- return NULL;
- }
-
- BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.remove()", value);
-
- if (BM_select_history_remove(self->bm, value->ele) == false) {
- PyErr_SetString(PyExc_ValueError,
- "Element not found in selection history");
- return NULL;
- }
-
- Py_RETURN_NONE;
+ BPY_BM_CHECK_OBJ(self);
+
+ if ((BPy_BMVert_Check(value) || BPy_BMEdge_Check(value) || BPy_BMFace_Check(value)) == false) {
+ PyErr_Format(
+ PyExc_TypeError, "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+
+ BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.remove()", value);
+
+ if (BM_select_history_remove(self->bm, value->ele) == false) {
+ PyErr_SetString(PyExc_ValueError, "Element not found in selection history");
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpy_bmeditselseq_discard_doc,
-".. method:: discard(element)\n"
-"\n"
-" Discard an element from the selection history.\n"
-"\n"
-" Like remove but doesn't raise an error when the elements not in the selection list.\n"
-);
+PyDoc_STRVAR(
+ bpy_bmeditselseq_discard_doc,
+ ".. method:: discard(element)\n"
+ "\n"
+ " Discard an element from the selection history.\n"
+ "\n"
+ " Like remove but doesn't raise an error when the elements not in the selection list.\n");
static PyObject *bpy_bmeditselseq_discard(BPy_BMEditSelSeq *self, BPy_BMElem *value)
{
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- if ((BPy_BMVert_Check(value) ||
- BPy_BMEdge_Check(value) ||
- BPy_BMFace_Check(value)) == false)
- {
- PyErr_Format(PyExc_TypeError,
- "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if ((BPy_BMVert_Check(value) || BPy_BMEdge_Check(value) || BPy_BMFace_Check(value)) == false) {
+ PyErr_Format(
+ PyExc_TypeError, "Expected a BMVert/BMedge/BMFace not a %.200s", Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.discard()", value);
+ BPY_BM_CHECK_SOURCE_OBJ(self->bm, "select_history.discard()", value);
- BM_select_history_remove(self->bm, value->ele);
+ BM_select_history_remove(self->bm, value->ele);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef bpy_bmeditselseq_methods[] = {
- {"validate", (PyCFunction)bpy_bmeditselseq_validate, METH_NOARGS, bpy_bmeditselseq_validate_doc},
- {"clear", (PyCFunction)bpy_bmeditselseq_clear, METH_NOARGS, bpy_bmeditselseq_clear_doc},
-
- {"add", (PyCFunction)bpy_bmeditselseq_add, METH_O, bpy_bmeditselseq_add_doc},
- {"remove", (PyCFunction)bpy_bmeditselseq_remove, METH_O, bpy_bmeditselseq_remove_doc},
- {"discard", (PyCFunction)bpy_bmeditselseq_discard, METH_O, bpy_bmeditselseq_discard_doc},
- {NULL, NULL, 0, NULL},
+ {"validate",
+ (PyCFunction)bpy_bmeditselseq_validate,
+ METH_NOARGS,
+ bpy_bmeditselseq_validate_doc},
+ {"clear", (PyCFunction)bpy_bmeditselseq_clear, METH_NOARGS, bpy_bmeditselseq_clear_doc},
+
+ {"add", (PyCFunction)bpy_bmeditselseq_add, METH_O, bpy_bmeditselseq_add_doc},
+ {"remove", (PyCFunction)bpy_bmeditselseq_remove, METH_O, bpy_bmeditselseq_remove_doc},
+ {"discard", (PyCFunction)bpy_bmeditselseq_discard, METH_O, bpy_bmeditselseq_discard_doc},
+ {NULL, NULL, 0, NULL},
};
-
/* Sequences
* ========= */
static Py_ssize_t bpy_bmeditselseq_length(BPy_BMEditSelSeq *self)
{
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- return BLI_listbase_count(&self->bm->selected);
+ return BLI_listbase_count(&self->bm->selected);
}
static PyObject *bpy_bmeditselseq_subscript_int(BPy_BMEditSelSeq *self, int keynum)
{
- BMEditSelection *ese;
-
- BPY_BM_CHECK_OBJ(self);
-
- if (keynum < 0) {
- ese = BLI_rfindlink(&self->bm->selected, -1 - keynum);
- }
- else {
- ese = BLI_findlink(&self->bm->selected, keynum);
- }
-
- if (ese) {
- return BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
- }
- else {
- PyErr_Format(PyExc_IndexError,
- "BMElemSeq[index]: index %d out of range", keynum);
- return NULL;
- }
+ BMEditSelection *ese;
+
+ BPY_BM_CHECK_OBJ(self);
+
+ if (keynum < 0) {
+ ese = BLI_rfindlink(&self->bm->selected, -1 - keynum);
+ }
+ else {
+ ese = BLI_findlink(&self->bm->selected, keynum);
+ }
+
+ if (ese) {
+ return BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
+ }
+ else {
+ PyErr_Format(PyExc_IndexError, "BMElemSeq[index]: index %d out of range", keynum);
+ return NULL;
+ }
}
-static PyObject *bpy_bmeditselseq_subscript_slice(BPy_BMEditSelSeq *self, Py_ssize_t start, Py_ssize_t stop)
+static PyObject *bpy_bmeditselseq_subscript_slice(BPy_BMEditSelSeq *self,
+ Py_ssize_t start,
+ Py_ssize_t stop)
{
- int count = 0;
- bool ok;
+ int count = 0;
+ bool ok;
- PyObject *list;
- BMEditSelection *ese;
+ PyObject *list;
+ BMEditSelection *ese;
- BPY_BM_CHECK_OBJ(self);
+ BPY_BM_CHECK_OBJ(self);
- list = PyList_New(0);
+ list = PyList_New(0);
- ese = self->bm->selected.first;
+ ese = self->bm->selected.first;
- ok = (ese != NULL);
+ ok = (ese != NULL);
- if (UNLIKELY(ok == false)) {
- return list;
- }
+ if (UNLIKELY(ok == false)) {
+ return list;
+ }
- /* first loop up-until the start */
- for (ok = true; ok; ok = ((ese = ese->next) != NULL)) {
- if (count == start) {
- break;
- }
- count++;
- }
+ /* first loop up-until the start */
+ for (ok = true; ok; ok = ((ese = ese->next) != NULL)) {
+ if (count == start) {
+ break;
+ }
+ count++;
+ }
- /* add items until stop */
- do {
- PyList_APPEND(list, BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head));
- count++;
- if (count == stop) {
- break;
- }
- } while ((ese = ese->next));
+ /* add items until stop */
+ do {
+ PyList_APPEND(list, BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head));
+ count++;
+ if (count == stop) {
+ break;
+ }
+ } while ((ese = ese->next));
- return list;
+ return list;
}
static PyObject *bpy_bmeditselseq_subscript(BPy_BMEditSelSeq *self, PyObject *key)
{
- /* don't need error check here */
- if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- return bpy_bmeditselseq_subscript_int(self, i);
- }
- else if (PySlice_Check(key)) {
- PySliceObject *key_slice = (PySliceObject *)key;
- Py_ssize_t step = 1;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError,
- "BMElemSeq[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- return bpy_bmeditselseq_subscript_slice(self, 0, PY_SSIZE_T_MAX);
- }
- else {
- Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
-
- /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
- if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
- return NULL;
- }
- if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
- return NULL;
- }
-
- if (start < 0 || stop < 0) {
- /* only get the length for negative values */
- Py_ssize_t len = bpy_bmeditselseq_length(self);
- if (start < 0) {
- start += len;
- }
- if (stop < 0) {
- stop += len;
- }
- }
-
- if (stop - start <= 0) {
- return PyList_New(0);
- }
- else {
- return bpy_bmeditselseq_subscript_slice(self, start, stop);
- }
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "BMElemSeq[key]: invalid key, key must be an int");
- return NULL;
- }
+ /* don't need error check here */
+ if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ return bpy_bmeditselseq_subscript_int(self, i);
+ }
+ else if (PySlice_Check(key)) {
+ PySliceObject *key_slice = (PySliceObject *)key;
+ Py_ssize_t step = 1;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "BMElemSeq[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ return bpy_bmeditselseq_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ }
+ else {
+ Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
+
+ /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
+ if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
+ return NULL;
+ }
+ if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
+ return NULL;
+ }
+
+ if (start < 0 || stop < 0) {
+ /* only get the length for negative values */
+ Py_ssize_t len = bpy_bmeditselseq_length(self);
+ if (start < 0) {
+ start += len;
+ }
+ if (stop < 0) {
+ stop += len;
+ }
+ }
+
+ if (stop - start <= 0) {
+ return PyList_New(0);
+ }
+ else {
+ return bpy_bmeditselseq_subscript_slice(self, start, stop);
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "BMElemSeq[key]: invalid key, key must be an int");
+ return NULL;
+ }
}
static int bpy_bmeditselseq_contains(BPy_BMEditSelSeq *self, PyObject *value)
{
- BPy_BMElem *value_bm_ele;
+ BPy_BMElem *value_bm_ele;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- value_bm_ele = (BPy_BMElem *)value;
- if (value_bm_ele->bm == self->bm) {
- return BM_select_history_check(self->bm, value_bm_ele->ele);
- }
+ value_bm_ele = (BPy_BMElem *)value;
+ if (value_bm_ele->bm == self->bm) {
+ return BM_select_history_check(self->bm, value_bm_ele->ele);
+ }
- return 0;
+ return 0;
}
static PySequenceMethods bpy_bmeditselseq_as_sequence = {
- (lenfunc)bpy_bmeditselseq_length, /* sq_length */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- (ssizeargfunc)bpy_bmeditselseq_subscript_int,/* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* sq_slice */
- (ssizeobjargproc)NULL, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)bpy_bmeditselseq_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)bpy_bmeditselseq_length, /* sq_length */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ (ssizeargfunc)bpy_bmeditselseq_subscript_int,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* sq_slice */
+ (ssizeobjargproc)NULL, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)bpy_bmeditselseq_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyMappingMethods bpy_bmeditselseq_as_mapping = {
- (lenfunc)bpy_bmeditselseq_length, /* mp_length */
- (binaryfunc)bpy_bmeditselseq_subscript, /* mp_subscript */
- (objobjargproc)NULL, /* mp_ass_subscript */
+ (lenfunc)bpy_bmeditselseq_length, /* mp_length */
+ (binaryfunc)bpy_bmeditselseq_subscript, /* mp_subscript */
+ (objobjargproc)NULL, /* mp_ass_subscript */
};
-
/* Iterator
* -------- */
static PyObject *bpy_bmeditselseq_iter(BPy_BMEditSelSeq *self)
{
- BPy_BMEditSelIter *py_iter;
+ BPy_BMEditSelIter *py_iter;
- BPY_BM_CHECK_OBJ(self);
- py_iter = (BPy_BMEditSelIter *)BPy_BMEditSelIter_CreatePyObject(self->bm);
- py_iter->ese = self->bm->selected.first;
- return (PyObject *)py_iter;
+ BPY_BM_CHECK_OBJ(self);
+ py_iter = (BPy_BMEditSelIter *)BPy_BMEditSelIter_CreatePyObject(self->bm);
+ py_iter->ese = self->bm->selected.first;
+ return (PyObject *)py_iter;
}
static PyObject *bpy_bmeditseliter_next(BPy_BMEditSelIter *self)
{
- BMEditSelection *ese = self->ese;
- if (ese == NULL) {
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
- else {
- self->ese = ese->next;
- return (PyObject *)BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
- }
+ BMEditSelection *ese = self->ese;
+ if (ese == NULL) {
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+ else {
+ self->ese = ese->next;
+ return (PyObject *)BPy_BMElem_CreatePyObject(self->bm, &ese->ele->head);
+ }
}
PyTypeObject BPy_BMEditSelSeq_Type;
PyTypeObject BPy_BMEditSelIter_Type;
-
PyObject *BPy_BMEditSel_CreatePyObject(BMesh *bm)
{
- BPy_BMEditSelSeq *self = PyObject_New(BPy_BMEditSelSeq, &BPy_BMEditSelSeq_Type);
- self->bm = bm;
- /* caller must initialize 'iter' member */
- return (PyObject *)self;
+ BPy_BMEditSelSeq *self = PyObject_New(BPy_BMEditSelSeq, &BPy_BMEditSelSeq_Type);
+ self->bm = bm;
+ /* caller must initialize 'iter' member */
+ return (PyObject *)self;
}
PyObject *BPy_BMEditSelIter_CreatePyObject(BMesh *bm)
{
- BPy_BMEditSelIter *self = PyObject_New(BPy_BMEditSelIter, &BPy_BMEditSelIter_Type);
- self->bm = bm;
- /* caller must initialize 'iter' member */
- return (PyObject *)self;
+ BPy_BMEditSelIter *self = PyObject_New(BPy_BMEditSelIter, &BPy_BMEditSelIter_Type);
+ self->bm = bm;
+ /* caller must initialize 'iter' member */
+ return (PyObject *)self;
}
void BPy_BM_init_types_select(void)
{
- BPy_BMEditSelSeq_Type.tp_basicsize = sizeof(BPy_BMEditSelSeq);
- BPy_BMEditSelIter_Type.tp_basicsize = sizeof(BPy_BMEditSelIter);
+ BPy_BMEditSelSeq_Type.tp_basicsize = sizeof(BPy_BMEditSelSeq);
+ BPy_BMEditSelIter_Type.tp_basicsize = sizeof(BPy_BMEditSelIter);
- BPy_BMEditSelSeq_Type.tp_name = "BMEditSelSeq";
- BPy_BMEditSelIter_Type.tp_name = "BMEditSelIter";
+ BPy_BMEditSelSeq_Type.tp_name = "BMEditSelSeq";
+ BPy_BMEditSelIter_Type.tp_name = "BMEditSelIter";
- BPy_BMEditSelSeq_Type.tp_doc = NULL; /* todo */
- BPy_BMEditSelIter_Type.tp_doc = NULL;
+ BPy_BMEditSelSeq_Type.tp_doc = NULL; /* todo */
+ BPy_BMEditSelIter_Type.tp_doc = NULL;
- BPy_BMEditSelSeq_Type.tp_repr = (reprfunc)NULL;
- BPy_BMEditSelIter_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMEditSelSeq_Type.tp_repr = (reprfunc)NULL;
+ BPy_BMEditSelIter_Type.tp_repr = (reprfunc)NULL;
- BPy_BMEditSelSeq_Type.tp_getset = bpy_bmeditselseq_getseters;
- BPy_BMEditSelIter_Type.tp_getset = NULL;
+ BPy_BMEditSelSeq_Type.tp_getset = bpy_bmeditselseq_getseters;
+ BPy_BMEditSelIter_Type.tp_getset = NULL;
- BPy_BMEditSelSeq_Type.tp_methods = bpy_bmeditselseq_methods;
- BPy_BMEditSelIter_Type.tp_methods = NULL;
+ BPy_BMEditSelSeq_Type.tp_methods = bpy_bmeditselseq_methods;
+ BPy_BMEditSelIter_Type.tp_methods = NULL;
- BPy_BMEditSelSeq_Type.tp_as_sequence = &bpy_bmeditselseq_as_sequence;
+ BPy_BMEditSelSeq_Type.tp_as_sequence = &bpy_bmeditselseq_as_sequence;
- BPy_BMEditSelSeq_Type.tp_as_mapping = &bpy_bmeditselseq_as_mapping;
+ BPy_BMEditSelSeq_Type.tp_as_mapping = &bpy_bmeditselseq_as_mapping;
- BPy_BMEditSelSeq_Type.tp_iter = (getiterfunc)bpy_bmeditselseq_iter;
+ BPy_BMEditSelSeq_Type.tp_iter = (getiterfunc)bpy_bmeditselseq_iter;
- /* only 1 iteratir so far */
- BPy_BMEditSelIter_Type.tp_iternext = (iternextfunc)bpy_bmeditseliter_next;
+ /* only 1 iteratir so far */
+ BPy_BMEditSelIter_Type.tp_iternext = (iternextfunc)bpy_bmeditseliter_next;
- BPy_BMEditSelSeq_Type.tp_dealloc = NULL; //(destructor)bpy_bmeditselseq_dealloc;
- BPy_BMEditSelIter_Type.tp_dealloc = NULL; //(destructor)bpy_bmvert_dealloc;
+ BPy_BMEditSelSeq_Type.tp_dealloc = NULL; //(destructor)bpy_bmeditselseq_dealloc;
+ BPy_BMEditSelIter_Type.tp_dealloc = NULL; //(destructor)bpy_bmvert_dealloc;
- BPy_BMEditSelSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- BPy_BMEditSelIter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMEditSelSeq_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ BPy_BMEditSelIter_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- PyType_Ready(&BPy_BMEditSelSeq_Type);
- PyType_Ready(&BPy_BMEditSelIter_Type);
+ PyType_Ready(&BPy_BMEditSelSeq_Type);
+ PyType_Ready(&BPy_BMEditSelIter_Type);
}
-
/* utility function */
/**
@@ -439,29 +429,35 @@ void BPy_BM_init_types_select(void)
*/
int BPy_BMEditSel_Assign(BPy_BMesh *self, PyObject *value)
{
- BMesh *bm;
- Py_ssize_t value_len;
- Py_ssize_t i;
- BMElem **value_array = NULL;
+ BMesh *bm;
+ Py_ssize_t value_len;
+ Py_ssize_t i;
+ BMElem **value_array = NULL;
- BPY_BM_CHECK_INT(self);
+ BPY_BM_CHECK_INT(self);
- bm = self->bm;
+ bm = self->bm;
- value_array = BPy_BMElem_PySeq_As_Array(&bm, value, 0, PY_SSIZE_T_MAX,
- &value_len, BM_VERT | BM_EDGE | BM_FACE,
- true, true, "BMesh.select_history = value");
+ value_array = BPy_BMElem_PySeq_As_Array(&bm,
+ value,
+ 0,
+ PY_SSIZE_T_MAX,
+ &value_len,
+ BM_VERT | BM_EDGE | BM_FACE,
+ true,
+ true,
+ "BMesh.select_history = value");
- if (value_array == NULL) {
- return -1;
- }
+ if (value_array == NULL) {
+ return -1;
+ }
- BM_select_history_clear(bm);
+ BM_select_history_clear(bm);
- for (i = 0; i < value_len; i++) {
- BM_select_history_store_notest(bm, value_array[i]);
- }
+ for (i = 0; i < value_len; i++) {
+ BM_select_history_store_notest(bm, value_array[i]);
+ }
- PyMem_FREE(value_array);
- return 0;
+ PyMem_FREE(value_array);
+ return 0;
}
diff --git a/source/blender/python/bmesh/bmesh_py_types_select.h b/source/blender/python/bmesh/bmesh_py_types_select.h
index 2bf2214d7f9..593857a5083 100644
--- a/source/blender/python/bmesh/bmesh_py_types_select.h
+++ b/source/blender/python/bmesh/bmesh_py_types_select.h
@@ -29,24 +29,22 @@ struct BPy_BMesh;
extern PyTypeObject BPy_BMEditSelSeq_Type;
extern PyTypeObject BPy_BMEditSelIter_Type;
-#define BPy_BMSelectHistory_Check(v) (Py_TYPE(v) == &BPy_BMEditSelSeq_Type)
-#define BPy_BMSelectHistoryIter_Check(v) (Py_TYPE(v) == &BPy_BMEditSelIter_Type)
+#define BPy_BMSelectHistory_Check(v) (Py_TYPE(v) == &BPy_BMEditSelSeq_Type)
+#define BPy_BMSelectHistoryIter_Check(v) (Py_TYPE(v) == &BPy_BMEditSelIter_Type)
typedef struct BPy_BMEditSelSeq {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
} BPy_BMEditSelSeq;
typedef struct BPy_BMEditSelIter {
- PyObject_VAR_HEAD
- struct BMesh *bm; /* keep first */
- struct BMEditSelection *ese;
+ PyObject_VAR_HEAD struct BMesh *bm; /* keep first */
+ struct BMEditSelection *ese;
} BPy_BMEditSelIter;
void BPy_BM_init_types_select(void);
PyObject *BPy_BMEditSel_CreatePyObject(BMesh *bm);
PyObject *BPy_BMEditSelIter_CreatePyObject(BMesh *bm);
-int BPy_BMEditSel_Assign(struct BPy_BMesh *self, PyObject *value);
+int BPy_BMEditSel_Assign(struct BPy_BMesh *self, PyObject *value);
#endif /* __BMESH_PY_SELECT_H__ */
diff --git a/source/blender/python/bmesh/bmesh_py_utils.c b/source/blender/python/bmesh/bmesh_py_utils.c
index 8b8dcb518b9..01f6cdf6e26 100644
--- a/source/blender/python/bmesh/bmesh_py_utils.c
+++ b/source/blender/python/bmesh/bmesh_py_utils.c
@@ -40,803 +40,821 @@
#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
-
PyDoc_STRVAR(bpy_bm_utils_vert_collapse_edge_doc,
-".. method:: vert_collapse_edge(vert, edge)\n"
-"\n"
-" Collapse a vertex into an edge.\n"
-"\n"
-" :arg vert: The vert that will be collapsed.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :arg edge: The edge to collapse into.\n"
-" :type edge: :class:`bmesh.types.BMEdge`\n"
-" :return: The resulting edge from the collapse operation.\n"
-" :rtype: :class:`bmesh.types.BMEdge`\n"
-);
+ ".. method:: vert_collapse_edge(vert, edge)\n"
+ "\n"
+ " Collapse a vertex into an edge.\n"
+ "\n"
+ " :arg vert: The vert that will be collapsed.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :arg edge: The edge to collapse into.\n"
+ " :type edge: :class:`bmesh.types.BMEdge`\n"
+ " :return: The resulting edge from the collapse operation.\n"
+ " :rtype: :class:`bmesh.types.BMEdge`\n");
static PyObject *bpy_bm_utils_vert_collapse_edge(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMEdge *py_edge;
- BPy_BMVert *py_vert;
-
- BMesh *bm;
- BMEdge *e_new = NULL;
-
- if (!PyArg_ParseTuple(args, "O!O!:vert_collapse_edge",
- &BPy_BMVert_Type, &py_vert,
- &BPy_BMEdge_Type, &py_edge))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_edge);
- BPY_BM_CHECK_OBJ(py_vert);
-
- /* this doubles for checking that the verts are in the same mesh */
- if (!(py_edge->e->v1 == py_vert->v ||
- py_edge->e->v2 == py_vert->v))
- {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_edge(vert, edge): the vertex is not found in the edge");
- return NULL;
- }
-
- if (BM_vert_edge_count_is_over(py_vert->v, 2)) {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_edge(vert, edge): vert has more than 2 connected edges");
- return NULL;
- }
-
- bm = py_edge->bm;
-
- e_new = BM_vert_collapse_edge(bm, py_edge->e, py_vert->v, true, true);
-
- if (e_new) {
- return BPy_BMEdge_CreatePyObject(bm, e_new);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_edge(vert, edge): no new edge created, internal error");
- return NULL;
- }
+ BPy_BMEdge *py_edge;
+ BPy_BMVert *py_vert;
+
+ BMesh *bm;
+ BMEdge *e_new = NULL;
+
+ if (!PyArg_ParseTuple(args,
+ "O!O!:vert_collapse_edge",
+ &BPy_BMVert_Type,
+ &py_vert,
+ &BPy_BMEdge_Type,
+ &py_edge)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_edge);
+ BPY_BM_CHECK_OBJ(py_vert);
+
+ /* this doubles for checking that the verts are in the same mesh */
+ if (!(py_edge->e->v1 == py_vert->v || py_edge->e->v2 == py_vert->v)) {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_edge(vert, edge): the vertex is not found in the edge");
+ return NULL;
+ }
+
+ if (BM_vert_edge_count_is_over(py_vert->v, 2)) {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_edge(vert, edge): vert has more than 2 connected edges");
+ return NULL;
+ }
+
+ bm = py_edge->bm;
+
+ e_new = BM_vert_collapse_edge(bm, py_edge->e, py_vert->v, true, true);
+
+ if (e_new) {
+ return BPy_BMEdge_CreatePyObject(bm, e_new);
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_edge(vert, edge): no new edge created, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_vert_collapse_faces_doc,
-".. method:: vert_collapse_faces(vert, edge, fac, join_faces)\n"
-"\n"
-" Collapses a vertex that has only two manifold edges onto a vertex it shares an edge with.\n"
-"\n"
-" :arg vert: The vert that will be collapsed.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :arg edge: The edge to collapse into.\n"
-" :type edge: :class:`bmesh.types.BMEdge`\n"
-" :arg fac: The factor to use when merging customdata [0 - 1].\n"
-" :type fac: float\n"
-" :return: The resulting edge from the collapse operation.\n"
-" :rtype: :class:`bmesh.types.BMEdge`\n"
-);
+ ".. method:: vert_collapse_faces(vert, edge, fac, join_faces)\n"
+ "\n"
+ " Collapses a vertex that has only two manifold edges onto a vertex it shares an "
+ "edge with.\n"
+ "\n"
+ " :arg vert: The vert that will be collapsed.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :arg edge: The edge to collapse into.\n"
+ " :type edge: :class:`bmesh.types.BMEdge`\n"
+ " :arg fac: The factor to use when merging customdata [0 - 1].\n"
+ " :type fac: float\n"
+ " :return: The resulting edge from the collapse operation.\n"
+ " :rtype: :class:`bmesh.types.BMEdge`\n");
static PyObject *bpy_bm_utils_vert_collapse_faces(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMEdge *py_edge;
- BPy_BMVert *py_vert;
-
- float fac;
- int do_join_faces;
-
- BMesh *bm;
- BMEdge *e_new = NULL;
-
- if (!PyArg_ParseTuple(args, "O!O!fi:vert_collapse_faces",
- &BPy_BMVert_Type, &py_vert,
- &BPy_BMEdge_Type, &py_edge,
- &fac, &do_join_faces))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_edge);
- BPY_BM_CHECK_OBJ(py_vert);
-
- /* this doubles for checking that the verts are in the same mesh */
- if (!(py_edge->e->v1 == py_vert->v ||
- py_edge->e->v2 == py_vert->v))
- {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_faces(vert, edge): the vertex is not found in the edge");
- return NULL;
- }
-
- if (BM_vert_edge_count_is_over(py_vert->v, 2)) {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_faces(vert, edge): vert has more than 2 connected edges");
- return NULL;
- }
-
- bm = py_edge->bm;
-
- e_new = BM_vert_collapse_faces(bm, py_edge->e, py_vert->v, clamp_f(fac, 0.0f, 1.0f), true, do_join_faces, true);
-
- if (e_new) {
- return BPy_BMEdge_CreatePyObject(bm, e_new);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "vert_collapse_faces(vert, edge): no new edge created, internal error");
- return NULL;
- }
+ BPy_BMEdge *py_edge;
+ BPy_BMVert *py_vert;
+
+ float fac;
+ int do_join_faces;
+
+ BMesh *bm;
+ BMEdge *e_new = NULL;
+
+ if (!PyArg_ParseTuple(args,
+ "O!O!fi:vert_collapse_faces",
+ &BPy_BMVert_Type,
+ &py_vert,
+ &BPy_BMEdge_Type,
+ &py_edge,
+ &fac,
+ &do_join_faces)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_edge);
+ BPY_BM_CHECK_OBJ(py_vert);
+
+ /* this doubles for checking that the verts are in the same mesh */
+ if (!(py_edge->e->v1 == py_vert->v || py_edge->e->v2 == py_vert->v)) {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_faces(vert, edge): the vertex is not found in the edge");
+ return NULL;
+ }
+
+ if (BM_vert_edge_count_is_over(py_vert->v, 2)) {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_faces(vert, edge): vert has more than 2 connected edges");
+ return NULL;
+ }
+
+ bm = py_edge->bm;
+
+ e_new = BM_vert_collapse_faces(
+ bm, py_edge->e, py_vert->v, clamp_f(fac, 0.0f, 1.0f), true, do_join_faces, true);
+
+ if (e_new) {
+ return BPy_BMEdge_CreatePyObject(bm, e_new);
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "vert_collapse_faces(vert, edge): no new edge created, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_vert_dissolve_doc,
-".. method:: vert_dissolve(vert)\n"
-"\n"
-" Dissolve this vertex (will be removed).\n"
-"\n"
-" :arg vert: The vert to be dissolved.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :return: True when the vertex dissolve is successful.\n"
-" :rtype: boolean\n"
-);
+ ".. method:: vert_dissolve(vert)\n"
+ "\n"
+ " Dissolve this vertex (will be removed).\n"
+ "\n"
+ " :arg vert: The vert to be dissolved.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :return: True when the vertex dissolve is successful.\n"
+ " :rtype: boolean\n");
static PyObject *bpy_bm_utils_vert_dissolve(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMVert *py_vert;
+ BPy_BMVert *py_vert;
- BMesh *bm;
+ BMesh *bm;
- if (!PyArg_ParseTuple(args, "O!:vert_dissolve",
- &BPy_BMVert_Type, &py_vert))
- {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O!:vert_dissolve", &BPy_BMVert_Type, &py_vert)) {
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(py_vert);
+ BPY_BM_CHECK_OBJ(py_vert);
- bm = py_vert->bm;
+ bm = py_vert->bm;
- return PyBool_FromLong((BM_vert_dissolve(bm, py_vert->v)));
+ return PyBool_FromLong((BM_vert_dissolve(bm, py_vert->v)));
}
PyDoc_STRVAR(bpy_bm_utils_vert_splice_doc,
-".. method:: vert_splice(vert, vert_target)\n"
-"\n"
-" Splice vert into vert_target.\n"
-"\n"
-" :arg vert: The vertex to be removed.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :arg vert_target: The vertex to use.\n"
-" :type vert_target: :class:`bmesh.types.BMVert`\n"
-"\n"
-" .. note:: The verts mustn't share an edge or face.\n"
-);
+ ".. method:: vert_splice(vert, vert_target)\n"
+ "\n"
+ " Splice vert into vert_target.\n"
+ "\n"
+ " :arg vert: The vertex to be removed.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :arg vert_target: The vertex to use.\n"
+ " :type vert_target: :class:`bmesh.types.BMVert`\n"
+ "\n"
+ " .. note:: The verts mustn't share an edge or face.\n");
static PyObject *bpy_bm_utils_vert_splice(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMVert *py_vert;
- BPy_BMVert *py_vert_target;
-
- BMesh *bm;
-
- bool ok;
-
- if (!PyArg_ParseTuple(args, "O!O!:vert_splice",
- &BPy_BMVert_Type, &py_vert,
- &BPy_BMVert_Type, &py_vert_target))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_vert);
- BPY_BM_CHECK_OBJ(py_vert_target);
-
- bm = py_vert->bm;
- BPY_BM_CHECK_SOURCE_OBJ(bm, "vert_splice", py_vert_target);
-
- if (py_vert->v == py_vert_target->v) {
- PyErr_SetString(PyExc_ValueError,
- "vert_splice(...): vert arguments match");
- return NULL;
- }
-
- if (BM_edge_exists(py_vert->v, py_vert_target->v)) {
- PyErr_SetString(PyExc_ValueError,
- "vert_splice(...): verts can't share an edge");
- return NULL;
- }
-
- if (BM_vert_pair_share_face_check(py_vert->v, py_vert_target->v)) {
- PyErr_SetString(PyExc_ValueError,
- "vert_splice(...): verts can't share a face");
- return NULL;
- }
-
- /* should always succeed */
- ok = BM_vert_splice(bm, py_vert_target->v, py_vert->v);
- BLI_assert(ok == true);
- UNUSED_VARS_NDEBUG(ok);
-
- Py_RETURN_NONE;
+ BPy_BMVert *py_vert;
+ BPy_BMVert *py_vert_target;
+
+ BMesh *bm;
+
+ bool ok;
+
+ if (!PyArg_ParseTuple(args,
+ "O!O!:vert_splice",
+ &BPy_BMVert_Type,
+ &py_vert,
+ &BPy_BMVert_Type,
+ &py_vert_target)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_vert);
+ BPY_BM_CHECK_OBJ(py_vert_target);
+
+ bm = py_vert->bm;
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "vert_splice", py_vert_target);
+
+ if (py_vert->v == py_vert_target->v) {
+ PyErr_SetString(PyExc_ValueError, "vert_splice(...): vert arguments match");
+ return NULL;
+ }
+
+ if (BM_edge_exists(py_vert->v, py_vert_target->v)) {
+ PyErr_SetString(PyExc_ValueError, "vert_splice(...): verts can't share an edge");
+ return NULL;
+ }
+
+ if (BM_vert_pair_share_face_check(py_vert->v, py_vert_target->v)) {
+ PyErr_SetString(PyExc_ValueError, "vert_splice(...): verts can't share a face");
+ return NULL;
+ }
+
+ /* should always succeed */
+ ok = BM_vert_splice(bm, py_vert_target->v, py_vert->v);
+ BLI_assert(ok == true);
+ UNUSED_VARS_NDEBUG(ok);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_bm_utils_vert_separate_doc,
-".. method:: vert_separate(vert, edges)\n"
-"\n"
-" Separate this vertex at every edge.\n"
-"\n"
-" :arg vert: The vert to be separated.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :arg edges: The edges to separated.\n"
-" :type edges: :class:`bmesh.types.BMEdge`\n"
-" :return: The newly separated verts (including the vertex passed).\n"
-" :rtype: tuple of :class:`bmesh.types.BMVert`\n"
-);
+ ".. method:: vert_separate(vert, edges)\n"
+ "\n"
+ " Separate this vertex at every edge.\n"
+ "\n"
+ " :arg vert: The vert to be separated.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :arg edges: The edges to separated.\n"
+ " :type edges: :class:`bmesh.types.BMEdge`\n"
+ " :return: The newly separated verts (including the vertex passed).\n"
+ " :rtype: tuple of :class:`bmesh.types.BMVert`\n");
static PyObject *bpy_bm_utils_vert_separate(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMVert *py_vert;
- PyObject *edge_seq;
+ BPy_BMVert *py_vert;
+ PyObject *edge_seq;
- BMesh *bm;
- BMVert **elem;
- int elem_len;
+ BMesh *bm;
+ BMVert **elem;
+ int elem_len;
- /* edges to split */
- BMEdge **edge_array;
- Py_ssize_t edge_array_len;
+ /* edges to split */
+ BMEdge **edge_array;
+ Py_ssize_t edge_array_len;
- PyObject *ret;
+ PyObject *ret;
+ if (!PyArg_ParseTuple(args, "O!O:vert_separate", &BPy_BMVert_Type, &py_vert, &edge_seq)) {
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "O!O:vert_separate",
- &BPy_BMVert_Type, &py_vert,
- &edge_seq))
- {
- return NULL;
- }
+ BPY_BM_CHECK_OBJ(py_vert);
- BPY_BM_CHECK_OBJ(py_vert);
+ bm = py_vert->bm;
- bm = py_vert->bm;
+ edge_array = BPy_BMElem_PySeq_As_Array(&bm,
+ edge_seq,
+ 0,
+ PY_SSIZE_T_MAX,
+ &edge_array_len,
+ BM_EDGE,
+ true,
+ true,
+ "vert_separate(...)");
- edge_array = BPy_BMElem_PySeq_As_Array(&bm, edge_seq, 0, PY_SSIZE_T_MAX,
- &edge_array_len, BM_EDGE,
- true, true, "vert_separate(...)");
+ if (edge_array == NULL) {
+ return NULL;
+ }
- if (edge_array == NULL) {
- return NULL;
- }
+ BM_vert_separate(bm, py_vert->v, edge_array, edge_array_len, false, &elem, &elem_len);
+ /* return collected verts */
+ ret = BPy_BMVert_Array_As_Tuple(bm, elem, elem_len);
+ MEM_freeN(elem);
- BM_vert_separate(bm, py_vert->v, edge_array, edge_array_len, false, &elem, &elem_len);
- /* return collected verts */
- ret = BPy_BMVert_Array_As_Tuple(bm, elem, elem_len);
- MEM_freeN(elem);
+ PyMem_FREE(edge_array);
- PyMem_FREE(edge_array);
-
- return ret;
+ return ret;
}
-
PyDoc_STRVAR(bpy_bm_utils_edge_split_doc,
-".. method:: edge_split(edge, vert, fac)\n"
-"\n"
-" Split an edge, return the newly created data.\n"
-"\n"
-" :arg edge: The edge to split.\n"
-" :type edge: :class:`bmesh.types.BMEdge`\n"
-" :arg vert: One of the verts on the edge, defines the split direction.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :arg fac: The point on the edge where the new vert will be created [0 - 1].\n"
-" :type fac: float\n"
-" :return: The newly created (edge, vert) pair.\n"
-" :rtype: tuple\n"
-);
+ ".. method:: edge_split(edge, vert, fac)\n"
+ "\n"
+ " Split an edge, return the newly created data.\n"
+ "\n"
+ " :arg edge: The edge to split.\n"
+ " :type edge: :class:`bmesh.types.BMEdge`\n"
+ " :arg vert: One of the verts on the edge, defines the split direction.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :arg fac: The point on the edge where the new vert will be created [0 - 1].\n"
+ " :type fac: float\n"
+ " :return: The newly created (edge, vert) pair.\n"
+ " :rtype: tuple\n");
static PyObject *bpy_bm_utils_edge_split(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMEdge *py_edge;
- BPy_BMVert *py_vert;
- float fac;
-
- BMesh *bm;
- BMVert *v_new = NULL;
- BMEdge *e_new = NULL;
-
- if (!PyArg_ParseTuple(args, "O!O!f:edge_split",
- &BPy_BMEdge_Type, &py_edge,
- &BPy_BMVert_Type, &py_vert,
- &fac))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_edge);
- BPY_BM_CHECK_OBJ(py_vert);
-
- /* this doubles for checking that the verts are in the same mesh */
- if (!(py_edge->e->v1 == py_vert->v ||
- py_edge->e->v2 == py_vert->v))
- {
- PyErr_SetString(PyExc_ValueError,
- "edge_split(edge, vert): the vertex is not found in the edge");
- return NULL;
- }
-
- bm = py_edge->bm;
-
- v_new = BM_edge_split(bm, py_edge->e, py_vert->v, &e_new, clamp_f(fac, 0.0f, 1.0f));
-
- if (v_new && e_new) {
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- BPy_BMEdge_CreatePyObject(bm, e_new),
- BPy_BMVert_CreatePyObject(bm, v_new));
- return ret;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "edge_split(edge, vert): couldn't split the edge, internal error");
- return NULL;
- }
+ BPy_BMEdge *py_edge;
+ BPy_BMVert *py_vert;
+ float fac;
+
+ BMesh *bm;
+ BMVert *v_new = NULL;
+ BMEdge *e_new = NULL;
+
+ if (!PyArg_ParseTuple(args,
+ "O!O!f:edge_split",
+ &BPy_BMEdge_Type,
+ &py_edge,
+ &BPy_BMVert_Type,
+ &py_vert,
+ &fac)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_edge);
+ BPY_BM_CHECK_OBJ(py_vert);
+
+ /* this doubles for checking that the verts are in the same mesh */
+ if (!(py_edge->e->v1 == py_vert->v || py_edge->e->v2 == py_vert->v)) {
+ PyErr_SetString(PyExc_ValueError,
+ "edge_split(edge, vert): the vertex is not found in the edge");
+ return NULL;
+ }
+
+ bm = py_edge->bm;
+
+ v_new = BM_edge_split(bm, py_edge->e, py_vert->v, &e_new, clamp_f(fac, 0.0f, 1.0f));
+
+ if (v_new && e_new) {
+ PyObject *ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(
+ ret, BPy_BMEdge_CreatePyObject(bm, e_new), BPy_BMVert_CreatePyObject(bm, v_new));
+ return ret;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "edge_split(edge, vert): couldn't split the edge, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_edge_rotate_doc,
-".. method:: edge_rotate(edge, ccw=False)\n"
-"\n"
-" Rotate the edge and return the newly created edge.\n"
-" If rotating the edge fails, None will be returned.\n"
-"\n"
-" :arg edge: The edge to rotate.\n"
-" :type edge: :class:`bmesh.types.BMEdge`\n"
-" :arg ccw: When True the edge will be rotated counter clockwise.\n"
-" :type ccw: boolean\n"
-" :return: The newly rotated edge.\n"
-" :rtype: :class:`bmesh.types.BMEdge`\n"
-);
+ ".. method:: edge_rotate(edge, ccw=False)\n"
+ "\n"
+ " Rotate the edge and return the newly created edge.\n"
+ " If rotating the edge fails, None will be returned.\n"
+ "\n"
+ " :arg edge: The edge to rotate.\n"
+ " :type edge: :class:`bmesh.types.BMEdge`\n"
+ " :arg ccw: When True the edge will be rotated counter clockwise.\n"
+ " :type ccw: boolean\n"
+ " :return: The newly rotated edge.\n"
+ " :rtype: :class:`bmesh.types.BMEdge`\n");
static PyObject *bpy_bm_utils_edge_rotate(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMEdge *py_edge;
- bool do_ccw = false;
+ BPy_BMEdge *py_edge;
+ bool do_ccw = false;
- BMesh *bm;
- BMEdge *e_new = NULL;
+ BMesh *bm;
+ BMEdge *e_new = NULL;
- if (!PyArg_ParseTuple(
- args, "O!|O&:edge_rotate",
- &BPy_BMEdge_Type, &py_edge,
- PyC_ParseBool, &do_ccw))
- {
- return NULL;
- }
+ if (!PyArg_ParseTuple(
+ args, "O!|O&:edge_rotate", &BPy_BMEdge_Type, &py_edge, PyC_ParseBool, &do_ccw)) {
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(py_edge);
+ BPY_BM_CHECK_OBJ(py_edge);
- bm = py_edge->bm;
+ bm = py_edge->bm;
- e_new = BM_edge_rotate(bm, py_edge->e, do_ccw, 0);
+ e_new = BM_edge_rotate(bm, py_edge->e, do_ccw, 0);
- if (e_new) {
- return BPy_BMEdge_CreatePyObject(bm, e_new);
- }
- else {
- Py_RETURN_NONE;
- }
+ if (e_new) {
+ return BPy_BMEdge_CreatePyObject(bm, e_new);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
-PyDoc_STRVAR(bpy_bm_utils_face_split_doc,
-".. method:: face_split(face, vert_a, vert_b, coords=(), use_exist=True, example=None)\n"
-"\n"
-" Face split with optional intermediate points.\n"
-"\n"
-" :arg face: The face to cut.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-" :arg vert_a: First vertex to cut in the face (face must contain the vert).\n"
-" :type vert_a: :class:`bmesh.types.BMVert`\n"
-" :arg vert_b: Second vertex to cut in the face (face must contain the vert).\n"
-" :type vert_b: :class:`bmesh.types.BMVert`\n"
-" :arg coords: Optional argument to define points in between *vert_a* and *vert_b*.\n"
-" :type coords: sequence of float triplets\n"
-" :arg use_exist: .Use an existing edge if it exists (Only used when *coords* argument is empty or omitted)\n"
-" :type use_exist: boolean\n"
-" :arg example: Newly created edge will copy settings from this one.\n"
-" :type example: :class:`bmesh.types.BMEdge`\n"
-" :return: The newly created face or None on failure.\n"
-" :rtype: (:class:`bmesh.types.BMFace`, :class:`bmesh.types.BMLoop`) pair\n"
-);
+PyDoc_STRVAR(
+ bpy_bm_utils_face_split_doc,
+ ".. method:: face_split(face, vert_a, vert_b, coords=(), use_exist=True, example=None)\n"
+ "\n"
+ " Face split with optional intermediate points.\n"
+ "\n"
+ " :arg face: The face to cut.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n"
+ " :arg vert_a: First vertex to cut in the face (face must contain the vert).\n"
+ " :type vert_a: :class:`bmesh.types.BMVert`\n"
+ " :arg vert_b: Second vertex to cut in the face (face must contain the vert).\n"
+ " :type vert_b: :class:`bmesh.types.BMVert`\n"
+ " :arg coords: Optional argument to define points in between *vert_a* and *vert_b*.\n"
+ " :type coords: sequence of float triplets\n"
+ " :arg use_exist: .Use an existing edge if it exists (Only used when *coords* argument is "
+ "empty or omitted)\n"
+ " :type use_exist: boolean\n"
+ " :arg example: Newly created edge will copy settings from this one.\n"
+ " :type example: :class:`bmesh.types.BMEdge`\n"
+ " :return: The newly created face or None on failure.\n"
+ " :rtype: (:class:`bmesh.types.BMFace`, :class:`bmesh.types.BMLoop`) pair\n");
static PyObject *bpy_bm_utils_face_split(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"face", "vert_a", "vert_b",
- "coords", "use_exist", "example", NULL};
-
- BPy_BMFace *py_face;
- BPy_BMVert *py_vert_a;
- BPy_BMVert *py_vert_b;
-
- /* optional */
- PyObject *py_coords = NULL;
- bool edge_exists = true;
- BPy_BMEdge *py_edge_example = NULL;
-
- float *coords;
- int ncoords = 0;
-
- BMesh *bm;
- BMFace *f_new = NULL;
- BMLoop *l_new = NULL;
- BMLoop *l_a, *l_b;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw,
- "O!O!O!|OO&O!:face_split", (char **)kwlist,
- &BPy_BMFace_Type, &py_face,
- &BPy_BMVert_Type, &py_vert_a,
- &BPy_BMVert_Type, &py_vert_b,
- &py_coords,
- PyC_ParseBool, &edge_exists,
- &BPy_BMEdge_Type, &py_edge_example))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_face);
- BPY_BM_CHECK_OBJ(py_vert_a);
- BPY_BM_CHECK_OBJ(py_vert_b);
-
- if (py_edge_example) {
- BPY_BM_CHECK_OBJ(py_edge_example);
- }
-
- /* this doubles for checking that the verts are in the same mesh */
- if ((l_a = BM_face_vert_share_loop(py_face->f, py_vert_a->v)) &&
- (l_b = BM_face_vert_share_loop(py_face->f, py_vert_b->v)))
- {
- /* pass */
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "face_split(...): one of the verts passed is not found in the face");
- return NULL;
- }
-
- if (py_vert_a->v == py_vert_b->v) {
- PyErr_SetString(PyExc_ValueError,
- "face_split(...): vert arguments must differ");
- return NULL;
- }
-
- if (py_coords) {
- ncoords = mathutils_array_parse_alloc_v(&coords, 3, py_coords, "face_split(...): ");
- if (ncoords == -1) {
- return NULL;
- }
- }
- else {
- if (BM_loop_is_adjacent(l_a, l_b)) {
- PyErr_SetString(PyExc_ValueError,
- "face_split(...): verts are adjacent in the face");
- return NULL;
- }
- }
-
- /* --- main function body --- */
- bm = py_face->bm;
-
- if (ncoords) {
- f_new = BM_face_split_n(bm, py_face->f,
- l_a, l_b,
- (float (*)[3])coords, ncoords,
- &l_new, py_edge_example ? py_edge_example->e : NULL);
- PyMem_Free(coords);
- }
- else {
- f_new = BM_face_split(bm, py_face->f,
- l_a, l_b,
- &l_new, py_edge_example ? py_edge_example->e : NULL, edge_exists);
- }
-
- if (f_new && l_new) {
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- BPy_BMFace_CreatePyObject(bm, f_new),
- BPy_BMLoop_CreatePyObject(bm, l_new));
- return ret;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "face_split(...): couldn't split the face, internal error");
- return NULL;
- }
+ static const char *kwlist[] = {
+ "face", "vert_a", "vert_b", "coords", "use_exist", "example", NULL};
+
+ BPy_BMFace *py_face;
+ BPy_BMVert *py_vert_a;
+ BPy_BMVert *py_vert_b;
+
+ /* optional */
+ PyObject *py_coords = NULL;
+ bool edge_exists = true;
+ BPy_BMEdge *py_edge_example = NULL;
+
+ float *coords;
+ int ncoords = 0;
+
+ BMesh *bm;
+ BMFace *f_new = NULL;
+ BMLoop *l_new = NULL;
+ BMLoop *l_a, *l_b;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O!O!O!|OO&O!:face_split",
+ (char **)kwlist,
+ &BPy_BMFace_Type,
+ &py_face,
+ &BPy_BMVert_Type,
+ &py_vert_a,
+ &BPy_BMVert_Type,
+ &py_vert_b,
+ &py_coords,
+ PyC_ParseBool,
+ &edge_exists,
+ &BPy_BMEdge_Type,
+ &py_edge_example)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_face);
+ BPY_BM_CHECK_OBJ(py_vert_a);
+ BPY_BM_CHECK_OBJ(py_vert_b);
+
+ if (py_edge_example) {
+ BPY_BM_CHECK_OBJ(py_edge_example);
+ }
+
+ /* this doubles for checking that the verts are in the same mesh */
+ if ((l_a = BM_face_vert_share_loop(py_face->f, py_vert_a->v)) &&
+ (l_b = BM_face_vert_share_loop(py_face->f, py_vert_b->v))) {
+ /* pass */
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "face_split(...): one of the verts passed is not found in the face");
+ return NULL;
+ }
+
+ if (py_vert_a->v == py_vert_b->v) {
+ PyErr_SetString(PyExc_ValueError, "face_split(...): vert arguments must differ");
+ return NULL;
+ }
+
+ if (py_coords) {
+ ncoords = mathutils_array_parse_alloc_v(&coords, 3, py_coords, "face_split(...): ");
+ if (ncoords == -1) {
+ return NULL;
+ }
+ }
+ else {
+ if (BM_loop_is_adjacent(l_a, l_b)) {
+ PyErr_SetString(PyExc_ValueError, "face_split(...): verts are adjacent in the face");
+ return NULL;
+ }
+ }
+
+ /* --- main function body --- */
+ bm = py_face->bm;
+
+ if (ncoords) {
+ f_new = BM_face_split_n(bm,
+ py_face->f,
+ l_a,
+ l_b,
+ (float(*)[3])coords,
+ ncoords,
+ &l_new,
+ py_edge_example ? py_edge_example->e : NULL);
+ PyMem_Free(coords);
+ }
+ else {
+ f_new = BM_face_split(bm,
+ py_face->f,
+ l_a,
+ l_b,
+ &l_new,
+ py_edge_example ? py_edge_example->e : NULL,
+ edge_exists);
+ }
+
+ if (f_new && l_new) {
+ PyObject *ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(
+ ret, BPy_BMFace_CreatePyObject(bm, f_new), BPy_BMLoop_CreatePyObject(bm, l_new));
+ return ret;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "face_split(...): couldn't split the face, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_face_split_edgenet_doc,
-".. method:: face_split_edgenet(face, edgenet)\n"
-"\n"
-" Splits a face into any number of regions defined by an edgenet.\n"
-"\n"
-" :arg face: The face to split.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-" :arg face: The face to split.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-" :arg edgenet: Sequence of edges.\n"
-" :type edgenet: :class:`bmesh.types.BMEdge`\n"
-" :return: The newly created faces.\n"
-" :rtype: tuple of (:class:`bmesh.types.BMFace`)\n"
-"\n"
-" .. note::\n"
-"\n"
-" Regions defined by edges need to connect to the face, otherwise they're ignored as loose edges.\n"
-);
-static PyObject *bpy_bm_utils_face_split_edgenet(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
+ ".. method:: face_split_edgenet(face, edgenet)\n"
+ "\n"
+ " Splits a face into any number of regions defined by an edgenet.\n"
+ "\n"
+ " :arg face: The face to split.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n"
+ " :arg face: The face to split.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n"
+ " :arg edgenet: Sequence of edges.\n"
+ " :type edgenet: :class:`bmesh.types.BMEdge`\n"
+ " :return: The newly created faces.\n"
+ " :rtype: tuple of (:class:`bmesh.types.BMFace`)\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " Regions defined by edges need to connect to the face, otherwise they're "
+ "ignored as loose edges.\n");
+static PyObject *bpy_bm_utils_face_split_edgenet(PyObject *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- static const char *kwlist[] = {"face", "edgenet", NULL};
-
- BPy_BMFace *py_face;
- PyObject *edge_seq;
-
- BMEdge **edge_array;
- Py_ssize_t edge_array_len;
-
- BMesh *bm;
-
- BMFace **face_arr;
- int face_arr_len;
- bool ok;
-
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O:face_split_edgenet", (char **)kwlist,
- &BPy_BMFace_Type, &py_face,
- &edge_seq))
- {
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(py_face);
-
- bm = py_face->bm;
-
- edge_array = BPy_BMElem_PySeq_As_Array(&bm, edge_seq, 1, PY_SSIZE_T_MAX,
- &edge_array_len, BM_EDGE,
- true, true, "face_split_edgenet(...)");
-
- if (edge_array == NULL) {
- return NULL;
- }
-
- /* --- main function body --- */
-
- ok = BM_face_split_edgenet(bm, py_face->f, edge_array, edge_array_len,
- &face_arr, &face_arr_len);
-
- PyMem_FREE(edge_array);
-
- if (ok) {
- PyObject *ret = BPy_BMFace_Array_As_Tuple(bm, face_arr, face_arr_len);
- if (face_arr) {
- MEM_freeN(face_arr);
- }
- return ret;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "face_split_edgenet(...): couldn't split the face, internal error");
- return NULL;
- }
+ static const char *kwlist[] = {"face", "edgenet", NULL};
+
+ BPy_BMFace *py_face;
+ PyObject *edge_seq;
+
+ BMEdge **edge_array;
+ Py_ssize_t edge_array_len;
+
+ BMesh *bm;
+
+ BMFace **face_arr;
+ int face_arr_len;
+ bool ok;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O!O:face_split_edgenet",
+ (char **)kwlist,
+ &BPy_BMFace_Type,
+ &py_face,
+ &edge_seq)) {
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(py_face);
+
+ bm = py_face->bm;
+
+ edge_array = BPy_BMElem_PySeq_As_Array(&bm,
+ edge_seq,
+ 1,
+ PY_SSIZE_T_MAX,
+ &edge_array_len,
+ BM_EDGE,
+ true,
+ true,
+ "face_split_edgenet(...)");
+
+ if (edge_array == NULL) {
+ return NULL;
+ }
+
+ /* --- main function body --- */
+
+ ok = BM_face_split_edgenet(bm, py_face->f, edge_array, edge_array_len, &face_arr, &face_arr_len);
+
+ PyMem_FREE(edge_array);
+
+ if (ok) {
+ PyObject *ret = BPy_BMFace_Array_As_Tuple(bm, face_arr, face_arr_len);
+ if (face_arr) {
+ MEM_freeN(face_arr);
+ }
+ return ret;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "face_split_edgenet(...): couldn't split the face, internal error");
+ return NULL;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_face_join_doc,
-".. method:: face_join(faces, remove=True)\n"
-"\n"
-" Joins a sequence of faces.\n"
-"\n"
-" :arg faces: Sequence of faces.\n"
-" :type faces: :class:`bmesh.types.BMFace`\n"
-" :arg remove: Remove the edges and vertices between the faces.\n"
-" :type remove: boolean\n"
-" :return: The newly created face or None on failure.\n"
-" :rtype: :class:`bmesh.types.BMFace`\n"
-);
+ ".. method:: face_join(faces, remove=True)\n"
+ "\n"
+ " Joins a sequence of faces.\n"
+ "\n"
+ " :arg faces: Sequence of faces.\n"
+ " :type faces: :class:`bmesh.types.BMFace`\n"
+ " :arg remove: Remove the edges and vertices between the faces.\n"
+ " :type remove: boolean\n"
+ " :return: The newly created face or None on failure.\n"
+ " :rtype: :class:`bmesh.types.BMFace`\n");
static PyObject *bpy_bm_utils_face_join(PyObject *UNUSED(self), PyObject *args)
{
- BMesh *bm = NULL;
- PyObject *py_face_array;
- BMFace **face_array;
- Py_ssize_t face_seq_len = 0;
- BMFace *f_new;
- bool do_remove = true;
-
- if (!PyArg_ParseTuple(
- args, "O|O&:face_join",
- &py_face_array,
- PyC_ParseBool, &do_remove))
- {
- return NULL;
- }
-
- face_array = BPy_BMElem_PySeq_As_Array(&bm, py_face_array, 2, PY_SSIZE_T_MAX,
- &face_seq_len, BM_FACE,
- true, true, "face_join(...)");
-
- if (face_array == NULL) {
- return NULL; /* error will be set */
- }
-
- /* Go ahead and join the face!
- * --------------------------- */
- f_new = BM_faces_join(bm, face_array, (int)face_seq_len, do_remove);
-
- PyMem_FREE(face_array);
-
- if (f_new) {
- return BPy_BMFace_CreatePyObject(bm, f_new);
- }
- else {
- Py_RETURN_NONE;
- }
+ BMesh *bm = NULL;
+ PyObject *py_face_array;
+ BMFace **face_array;
+ Py_ssize_t face_seq_len = 0;
+ BMFace *f_new;
+ bool do_remove = true;
+
+ if (!PyArg_ParseTuple(args, "O|O&:face_join", &py_face_array, PyC_ParseBool, &do_remove)) {
+ return NULL;
+ }
+
+ face_array = BPy_BMElem_PySeq_As_Array(
+ &bm, py_face_array, 2, PY_SSIZE_T_MAX, &face_seq_len, BM_FACE, true, true, "face_join(...)");
+
+ if (face_array == NULL) {
+ return NULL; /* error will be set */
+ }
+
+ /* Go ahead and join the face!
+ * --------------------------- */
+ f_new = BM_faces_join(bm, face_array, (int)face_seq_len, do_remove);
+
+ PyMem_FREE(face_array);
+
+ if (f_new) {
+ return BPy_BMFace_CreatePyObject(bm, f_new);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
-PyDoc_STRVAR(bpy_bm_utils_face_vert_separate_doc,
-".. method:: face_vert_separate(face, vert)\n"
-"\n"
-" Rip a vertex in a face away and add a new vertex.\n"
-"\n"
-" :arg face: The face to separate.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-" :arg vert: A vertex in the face to separate.\n"
-" :type vert: :class:`bmesh.types.BMVert`\n"
-" :return vert: The newly created vertex or None on failure.\n"
-" :rtype vert: :class:`bmesh.types.BMVert`\n"
-"\n"
-" .. note::\n"
-"\n"
-" This is the same as loop_separate, and has only been added for convenience.\n"
-);
+PyDoc_STRVAR(
+ bpy_bm_utils_face_vert_separate_doc,
+ ".. method:: face_vert_separate(face, vert)\n"
+ "\n"
+ " Rip a vertex in a face away and add a new vertex.\n"
+ "\n"
+ " :arg face: The face to separate.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n"
+ " :arg vert: A vertex in the face to separate.\n"
+ " :type vert: :class:`bmesh.types.BMVert`\n"
+ " :return vert: The newly created vertex or None on failure.\n"
+ " :rtype vert: :class:`bmesh.types.BMVert`\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " This is the same as loop_separate, and has only been added for convenience.\n");
static PyObject *bpy_bm_utils_face_vert_separate(PyObject *UNUSED(self), PyObject *args)
{
- BPy_BMFace *py_face;
- BPy_BMVert *py_vert;
-
- BMesh *bm;
- BMLoop *l;
- BMVert *v_old, *v_new;
-
- if (!PyArg_ParseTuple(args, "O!O!:face_vert_separate",
- &BPy_BMFace_Type, &py_face,
- &BPy_BMVert_Type, &py_vert))
- {
- return NULL;
- }
-
- bm = py_face->bm;
-
- BPY_BM_CHECK_OBJ(py_face);
- BPY_BM_CHECK_SOURCE_OBJ(bm, "face_vert_separate()", py_vert);
-
- l = BM_face_vert_share_loop(py_face->f, py_vert->v);
-
- if (l == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "vertex not found in face");
- return NULL;
- }
-
- v_old = l->v;
- v_new = BM_face_loop_separate(bm, l);
-
- if (v_new != v_old) {
- return BPy_BMVert_CreatePyObject(bm, v_new);
- }
- else {
- Py_RETURN_NONE;
- }
+ BPy_BMFace *py_face;
+ BPy_BMVert *py_vert;
+
+ BMesh *bm;
+ BMLoop *l;
+ BMVert *v_old, *v_new;
+
+ if (!PyArg_ParseTuple(args,
+ "O!O!:face_vert_separate",
+ &BPy_BMFace_Type,
+ &py_face,
+ &BPy_BMVert_Type,
+ &py_vert)) {
+ return NULL;
+ }
+
+ bm = py_face->bm;
+
+ BPY_BM_CHECK_OBJ(py_face);
+ BPY_BM_CHECK_SOURCE_OBJ(bm, "face_vert_separate()", py_vert);
+
+ l = BM_face_vert_share_loop(py_face->f, py_vert->v);
+
+ if (l == NULL) {
+ PyErr_SetString(PyExc_ValueError, "vertex not found in face");
+ return NULL;
+ }
+
+ v_old = l->v;
+ v_new = BM_face_loop_separate(bm, l);
+
+ if (v_new != v_old) {
+ return BPy_BMVert_CreatePyObject(bm, v_new);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
PyDoc_STRVAR(bpy_bm_utils_face_flip_doc,
-".. method:: face_flip(faces)\n"
-"\n"
-" Flip the faces direction.\n"
-"\n"
-" :arg face: Face to flip.\n"
-" :type face: :class:`bmesh.types.BMFace`\n"
-);
+ ".. method:: face_flip(faces)\n"
+ "\n"
+ " Flip the faces direction.\n"
+ "\n"
+ " :arg face: Face to flip.\n"
+ " :type face: :class:`bmesh.types.BMFace`\n");
static PyObject *bpy_bm_utils_face_flip(PyObject *UNUSED(self), BPy_BMFace *value)
{
- if (!BPy_BMFace_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "face_flip(face): BMFace expected, not '%.200s'",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
+ if (!BPy_BMFace_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "face_flip(face): BMFace expected, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
- BPY_BM_CHECK_OBJ(value);
+ BPY_BM_CHECK_OBJ(value);
- BM_face_normal_flip(value->bm, value->f);
+ BM_face_normal_flip(value->bm, value->f);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
-
PyDoc_STRVAR(bpy_bm_utils_loop_separate_doc,
-".. method:: loop_separate(loop)\n"
-"\n"
-" Rip a vertex in a face away and add a new vertex.\n"
-"\n"
-" :arg loop: The loop to separate.\n"
-" :type loop: :class:`bmesh.types.BMLoop`\n"
-" :return vert: The newly created vertex or None on failure.\n"
-" :rtype vert: :class:`bmesh.types.BMVert`\n"
-);
+ ".. method:: loop_separate(loop)\n"
+ "\n"
+ " Rip a vertex in a face away and add a new vertex.\n"
+ "\n"
+ " :arg loop: The loop to separate.\n"
+ " :type loop: :class:`bmesh.types.BMLoop`\n"
+ " :return vert: The newly created vertex or None on failure.\n"
+ " :rtype vert: :class:`bmesh.types.BMVert`\n");
static PyObject *bpy_bm_utils_loop_separate(PyObject *UNUSED(self), BPy_BMLoop *value)
{
- BMesh *bm;
- BMLoop *l;
- BMVert *v_old, *v_new;
-
- if (!BPy_BMLoop_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "loop_separate(loop): BMLoop expected, not '%.200s'",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
-
- BPY_BM_CHECK_OBJ(value);
-
- bm = value->bm;
- l = value->l;
-
- v_old = l->v;
- v_new = BM_face_loop_separate(bm, l);
-
- if (v_new != v_old) {
- return BPy_BMVert_CreatePyObject(bm, v_new);
- }
- else {
- Py_RETURN_NONE;
- }
+ BMesh *bm;
+ BMLoop *l;
+ BMVert *v_old, *v_new;
+
+ if (!BPy_BMLoop_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "loop_separate(loop): BMLoop expected, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+
+ BPY_BM_CHECK_OBJ(value);
+
+ bm = value->bm;
+ l = value->l;
+
+ v_old = l->v;
+ v_new = BM_face_loop_separate(bm, l);
+
+ if (v_new != v_old) {
+ return BPy_BMVert_CreatePyObject(bm, v_new);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
static struct PyMethodDef BPy_BM_utils_methods[] = {
- {"vert_collapse_edge", (PyCFunction)bpy_bm_utils_vert_collapse_edge, METH_VARARGS, bpy_bm_utils_vert_collapse_edge_doc},
- {"vert_collapse_faces", (PyCFunction)bpy_bm_utils_vert_collapse_faces, METH_VARARGS, bpy_bm_utils_vert_collapse_faces_doc},
- {"vert_dissolve", (PyCFunction)bpy_bm_utils_vert_dissolve, METH_VARARGS, bpy_bm_utils_vert_dissolve_doc}, /* could use METH_O */
- {"vert_splice", (PyCFunction)bpy_bm_utils_vert_splice, METH_VARARGS, bpy_bm_utils_vert_splice_doc},
- {"vert_separate", (PyCFunction)bpy_bm_utils_vert_separate, METH_VARARGS, bpy_bm_utils_vert_separate_doc},
- {"edge_split", (PyCFunction)bpy_bm_utils_edge_split, METH_VARARGS, bpy_bm_utils_edge_split_doc},
- {"edge_rotate", (PyCFunction)bpy_bm_utils_edge_rotate, METH_VARARGS, bpy_bm_utils_edge_rotate_doc},
- {"face_split", (PyCFunction)bpy_bm_utils_face_split, METH_VARARGS | METH_KEYWORDS, bpy_bm_utils_face_split_doc},
- {"face_split_edgenet", (PyCFunction)bpy_bm_utils_face_split_edgenet, METH_VARARGS | METH_KEYWORDS, bpy_bm_utils_face_split_edgenet_doc},
- {"face_join", (PyCFunction)bpy_bm_utils_face_join, METH_VARARGS, bpy_bm_utils_face_join_doc},
- {"face_vert_separate", (PyCFunction)bpy_bm_utils_face_vert_separate, METH_VARARGS, bpy_bm_utils_face_vert_separate_doc},
- {"face_flip", (PyCFunction)bpy_bm_utils_face_flip, METH_O, bpy_bm_utils_face_flip_doc},
- {"loop_separate", (PyCFunction)bpy_bm_utils_loop_separate, METH_O, bpy_bm_utils_loop_separate_doc},
- {NULL, NULL, 0, NULL},
+ {"vert_collapse_edge",
+ (PyCFunction)bpy_bm_utils_vert_collapse_edge,
+ METH_VARARGS,
+ bpy_bm_utils_vert_collapse_edge_doc},
+ {"vert_collapse_faces",
+ (PyCFunction)bpy_bm_utils_vert_collapse_faces,
+ METH_VARARGS,
+ bpy_bm_utils_vert_collapse_faces_doc},
+ {"vert_dissolve",
+ (PyCFunction)bpy_bm_utils_vert_dissolve,
+ METH_VARARGS,
+ bpy_bm_utils_vert_dissolve_doc}, /* could use METH_O */
+ {"vert_splice",
+ (PyCFunction)bpy_bm_utils_vert_splice,
+ METH_VARARGS,
+ bpy_bm_utils_vert_splice_doc},
+ {"vert_separate",
+ (PyCFunction)bpy_bm_utils_vert_separate,
+ METH_VARARGS,
+ bpy_bm_utils_vert_separate_doc},
+ {"edge_split",
+ (PyCFunction)bpy_bm_utils_edge_split,
+ METH_VARARGS,
+ bpy_bm_utils_edge_split_doc},
+ {"edge_rotate",
+ (PyCFunction)bpy_bm_utils_edge_rotate,
+ METH_VARARGS,
+ bpy_bm_utils_edge_rotate_doc},
+ {"face_split",
+ (PyCFunction)bpy_bm_utils_face_split,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bm_utils_face_split_doc},
+ {"face_split_edgenet",
+ (PyCFunction)bpy_bm_utils_face_split_edgenet,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_bm_utils_face_split_edgenet_doc},
+ {"face_join", (PyCFunction)bpy_bm_utils_face_join, METH_VARARGS, bpy_bm_utils_face_join_doc},
+ {"face_vert_separate",
+ (PyCFunction)bpy_bm_utils_face_vert_separate,
+ METH_VARARGS,
+ bpy_bm_utils_face_vert_separate_doc},
+ {"face_flip", (PyCFunction)bpy_bm_utils_face_flip, METH_O, bpy_bm_utils_face_flip_doc},
+ {"loop_separate",
+ (PyCFunction)bpy_bm_utils_loop_separate,
+ METH_O,
+ bpy_bm_utils_loop_separate_doc},
+ {NULL, NULL, 0, NULL},
};
-
-PyDoc_STRVAR(BPy_BM_utils_doc,
-"This module provides access to blenders bmesh data structures."
-);
+PyDoc_STRVAR(BPy_BM_utils_doc, "This module provides access to blenders bmesh data structures.");
static struct PyModuleDef BPy_BM_utils_module_def = {
- PyModuleDef_HEAD_INIT,
- "bmesh.utils", /* m_name */
- BPy_BM_utils_doc, /* m_doc */
- 0, /* m_size */
- BPy_BM_utils_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bmesh.utils", /* m_name */
+ BPy_BM_utils_doc, /* m_doc */
+ 0, /* m_size */
+ BPy_BM_utils_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
-
PyObject *BPyInit_bmesh_utils(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPy_BM_utils_module_def);
+ submodule = PyModule_Create(&BPy_BM_utils_module_def);
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/generic/CMakeLists.txt b/source/blender/python/generic/CMakeLists.txt
index ea766d9f8d1..3b4182bc795 100644
--- a/source/blender/python/generic/CMakeLists.txt
+++ b/source/blender/python/generic/CMakeLists.txt
@@ -16,42 +16,42 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- .
- ../../blenkernel
- ../../blenlib
- ../../gpu
- ../../makesdna
- ../../../../intern/guardedalloc
- ../../../../intern/glew-mx
+ .
+ ../../blenkernel
+ ../../blenlib
+ ../../gpu
+ ../../makesdna
+ ../../../../intern/guardedalloc
+ ../../../../intern/glew-mx
)
set(INC_SYS
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
+ ${GLEW_INCLUDE_PATH}
+ ${PYTHON_INCLUDE_DIRS}
)
set(SRC
- bgl.c
- blf_py_api.c
- bpy_internal_import.c
- bpy_threads.c
- idprop_py_api.c
- imbuf_py_api.c
- py_capi_utils.c
-
- bgl.h
- blf_py_api.h
- bpy_internal_import.h
- idprop_py_api.h
- imbuf_py_api.h
- py_capi_utils.h
-
- # header-only
- python_utildefines.h
+ bgl.c
+ blf_py_api.c
+ bpy_internal_import.c
+ bpy_threads.c
+ idprop_py_api.c
+ imbuf_py_api.c
+ py_capi_utils.c
+
+ bgl.h
+ blf_py_api.h
+ bpy_internal_import.h
+ idprop_py_api.h
+ imbuf_py_api.h
+ py_capi_utils.h
+
+ # header-only
+ python_utildefines.h
)
set(LIB
- ${GLEW_LIBRARY}
+ ${GLEW_LIBRARY}
)
add_definitions(${GL_DEFINITIONS})
diff --git a/source/blender/python/generic/bgl.c b/source/blender/python/generic/bgl.c
index c089a2d03c2..02cad742ed9 100644
--- a/source/blender/python/generic/bgl.c
+++ b/source/blender/python/generic/bgl.c
@@ -35,123 +35,121 @@
#include "bgl.h"
-
/* -------------------------------------------------------------------- */
/** \name Local utility defines for wrapping OpenGL
* \{ */
/*@ By golly George! It looks like fancy pants macro time!!! */
-
/* TYPE_str is the string to pass to Py_ArgParse (for the format) */
/* TYPE_var is the name to pass to the GL function */
/* TYPE_ref is the pointer to pass to Py_ArgParse (to store in) */
/* TYPE_def is the C initialization of the variable */
-#define void_str ""
+#define void_str ""
#define void_var(num)
-#define void_ref(num) &bgl_var##num
-#define void_def(num) char bgl_var##num
+#define void_ref(num) &bgl_var##num
+#define void_def(num) char bgl_var##num
#if 0
-#define buffer_str "O!"
-#define buffer_var(number) (bgl_buffer##number)->buf.asvoid
-#define buffer_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define buffer_def(number) Buffer *bgl_buffer##number
+# define buffer_str "O!"
+# define buffer_var(number) (bgl_buffer##number)->buf.asvoid
+# define buffer_ref(number) &BGL_bufferType, &bgl_buffer##number
+# define buffer_def(number) Buffer *bgl_buffer##number
#endif
/* GL Pointer fields, handled by buffer type */
/* GLdoubleP, GLfloatP, GLintP, GLuintP, GLshortP, GLsizeiP, GLcharP */
-#define GLbooleanP_str "O!"
-#define GLbooleanP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLbooleanP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLbooleanP_def(number) Buffer *bgl_buffer##number
+#define GLbooleanP_str "O!"
+#define GLbooleanP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLbooleanP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLbooleanP_def(number) Buffer *bgl_buffer##number
-#define GLbyteP_str "O!"
+#define GLbyteP_str "O!"
#define GLbyteP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLbyteP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLbyteP_def(number) Buffer *bgl_buffer##number
-#define GLubyteP_str "O!"
-#define GLubyteP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLubyteP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLubyteP_def(number) Buffer *bgl_buffer##number
+#define GLubyteP_str "O!"
+#define GLubyteP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLubyteP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLubyteP_def(number) Buffer *bgl_buffer##number
-#define GLintP_str "O!"
-#define GLintP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLintP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLintP_def(number) Buffer *bgl_buffer##number
+#define GLintP_str "O!"
+#define GLintP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLintP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLintP_def(number) Buffer *bgl_buffer##number
-#define GLint64P_str "O!"
-#define GLint64P_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLint64P_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLint64P_def(number) Buffer *bgl_buffer##number
+#define GLint64P_str "O!"
+#define GLint64P_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLint64P_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLint64P_def(number) Buffer *bgl_buffer##number
-#define GLenumP_str "O!"
-#define GLenumP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLenumP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLenumP_def(number) Buffer *bgl_buffer##number
+#define GLenumP_str "O!"
+#define GLenumP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLenumP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLenumP_def(number) Buffer *bgl_buffer##number
-#define GLuintP_str "O!"
+#define GLuintP_str "O!"
#define GLuintP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLuintP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLuintP_def(number) Buffer *bgl_buffer##number
#if 0
-#define GLuint64P_str "O!"
-#define GLuint64P_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLuint64P_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLuint64P_def(number) Buffer *bgl_buffer##number
+# define GLuint64P_str "O!"
+# define GLuint64P_var(number) (bgl_buffer##number)->buf.asvoid
+# define GLuint64P_ref(number) &BGL_bufferType, &bgl_buffer##number
+# define GLuint64P_def(number) Buffer *bgl_buffer##number
#endif
-#define GLshortP_str "O!"
-#define GLshortP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLshortP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLshortP_def(number) Buffer *bgl_buffer##number
+#define GLshortP_str "O!"
+#define GLshortP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLshortP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLshortP_def(number) Buffer *bgl_buffer##number
-#define GLushortP_str "O!"
+#define GLushortP_str "O!"
#define GLushortP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLushortP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLushortP_def(number) Buffer *bgl_buffer##number
-#define GLfloatP_str "O!"
-#define GLfloatP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLfloatP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLfloatP_def(number) Buffer *bgl_buffer##number
+#define GLfloatP_str "O!"
+#define GLfloatP_var(number) (bgl_buffer##number)->buf.asvoid
+#define GLfloatP_ref(number) &BGL_bufferType, &bgl_buffer##number
+#define GLfloatP_def(number) Buffer *bgl_buffer##number
-#define GLdoubleP_str "O!"
+#define GLdoubleP_str "O!"
#define GLdoubleP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLdoubleP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLdoubleP_def(number) Buffer *bgl_buffer##number
#if 0
-#define GLclampfP_str "O!"
-#define GLclampfP_var(number) (bgl_buffer##number)->buf.asvoid
-#define GLclampfP_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define GLclampfP_def(number) Buffer *bgl_buffer##number
+# define GLclampfP_str "O!"
+# define GLclampfP_var(number) (bgl_buffer##number)->buf.asvoid
+# define GLclampfP_ref(number) &BGL_bufferType, &bgl_buffer##number
+# define GLclampfP_def(number) Buffer *bgl_buffer##number
#endif
-#define GLvoidP_str "O&"
+#define GLvoidP_str "O&"
#define GLvoidP_var(number) ((bgl_buffer##number) ? (bgl_buffer##number)->buf.asvoid : NULL)
#define GLvoidP_ref(number) BGL_BufferOrNoneConverter, &bgl_buffer##number
#define GLvoidP_def(number) Buffer *bgl_buffer##number
-#define GLsizeiP_str "O!"
+#define GLsizeiP_str "O!"
#define GLsizeiP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLsizeiP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLsizeiP_def(number) Buffer *bgl_buffer##number
-#define GLcharP_str "O!"
+#define GLcharP_str "O!"
#define GLcharP_var(number) (bgl_buffer##number)->buf.asvoid
#define GLcharP_ref(number) &BGL_bufferType, &bgl_buffer##number
#define GLcharP_def(number) Buffer *bgl_buffer##number
#if 0
-#define buffer_str "O!"
-#define buffer_var(number) (bgl_buffer##number)->buf.asvoid
-#define buffer_ref(number) &BGL_bufferType, &bgl_buffer##number
-#define buffer_def(number) Buffer *bgl_buffer##number
+# define buffer_str "O!"
+# define buffer_var(number) (bgl_buffer##number)->buf.asvoid
+# define buffer_ref(number) &BGL_bufferType, &bgl_buffer##number
+# define buffer_def(number) Buffer *bgl_buffer##number
#endif
/*@The standard GL typedefs are used as prototypes, we can't
@@ -163,274 +161,260 @@
*/
/* typedef unsigned int GLenum; */
-#define GLenum_str "i"
-#define GLenum_var(num) bgl_var##num
-#define GLenum_ref(num) &bgl_var##num
-#define GLenum_def(num) /* unsigned */ int GLenum_var(num)
+#define GLenum_str "i"
+#define GLenum_var(num) bgl_var##num
+#define GLenum_ref(num) &bgl_var##num
+#define GLenum_def(num) /* unsigned */ int GLenum_var(num)
/* typedef unsigned int GLboolean; */
-#define GLboolean_str "b"
-#define GLboolean_var(num) bgl_var##num
-#define GLboolean_ref(num) &bgl_var##num
-#define GLboolean_def(num) /* unsigned */ char GLboolean_var(num)
+#define GLboolean_str "b"
+#define GLboolean_var(num) bgl_var##num
+#define GLboolean_ref(num) &bgl_var##num
+#define GLboolean_def(num) /* unsigned */ char GLboolean_var(num)
/* typedef unsigned int GLbitfield; */
-#define GLbitfield_str "i"
-#define GLbitfield_var(num) bgl_var##num
-#define GLbitfield_ref(num) &bgl_var##num
-#define GLbitfield_def(num) /* unsigned */ int GLbitfield_var(num)
+#define GLbitfield_str "i"
+#define GLbitfield_var(num) bgl_var##num
+#define GLbitfield_ref(num) &bgl_var##num
+#define GLbitfield_def(num) /* unsigned */ int GLbitfield_var(num)
#if 0
/* typedef signed char GLbyte; */
-#define GLbyte_str "b"
-#define GLbyte_var(num) bgl_var##num
-#define GLbyte_ref(num) &bgl_var##num
-#define GLbyte_def(num) signed char GLbyte_var(num)
+# define GLbyte_str "b"
+# define GLbyte_var(num) bgl_var##num
+# define GLbyte_ref(num) &bgl_var##num
+# define GLbyte_def(num) signed char GLbyte_var(num)
#endif
/* typedef short GLshort; */
-#define GLshort_str "h"
-#define GLshort_var(num) bgl_var##num
-#define GLshort_ref(num) &bgl_var##num
-#define GLshort_def(num) short GLshort_var(num)
+#define GLshort_str "h"
+#define GLshort_var(num) bgl_var##num
+#define GLshort_ref(num) &bgl_var##num
+#define GLshort_def(num) short GLshort_var(num)
/* typedef int GLint; */
-#define GLint_str "i"
-#define GLint_var(num) bgl_var##num
-#define GLint_ref(num) &bgl_var##num
-#define GLint_def(num) int GLint_var(num)
+#define GLint_str "i"
+#define GLint_var(num) bgl_var##num
+#define GLint_ref(num) &bgl_var##num
+#define GLint_def(num) int GLint_var(num)
/* typedef int GLsizei; */
-#define GLsizei_str "n"
-#define GLsizei_var(num) bgl_var##num
-#define GLsizei_ref(num) &bgl_var##num
-#define GLsizei_def(num) size_t GLsizei_var(num)
+#define GLsizei_str "n"
+#define GLsizei_var(num) bgl_var##num
+#define GLsizei_ref(num) &bgl_var##num
+#define GLsizei_def(num) size_t GLsizei_var(num)
/* typedef int GLsizeiptr; */
-#define GLsizeiptr_str "n"
-#define GLsizeiptr_var(num) bgl_var##num
-#define GLsizeiptr_ref(num) &bgl_var##num
-#define GLsizeiptr_def(num) size_t GLsizeiptr_var(num)
+#define GLsizeiptr_str "n"
+#define GLsizeiptr_var(num) bgl_var##num
+#define GLsizeiptr_ref(num) &bgl_var##num
+#define GLsizeiptr_def(num) size_t GLsizeiptr_var(num)
/* typedef int GLintptr; */
-#define GLintptr_str "n"
-#define GLintptr_var(num) bgl_var##num
-#define GLintptr_ref(num) &bgl_var##num
-#define GLintptr_def(num) size_t GLintptr_var(num)
+#define GLintptr_str "n"
+#define GLintptr_var(num) bgl_var##num
+#define GLintptr_ref(num) &bgl_var##num
+#define GLintptr_def(num) size_t GLintptr_var(num)
/* typedef unsigned char GLubyte; */
-#define GLubyte_str "B"
-#define GLubyte_var(num) bgl_var##num
-#define GLubyte_ref(num) &bgl_var##num
-#define GLubyte_def(num) /* unsigned */ char GLubyte_var(num)
+#define GLubyte_str "B"
+#define GLubyte_var(num) bgl_var##num
+#define GLubyte_ref(num) &bgl_var##num
+#define GLubyte_def(num) /* unsigned */ char GLubyte_var(num)
#if 0
/* typedef unsigned short GLushort; */
-#define GLushort_str "H"
-#define GLushort_var(num) bgl_var##num
-#define GLushort_ref(num) &bgl_var##num
-#define GLushort_def(num) /* unsigned */ short GLushort_var(num)
+# define GLushort_str "H"
+# define GLushort_var(num) bgl_var##num
+# define GLushort_ref(num) &bgl_var##num
+# define GLushort_def(num) /* unsigned */ short GLushort_var(num)
#endif
/* typedef unsigned int GLuint; */
-#define GLuint_str "I"
-#define GLuint_var(num) bgl_var##num
-#define GLuint_ref(num) &bgl_var##num
-#define GLuint_def(num) /* unsigned */ int GLuint_var(num)
+#define GLuint_str "I"
+#define GLuint_var(num) bgl_var##num
+#define GLuint_ref(num) &bgl_var##num
+#define GLuint_def(num) /* unsigned */ int GLuint_var(num)
/* typedef unsigned int GLuint64; */
#if 0
-#define GLuint64_str "Q"
-#define GLuint64_var(num) bgl_var##num
-#define GLuint64_ref(num) &bgl_var##num
-#define GLuint64_def(num) /* unsigned */ int GLuint64_var(num)
+# define GLuint64_str "Q"
+# define GLuint64_var(num) bgl_var##num
+# define GLuint64_ref(num) &bgl_var##num
+# define GLuint64_def(num) /* unsigned */ int GLuint64_var(num)
#endif
/* typedef unsigned int GLsync; */
#if 0
-#define GLsync_str "I"
-#define GLsync_var(num) bgl_var##num
-#define GLsync_ref(num) &bgl_var##num
-#define GLsync_def(num) /* unsigned */ int GLsync_var(num)
+# define GLsync_str "I"
+# define GLsync_var(num) bgl_var##num
+# define GLsync_ref(num) &bgl_var##num
+# define GLsync_def(num) /* unsigned */ int GLsync_var(num)
#endif
/* typedef float GLfloat; */
-#define GLfloat_str "f"
-#define GLfloat_var(num) bgl_var##num
-#define GLfloat_ref(num) &bgl_var##num
-#define GLfloat_def(num) float GLfloat_var(num)
+#define GLfloat_str "f"
+#define GLfloat_var(num) bgl_var##num
+#define GLfloat_ref(num) &bgl_var##num
+#define GLfloat_def(num) float GLfloat_var(num)
/* typedef char *GLstring; */
-#define GLstring_str "s"
+#define GLstring_str "s"
#define GLstring_var(number) bgl_var##number
#define GLstring_ref(number) &bgl_var##number
#define GLstring_def(number) char *GLstring_var(number)
/* typedef float GLclampf; */
#if 0
-#define GLclampf_str "f"
-#define GLclampf_var(num) bgl_var##num
-#define GLclampf_ref(num) &bgl_var##num
-#define GLclampf_def(num) float GLclampf_var(num)
+# define GLclampf_str "f"
+# define GLclampf_var(num) bgl_var##num
+# define GLclampf_ref(num) &bgl_var##num
+# define GLclampf_def(num) float GLclampf_var(num)
#endif
/* typedef double GLdouble; */
-#define GLdouble_str "d"
-#define GLdouble_var(num) bgl_var##num
-#define GLdouble_ref(num) &bgl_var##num
-#define GLdouble_def(num) double GLdouble_var(num)
+#define GLdouble_str "d"
+#define GLdouble_var(num) bgl_var##num
+#define GLdouble_ref(num) &bgl_var##num
+#define GLdouble_def(num) double GLdouble_var(num)
/* typedef double GLclampd; */
#if 0
-#define GLclampd_str "d"
-#define GLclampd_var(num) bgl_var##num
-#define GLclampd_ref(num) &bgl_var##num
-#define GLclampd_def(num) double GLclampd_var(num)
+# define GLclampd_str "d"
+# define GLclampd_var(num) bgl_var##num
+# define GLclampd_ref(num) &bgl_var##num
+# define GLclampd_def(num) double GLclampd_var(num)
#endif
-#define _arg_def1(a1) \
- a1##_def(1)
+#define _arg_def1(a1) a1##_def(1)
#define _arg_def2(a1, a2) \
- _arg_def1(a1); a2##_def(2)
+ _arg_def1(a1); \
+ a2##_def(2)
#define _arg_def3(a1, a2, a3) \
- _arg_def2(a1, a2); a3##_def(3)
+ _arg_def2(a1, a2); \
+ a3##_def(3)
#define _arg_def4(a1, a2, a3, a4) \
- _arg_def3(a1, a2, a3); a4##_def(4)
+ _arg_def3(a1, a2, a3); \
+ a4##_def(4)
#define _arg_def5(a1, a2, a3, a4, a5) \
- _arg_def4(a1, a2, a3, a4); a5##_def(5)
+ _arg_def4(a1, a2, a3, a4); \
+ a5##_def(5)
#define _arg_def6(a1, a2, a3, a4, a5, a6) \
- _arg_def5(a1, a2, a3, a4, a5); a6##_def(6)
+ _arg_def5(a1, a2, a3, a4, a5); \
+ a6##_def(6)
#define _arg_def7(a1, a2, a3, a4, a5, a6, a7) \
- _arg_def6(a1, a2, a3, a4, a5, a6); a7##_def(7)
+ _arg_def6(a1, a2, a3, a4, a5, a6); \
+ a7##_def(7)
#define _arg_def8(a1, a2, a3, a4, a5, a6, a7, a8) \
- _arg_def7(a1, a2, a3, a4, a5, a6, a7); a8##_def(8)
+ _arg_def7(a1, a2, a3, a4, a5, a6, a7); \
+ a8##_def(8)
#define _arg_def9(a1, a2, a3, a4, a5, a6, a7, a8, a9) \
- _arg_def8(a1, a2, a3, a4, a5, a6, a7, a8); a9##_def(9)
+ _arg_def8(a1, a2, a3, a4, a5, a6, a7, a8); \
+ a9##_def(9)
#define _arg_def10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
- _arg_def9(a1, a2, a3, a4, a5, a6, a7, a8, a9); a10##_def(10)
+ _arg_def9(a1, a2, a3, a4, a5, a6, a7, a8, a9); \
+ a10##_def(10)
#define _arg_def11(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
- _arg_def10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); a11##_def(11)
-#define arg_def(...) VA_NARGS_CALL_OVERLOAD(_arg_def, __VA_ARGS__)
-
-#define _arg_var1(a1) \
- a1##_var(1)
-#define _arg_var2(a1, a2) \
- _arg_var1(a1), a2##_var(2)
-#define _arg_var3(a1, a2, a3) \
- _arg_var2(a1, a2), a3##_var(3)
-#define _arg_var4(a1, a2, a3, a4) \
- _arg_var3(a1, a2, a3), a4##_var(4)
-#define _arg_var5(a1, a2, a3, a4, a5) \
- _arg_var4(a1, a2, a3, a4), a5##_var(5)
-#define _arg_var6(a1, a2, a3, a4, a5, a6) \
- _arg_var5(a1, a2, a3, a4, a5), a6##_var(6)
-#define _arg_var7(a1, a2, a3, a4, a5, a6, a7) \
- _arg_var6(a1, a2, a3, a4, a5, a6), a7##_var(7)
+ _arg_def10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); \
+ a11##_def(11)
+#define arg_def(...) VA_NARGS_CALL_OVERLOAD(_arg_def, __VA_ARGS__)
+
+#define _arg_var1(a1) a1##_var(1)
+#define _arg_var2(a1, a2) _arg_var1(a1), a2##_var(2)
+#define _arg_var3(a1, a2, a3) _arg_var2(a1, a2), a3##_var(3)
+#define _arg_var4(a1, a2, a3, a4) _arg_var3(a1, a2, a3), a4##_var(4)
+#define _arg_var5(a1, a2, a3, a4, a5) _arg_var4(a1, a2, a3, a4), a5##_var(5)
+#define _arg_var6(a1, a2, a3, a4, a5, a6) _arg_var5(a1, a2, a3, a4, a5), a6##_var(6)
+#define _arg_var7(a1, a2, a3, a4, a5, a6, a7) _arg_var6(a1, a2, a3, a4, a5, a6), a7##_var(7)
#define _arg_var8(a1, a2, a3, a4, a5, a6, a7, a8) \
- _arg_var7(a1, a2, a3, a4, a5, a6, a7), a8##_var(8)
+ _arg_var7(a1, a2, a3, a4, a5, a6, a7), a8##_var(8)
#define _arg_var9(a1, a2, a3, a4, a5, a6, a7, a8, a9) \
- _arg_var8(a1, a2, a3, a4, a5, a6, a7, a8), a9##_var(9)
+ _arg_var8(a1, a2, a3, a4, a5, a6, a7, a8), a9##_var(9)
#define _arg_var10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
- _arg_var9(a1, a2, a3, a4, a5, a6, a7, a8, a9), a10##_var(10)
+ _arg_var9(a1, a2, a3, a4, a5, a6, a7, a8, a9), a10##_var(10)
#define _arg_var11(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
- _arg_var10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10), a11##_var(11)
-#define arg_var(...) VA_NARGS_CALL_OVERLOAD(_arg_var, __VA_ARGS__)
-
-#define _arg_ref1(a1) \
- a1##_ref(1)
-#define _arg_ref2(a1, a2) \
- _arg_ref1(a1), a2##_ref(2)
-#define _arg_ref3(a1, a2, a3) \
- _arg_ref2(a1, a2), a3##_ref(3)
-#define _arg_ref4(a1, a2, a3, a4) \
- _arg_ref3(a1, a2, a3), a4##_ref(4)
-#define _arg_ref5(a1, a2, a3, a4, a5) \
- _arg_ref4(a1, a2, a3, a4), a5##_ref(5)
-#define _arg_ref6(a1, a2, a3, a4, a5, a6) \
- _arg_ref5(a1, a2, a3, a4, a5), a6##_ref(6)
-#define _arg_ref7(a1, a2, a3, a4, a5, a6, a7) \
- _arg_ref6(a1, a2, a3, a4, a5, a6), a7##_ref(7)
+ _arg_var10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10), a11##_var(11)
+#define arg_var(...) VA_NARGS_CALL_OVERLOAD(_arg_var, __VA_ARGS__)
+
+#define _arg_ref1(a1) a1##_ref(1)
+#define _arg_ref2(a1, a2) _arg_ref1(a1), a2##_ref(2)
+#define _arg_ref3(a1, a2, a3) _arg_ref2(a1, a2), a3##_ref(3)
+#define _arg_ref4(a1, a2, a3, a4) _arg_ref3(a1, a2, a3), a4##_ref(4)
+#define _arg_ref5(a1, a2, a3, a4, a5) _arg_ref4(a1, a2, a3, a4), a5##_ref(5)
+#define _arg_ref6(a1, a2, a3, a4, a5, a6) _arg_ref5(a1, a2, a3, a4, a5), a6##_ref(6)
+#define _arg_ref7(a1, a2, a3, a4, a5, a6, a7) _arg_ref6(a1, a2, a3, a4, a5, a6), a7##_ref(7)
#define _arg_ref8(a1, a2, a3, a4, a5, a6, a7, a8) \
- _arg_ref7(a1, a2, a3, a4, a5, a6, a7), a8##_ref(8)
+ _arg_ref7(a1, a2, a3, a4, a5, a6, a7), a8##_ref(8)
#define _arg_ref9(a1, a2, a3, a4, a5, a6, a7, a8, a9) \
- _arg_ref8(a1, a2, a3, a4, a5, a6, a7, a8), a9##_ref(9)
+ _arg_ref8(a1, a2, a3, a4, a5, a6, a7, a8), a9##_ref(9)
#define _arg_ref10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
- _arg_ref9(a1, a2, a3, a4, a5, a6, a7, a8, a9), a10##_ref(10)
+ _arg_ref9(a1, a2, a3, a4, a5, a6, a7, a8, a9), a10##_ref(10)
#define _arg_ref11(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
- _arg_ref10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10), a11##_ref(11)
-#define arg_ref(...) VA_NARGS_CALL_OVERLOAD(_arg_ref, __VA_ARGS__)
-
-#define _arg_str1(a1) \
- a1##_str
-#define _arg_str2(a1, a2) \
- _arg_str1(a1) a2##_str
-#define _arg_str3(a1, a2, a3) \
- _arg_str2(a1, a2) a3##_str
-#define _arg_str4(a1, a2, a3, a4) \
- _arg_str3(a1, a2, a3) a4##_str
-#define _arg_str5(a1, a2, a3, a4, a5) \
- _arg_str4(a1, a2, a3, a4) a5##_str
-#define _arg_str6(a1, a2, a3, a4, a5, a6) \
- _arg_str5(a1, a2, a3, a4, a5) a6##_str
-#define _arg_str7(a1, a2, a3, a4, a5, a6, a7) \
- _arg_str6(a1, a2, a3, a4, a5, a6) a7##_str
-#define _arg_str8(a1, a2, a3, a4, a5, a6, a7, a8) \
- _arg_str7(a1, a2, a3, a4, a5, a6, a7) a8##_str
+ _arg_ref10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10), a11##_ref(11)
+#define arg_ref(...) VA_NARGS_CALL_OVERLOAD(_arg_ref, __VA_ARGS__)
+
+#define _arg_str1(a1) a1##_str
+#define _arg_str2(a1, a2) _arg_str1(a1) a2##_str
+#define _arg_str3(a1, a2, a3) _arg_str2(a1, a2) a3##_str
+#define _arg_str4(a1, a2, a3, a4) _arg_str3(a1, a2, a3) a4##_str
+#define _arg_str5(a1, a2, a3, a4, a5) _arg_str4(a1, a2, a3, a4) a5##_str
+#define _arg_str6(a1, a2, a3, a4, a5, a6) _arg_str5(a1, a2, a3, a4, a5) a6##_str
+#define _arg_str7(a1, a2, a3, a4, a5, a6, a7) _arg_str6(a1, a2, a3, a4, a5, a6) a7##_str
+#define _arg_str8(a1, a2, a3, a4, a5, a6, a7, a8) _arg_str7(a1, a2, a3, a4, a5, a6, a7) a8##_str
#define _arg_str9(a1, a2, a3, a4, a5, a6, a7, a8, a9) \
- _arg_str8(a1, a2, a3, a4, a5, a6, a7, a8) a9##_str
+ _arg_str8(a1, a2, a3, a4, a5, a6, a7, a8) a9##_str
#define _arg_str10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) \
- _arg_str9(a1, a2, a3, a4, a5, a6, a7, a8, a9) a10##_str
+ _arg_str9(a1, a2, a3, a4, a5, a6, a7, a8, a9) a10##_str
#define _arg_str11(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) \
- _arg_str10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) a11##_str
-#define arg_str(...) VA_NARGS_CALL_OVERLOAD(_arg_str, __VA_ARGS__)
+ _arg_str10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) a11##_str
+#define arg_str(...) VA_NARGS_CALL_OVERLOAD(_arg_str, __VA_ARGS__)
#define ret_def_void
#define ret_set_void
-#define ret_ret_void return Py_INCREF(Py_None), Py_None
+#define ret_ret_void return Py_INCREF(Py_None), Py_None
-#define ret_def_GLint int ret_int
-#define ret_set_GLint ret_int =
-#define ret_ret_GLint return PyLong_FromLong(ret_int)
+#define ret_def_GLint int ret_int
+#define ret_set_GLint ret_int =
+#define ret_ret_GLint return PyLong_FromLong(ret_int)
-#define ret_def_GLuint unsigned int ret_uint
-#define ret_set_GLuint ret_uint =
-#define ret_ret_GLuint return PyLong_FromLong((long) ret_uint)
+#define ret_def_GLuint unsigned int ret_uint
+#define ret_set_GLuint ret_uint =
+#define ret_ret_GLuint return PyLong_FromLong((long)ret_uint)
#if 0
-#define ret_def_GLsizei size_t ret_size_t
-#define ret_set_GLsizei ret_size_t =
-#define ret_ret_GLsizei return PyLong_FromSsize_t(ret_size_t)
+# define ret_def_GLsizei size_t ret_size_t
+# define ret_set_GLsizei ret_size_t =
+# define ret_ret_GLsizei return PyLong_FromSsize_t(ret_size_t)
#endif
#if 0
-#define ret_def_GLsync unsigned int ret_sync
-#define ret_set_GLsync ret_sync =
-#define ret_ret_GLsync return PyLong_FromLong((long) ret_sync)
+# define ret_def_GLsync unsigned int ret_sync
+# define ret_set_GLsync ret_sync =
+# define ret_ret_GLsync return PyLong_FromLong((long)ret_sync)
#endif
-#define ret_def_GLenum unsigned int ret_uint
-#define ret_set_GLenum ret_uint =
-#define ret_ret_GLenum return PyLong_FromLong((long) ret_uint)
+#define ret_def_GLenum unsigned int ret_uint
+#define ret_set_GLenum ret_uint =
+#define ret_ret_GLenum return PyLong_FromLong((long)ret_uint)
#define ret_def_GLboolean unsigned char ret_bool
#define ret_set_GLboolean ret_bool =
-#define ret_ret_GLboolean return PyLong_FromLong((long) ret_bool)
+#define ret_ret_GLboolean return PyLong_FromLong((long)ret_bool)
-#define ret_def_GLstring const unsigned char *ret_str
-#define ret_set_GLstring ret_str =
+#define ret_def_GLstring const unsigned char *ret_str
+#define ret_set_GLstring ret_str =
-#define ret_ret_GLstring \
- if (ret_str) { \
- return PyUnicode_FromString((const char *)ret_str); \
- } \
- else { \
- PyErr_SetString(PyExc_AttributeError, "could not get opengl string"); \
- return NULL; \
- } \
+#define ret_ret_GLstring \
+ if (ret_str) { \
+ return PyUnicode_FromString((const char *)ret_str); \
+ } \
+ else { \
+ PyErr_SetString(PyExc_AttributeError, "could not get opengl string"); \
+ return NULL; \
+ }
/** \} */
-
/* -------------------------------------------------------------------- */
/* Forward Declarations */
@@ -447,94 +431,88 @@ static int Buffer_ass_slice(Buffer *self, int begin, int end, PyObject *seq);
static PyObject *Buffer_subscript(Buffer *self, PyObject *item);
static int Buffer_ass_subscript(Buffer *self, PyObject *item, PyObject *value);
-
/* -------------------------------------------------------------------- */
/** \name Utility Functions
* \{ */
-
int BGL_typeSize(int type)
{
- switch (type) {
- case GL_BYTE:
- return sizeof(char);
- case GL_SHORT:
- return sizeof(short);
- case GL_INT:
- return sizeof(int);
- case GL_FLOAT:
- return sizeof(float);
- case GL_DOUBLE:
- return sizeof(double);
- }
- return -1;
+ switch (type) {
+ case GL_BYTE:
+ return sizeof(char);
+ case GL_SHORT:
+ return sizeof(short);
+ case GL_INT:
+ return sizeof(int);
+ case GL_FLOAT:
+ return sizeof(float);
+ case GL_DOUBLE:
+ return sizeof(double);
+ }
+ return -1;
}
static int gl_buffer_type_from_py_buffer(Py_buffer *pybuffer)
{
- const char format = PyC_StructFmt_type_from_str(pybuffer->format);
- Py_ssize_t itemsize = pybuffer->itemsize;
-
- if (PyC_StructFmt_type_is_float_any(format)) {
- if (itemsize == 4) {
- return GL_FLOAT;
- }
- if (itemsize == 8) {
- return GL_DOUBLE;
- }
- }
- if (PyC_StructFmt_type_is_byte(format) ||
- PyC_StructFmt_type_is_int_any(format))
- {
- if (itemsize == 1) {
- return GL_BYTE;
- }
- if (itemsize == 2) {
- return GL_SHORT;
- }
- if (itemsize == 4) {
- return GL_INT;
- }
- }
-
- return -1; /* UNKNOWN */
+ const char format = PyC_StructFmt_type_from_str(pybuffer->format);
+ Py_ssize_t itemsize = pybuffer->itemsize;
+
+ if (PyC_StructFmt_type_is_float_any(format)) {
+ if (itemsize == 4) {
+ return GL_FLOAT;
+ }
+ if (itemsize == 8) {
+ return GL_DOUBLE;
+ }
+ }
+ if (PyC_StructFmt_type_is_byte(format) || PyC_StructFmt_type_is_int_any(format)) {
+ if (itemsize == 1) {
+ return GL_BYTE;
+ }
+ if (itemsize == 2) {
+ return GL_SHORT;
+ }
+ if (itemsize == 4) {
+ return GL_INT;
+ }
+ }
+
+ return -1; /* UNKNOWN */
}
static bool compare_dimensions(int ndim, int *dim1, Py_ssize_t *dim2)
{
- for (int i = 0; i < ndim; i++) {
- if (dim1[i] != dim2[i]) {
- return false;
- }
- }
- return true;
+ for (int i = 0; i < ndim; i++) {
+ if (dim1[i] != dim2[i]) {
+ return false;
+ }
+ }
+ return true;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Buffer API
* \{ */
static PySequenceMethods Buffer_SeqMethods = {
- (lenfunc) Buffer_len, /*sq_length */
- (binaryfunc) NULL, /*sq_concat */
- (ssizeargfunc) NULL, /*sq_repeat */
- (ssizeargfunc) Buffer_item, /*sq_item */
- (ssizessizeargfunc) NULL, /*sq_slice, deprecated, handled in Buffer_item */
- (ssizeobjargproc) Buffer_ass_item, /*sq_ass_item */
- (ssizessizeobjargproc) NULL, /*sq_ass_slice, deprecated handled in Buffer_ass_item */
- (objobjproc) NULL, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)Buffer_len, /*sq_length */
+ (binaryfunc)NULL, /*sq_concat */
+ (ssizeargfunc)NULL, /*sq_repeat */
+ (ssizeargfunc)Buffer_item, /*sq_item */
+ (ssizessizeargfunc)NULL, /*sq_slice, deprecated, handled in Buffer_item */
+ (ssizeobjargproc)Buffer_ass_item, /*sq_ass_item */
+ (ssizessizeobjargproc)NULL, /*sq_ass_slice, deprecated handled in Buffer_ass_item */
+ (objobjproc)NULL, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
-
static PyMappingMethods Buffer_AsMapping = {
- (lenfunc)Buffer_len,
- (binaryfunc)Buffer_subscript,
- (objobjargproc)Buffer_ass_subscript,
+ (lenfunc)Buffer_len,
+ (binaryfunc)Buffer_subscript,
+ (objobjargproc)Buffer_ass_subscript,
};
static void Buffer_dealloc(Buffer *self);
@@ -542,145 +520,142 @@ static PyObject *Buffer_repr(Buffer *self);
static PyObject *Buffer_to_list(Buffer *self)
{
- int i, len = self->dimensions[0];
- PyObject *list = PyList_New(len);
+ int i, len = self->dimensions[0];
+ PyObject *list = PyList_New(len);
- for (i = 0; i < len; i++) {
- PyList_SET_ITEM(list, i, Buffer_item(self, i));
- }
+ for (i = 0; i < len; i++) {
+ PyList_SET_ITEM(list, i, Buffer_item(self, i));
+ }
- return list;
+ return list;
}
static PyObject *Buffer_to_list_recursive(Buffer *self)
{
- PyObject *list;
-
- if (self->ndimensions > 1) {
- int i, len = self->dimensions[0];
- list = PyList_New(len);
-
- for (i = 0; i < len; i++) {
- Buffer *sub = (Buffer *)Buffer_item(self, i);
- PyList_SET_ITEM(list, i, Buffer_to_list_recursive(sub));
- Py_DECREF(sub);
- }
- }
- else {
- list = Buffer_to_list(self);
- }
-
- return list;
+ PyObject *list;
+
+ if (self->ndimensions > 1) {
+ int i, len = self->dimensions[0];
+ list = PyList_New(len);
+
+ for (i = 0; i < len; i++) {
+ Buffer *sub = (Buffer *)Buffer_item(self, i);
+ PyList_SET_ITEM(list, i, Buffer_to_list_recursive(sub));
+ Py_DECREF(sub);
+ }
+ }
+ else {
+ list = Buffer_to_list(self);
+ }
+
+ return list;
}
static PyObject *Buffer_dimensions(Buffer *self, void *UNUSED(arg))
{
- PyObject *list = PyList_New(self->ndimensions);
- int i;
+ PyObject *list = PyList_New(self->ndimensions);
+ int i;
- for (i = 0; i < self->ndimensions; i++) {
- PyList_SET_ITEM(list, i, PyLong_FromLong(self->dimensions[i]));
- }
+ for (i = 0; i < self->ndimensions; i++) {
+ PyList_SET_ITEM(list, i, PyLong_FromLong(self->dimensions[i]));
+ }
- return list;
+ return list;
}
static PyMethodDef Buffer_methods[] = {
- {"to_list", (PyCFunction)Buffer_to_list_recursive, METH_NOARGS,
- "return the buffer as a list"},
- {NULL, NULL, 0, NULL},
+ {"to_list", (PyCFunction)Buffer_to_list_recursive, METH_NOARGS, "return the buffer as a list"},
+ {NULL, NULL, 0, NULL},
};
static PyGetSetDef Buffer_getseters[] = {
- {(char *)"dimensions", (getter)Buffer_dimensions, NULL, NULL, NULL},
- {NULL, NULL, NULL, NULL, NULL},
+ {(char *)"dimensions", (getter)Buffer_dimensions, NULL, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL},
};
-
PyTypeObject BGL_bufferType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bgl.Buffer", /*tp_name */
- sizeof(Buffer), /*tp_basicsize */
- 0, /*tp_itemsize */
- (destructor)Buffer_dealloc, /*tp_dealloc */
- (printfunc)NULL, /*tp_print */
- NULL, /*tp_getattr */
- NULL, /*tp_setattr */
- NULL, /*tp_compare */
- (reprfunc) Buffer_repr, /*tp_repr */
- NULL, /*tp_as_number */
- &Buffer_SeqMethods, /*tp_as_sequence */
- &Buffer_AsMapping, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
- /*** Attribute descriptor and subclassing stuff ***/
- Buffer_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- Buffer_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /*tp_base*/
- NULL, /*tp_dict*/
- NULL, /*tp_descr_get*/
- NULL, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- NULL, /*tp_init*/
- NULL, /*tp_alloc*/
- Buffer_new, /*tp_new*/
- NULL, /*tp_free*/
- NULL, /*tp_is_gc*/
- NULL, /*tp_bases*/
- NULL, /*tp_mro*/
- NULL, /*tp_cache*/
- NULL, /*tp_subclasses*/
- NULL, /*tp_weaklist*/
- NULL, /*tp_del*/
+ PyVarObject_HEAD_INIT(NULL, 0) "bgl.Buffer", /*tp_name */
+ sizeof(Buffer), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ (destructor)Buffer_dealloc, /*tp_dealloc */
+ (printfunc)NULL, /*tp_print */
+ NULL, /*tp_getattr */
+ NULL, /*tp_setattr */
+ NULL, /*tp_compare */
+ (reprfunc)Buffer_repr, /*tp_repr */
+ NULL, /*tp_as_number */
+ &Buffer_SeqMethods, /*tp_as_sequence */
+ &Buffer_AsMapping, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+ /*** Attribute descriptor and subclassing stuff ***/
+ Buffer_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ Buffer_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /*tp_base*/
+ NULL, /*tp_dict*/
+ NULL, /*tp_descr_get*/
+ NULL, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ NULL, /*tp_init*/
+ NULL, /*tp_alloc*/
+ Buffer_new, /*tp_new*/
+ NULL, /*tp_free*/
+ NULL, /*tp_is_gc*/
+ NULL, /*tp_bases*/
+ NULL, /*tp_mro*/
+ NULL, /*tp_cache*/
+ NULL, /*tp_subclasses*/
+ NULL, /*tp_weaklist*/
+ NULL, /*tp_del*/
};
-
-static Buffer *BGL_MakeBuffer_FromData(PyObject *parent, int type, int ndimensions, int *dimensions, void *buf)
+static Buffer *BGL_MakeBuffer_FromData(
+ PyObject *parent, int type, int ndimensions, int *dimensions, void *buf)
{
- Buffer *buffer = (Buffer *)PyObject_NEW(Buffer, &BGL_bufferType);
+ Buffer *buffer = (Buffer *)PyObject_NEW(Buffer, &BGL_bufferType);
- Py_XINCREF(parent);
- buffer->parent = parent;
- buffer->ndimensions = ndimensions;
- buffer->dimensions = MEM_mallocN(ndimensions * sizeof(int), "Buffer dimensions");
- memcpy(buffer->dimensions, dimensions, ndimensions * sizeof(int));
- buffer->type = type;
- buffer->buf.asvoid = buf;
+ Py_XINCREF(parent);
+ buffer->parent = parent;
+ buffer->ndimensions = ndimensions;
+ buffer->dimensions = MEM_mallocN(ndimensions * sizeof(int), "Buffer dimensions");
+ memcpy(buffer->dimensions, dimensions, ndimensions * sizeof(int));
+ buffer->type = type;
+ buffer->buf.asvoid = buf;
- return buffer;
+ return buffer;
}
/**
@@ -692,741 +667,771 @@ static Buffer *BGL_MakeBuffer_FromData(PyObject *parent, int type, int ndimensio
*/
Buffer *BGL_MakeBuffer(int type, int ndimensions, int *dimensions, void *initbuffer)
{
- Buffer *buffer;
- void *buf = NULL;
- int i, size = BGL_typeSize(type);
+ Buffer *buffer;
+ void *buf = NULL;
+ int i, size = BGL_typeSize(type);
- for (i = 0; i < ndimensions; i++) {
- size *= dimensions[i];
- }
+ for (i = 0; i < ndimensions; i++) {
+ size *= dimensions[i];
+ }
- buf = MEM_mallocN(size, "Buffer buffer");
+ buf = MEM_mallocN(size, "Buffer buffer");
- buffer = BGL_MakeBuffer_FromData(NULL, type, ndimensions, dimensions, buf);
+ buffer = BGL_MakeBuffer_FromData(NULL, type, ndimensions, dimensions, buf);
- if (initbuffer) {
- memcpy(buffer->buf.asvoid, initbuffer, size);
- }
- else {
- memset(buffer->buf.asvoid, 0, size);
- }
- return buffer;
+ if (initbuffer) {
+ memcpy(buffer->buf.asvoid, initbuffer, size);
+ }
+ else {
+ memset(buffer->buf.asvoid, 0, size);
+ }
+ return buffer;
}
/* Custom converter function so we can support a buffer or NULL. */
static int BGL_BufferOrNoneConverter(PyObject *object, Buffer **buffer)
{
- if (object == Py_None) {
- *buffer = NULL;
- return 1;
- }
- else if (PyObject_TypeCheck(object, &BGL_bufferType)) {
- *buffer = (Buffer *)object;
- return 1;
- }
- else {
- PyErr_SetString(PyExc_TypeError, "expected a bgl.Buffer or None");
- return 0;
- }
+ if (object == Py_None) {
+ *buffer = NULL;
+ return 1;
+ }
+ else if (PyObject_TypeCheck(object, &BGL_bufferType)) {
+ *buffer = (Buffer *)object;
+ return 1;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "expected a bgl.Buffer or None");
+ return 0;
+ }
}
-#define MAX_DIMENSIONS 256
+#define MAX_DIMENSIONS 256
static PyObject *Buffer_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- PyObject *length_ob = NULL, *init = NULL;
- Buffer *buffer = NULL;
- int dimensions[MAX_DIMENSIONS];
-
- int type;
- Py_ssize_t i, ndimensions = 0;
-
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "bgl.Buffer(): takes no keyword args");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "iO|O: bgl.Buffer", &type, &length_ob, &init)) {
- return NULL;
- }
- if (!ELEM(type, GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE)) {
- PyErr_SetString(PyExc_AttributeError,
- "invalid first argument type, should be one of "
- "GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT or GL_DOUBLE");
- return NULL;
- }
-
- if (PyLong_Check(length_ob)) {
- ndimensions = 1;
- if (((dimensions[0] = PyLong_AsLong(length_ob)) < 1)) {
- PyErr_SetString(PyExc_AttributeError,
- "dimensions must be between 1 and "STRINGIFY(MAX_DIMENSIONS));
- return NULL;
- }
- }
- else if (PySequence_Check(length_ob)) {
- ndimensions = PySequence_Size(length_ob);
- if (ndimensions > MAX_DIMENSIONS) {
- PyErr_SetString(PyExc_AttributeError,
- "too many dimensions, max is "STRINGIFY(MAX_DIMENSIONS));
- return NULL;
- }
- else if (ndimensions < 1) {
- PyErr_SetString(PyExc_AttributeError,
- "sequence must have at least one dimension");
- return NULL;
- }
- for (i = 0; i < ndimensions; i++) {
- PyObject *ob = PySequence_GetItem(length_ob, i);
-
- if (!PyLong_Check(ob)) {
- dimensions[i] = 1;
- }
- else {
- dimensions[i] = PyLong_AsLong(ob);
- }
- Py_DECREF(ob);
-
- if (dimensions[i] < 1) {
- PyErr_SetString(PyExc_AttributeError,
- "dimensions must be between 1 and "STRINGIFY(MAX_DIMENSIONS));
- return NULL;
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "invalid second argument argument expected a sequence "
- "or an int, not a %.200s", Py_TYPE(length_ob)->tp_name);
- return NULL;
- }
-
- if (init && PyObject_CheckBuffer(init)) {
- Py_buffer pybuffer;
-
- if (PyObject_GetBuffer(init, &pybuffer, PyBUF_ND | PyBUF_FORMAT) == -1) {
- /* PyObject_GetBuffer raise a PyExc_BufferError */
- return NULL;
- }
-
- if (type != gl_buffer_type_from_py_buffer(&pybuffer)) {
- PyErr_Format(PyExc_TypeError,
- "`GL_TYPE` and `typestr` of object with buffer interface do not match. '%s'", pybuffer.format);
- }
- else if (ndimensions != pybuffer.ndim ||
- !compare_dimensions(ndimensions, dimensions, pybuffer.shape))
- {
- PyErr_Format(PyExc_TypeError, "array size does not match");
- }
- else {
- buffer = BGL_MakeBuffer_FromData(init, type, pybuffer.ndim, dimensions, pybuffer.buf);
- }
-
- PyBuffer_Release(&pybuffer);
- }
- else {
- buffer = BGL_MakeBuffer(type, ndimensions, dimensions, NULL);
- if (init && Buffer_ass_slice(buffer, 0, dimensions[0], init)) {
- Py_DECREF(buffer);
- return NULL;
- }
- }
-
- return (PyObject *)buffer;
+ PyObject *length_ob = NULL, *init = NULL;
+ Buffer *buffer = NULL;
+ int dimensions[MAX_DIMENSIONS];
+
+ int type;
+ Py_ssize_t i, ndimensions = 0;
+
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError, "bgl.Buffer(): takes no keyword args");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "iO|O: bgl.Buffer", &type, &length_ob, &init)) {
+ return NULL;
+ }
+ if (!ELEM(type, GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT, GL_DOUBLE)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "invalid first argument type, should be one of "
+ "GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT or GL_DOUBLE");
+ return NULL;
+ }
+
+ if (PyLong_Check(length_ob)) {
+ ndimensions = 1;
+ if (((dimensions[0] = PyLong_AsLong(length_ob)) < 1)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "dimensions must be between 1 and " STRINGIFY(MAX_DIMENSIONS));
+ return NULL;
+ }
+ }
+ else if (PySequence_Check(length_ob)) {
+ ndimensions = PySequence_Size(length_ob);
+ if (ndimensions > MAX_DIMENSIONS) {
+ PyErr_SetString(PyExc_AttributeError,
+ "too many dimensions, max is " STRINGIFY(MAX_DIMENSIONS));
+ return NULL;
+ }
+ else if (ndimensions < 1) {
+ PyErr_SetString(PyExc_AttributeError, "sequence must have at least one dimension");
+ return NULL;
+ }
+ for (i = 0; i < ndimensions; i++) {
+ PyObject *ob = PySequence_GetItem(length_ob, i);
+
+ if (!PyLong_Check(ob)) {
+ dimensions[i] = 1;
+ }
+ else {
+ dimensions[i] = PyLong_AsLong(ob);
+ }
+ Py_DECREF(ob);
+
+ if (dimensions[i] < 1) {
+ PyErr_SetString(PyExc_AttributeError,
+ "dimensions must be between 1 and " STRINGIFY(MAX_DIMENSIONS));
+ return NULL;
+ }
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "invalid second argument argument expected a sequence "
+ "or an int, not a %.200s",
+ Py_TYPE(length_ob)->tp_name);
+ return NULL;
+ }
+
+ if (init && PyObject_CheckBuffer(init)) {
+ Py_buffer pybuffer;
+
+ if (PyObject_GetBuffer(init, &pybuffer, PyBUF_ND | PyBUF_FORMAT) == -1) {
+ /* PyObject_GetBuffer raise a PyExc_BufferError */
+ return NULL;
+ }
+
+ if (type != gl_buffer_type_from_py_buffer(&pybuffer)) {
+ PyErr_Format(PyExc_TypeError,
+ "`GL_TYPE` and `typestr` of object with buffer interface do not match. '%s'",
+ pybuffer.format);
+ }
+ else if (ndimensions != pybuffer.ndim ||
+ !compare_dimensions(ndimensions, dimensions, pybuffer.shape)) {
+ PyErr_Format(PyExc_TypeError, "array size does not match");
+ }
+ else {
+ buffer = BGL_MakeBuffer_FromData(init, type, pybuffer.ndim, dimensions, pybuffer.buf);
+ }
+
+ PyBuffer_Release(&pybuffer);
+ }
+ else {
+ buffer = BGL_MakeBuffer(type, ndimensions, dimensions, NULL);
+ if (init && Buffer_ass_slice(buffer, 0, dimensions[0], init)) {
+ Py_DECREF(buffer);
+ return NULL;
+ }
+ }
+
+ return (PyObject *)buffer;
}
/* Buffer sequence methods */
static int Buffer_len(Buffer *self)
{
- return self->dimensions[0];
+ return self->dimensions[0];
}
static PyObject *Buffer_item(Buffer *self, int i)
{
- if (i >= self->dimensions[0] || i < 0) {
- PyErr_SetString(PyExc_IndexError, "array index out of range");
- return NULL;
- }
-
- if (self->ndimensions == 1) {
- switch (self->type) {
- case GL_BYTE: return Py_BuildValue("b", self->buf.asbyte[i]);
- case GL_SHORT: return Py_BuildValue("h", self->buf.asshort[i]);
- case GL_INT: return Py_BuildValue("i", self->buf.asint[i]);
- case GL_FLOAT: return PyFloat_FromDouble(self->buf.asfloat[i]);
- case GL_DOUBLE: return Py_BuildValue("d", self->buf.asdouble[i]);
- }
- }
- else {
- int j, offset = i * BGL_typeSize(self->type);
-
- for (j = 1; j < self->ndimensions; j++) {
- offset *= self->dimensions[j];
- }
-
- return (PyObject *)BGL_MakeBuffer_FromData(
- (PyObject *)self, self->type,
- self->ndimensions - 1,
- self->dimensions + 1,
- self->buf.asbyte + offset);
- }
-
- return NULL;
+ if (i >= self->dimensions[0] || i < 0) {
+ PyErr_SetString(PyExc_IndexError, "array index out of range");
+ return NULL;
+ }
+
+ if (self->ndimensions == 1) {
+ switch (self->type) {
+ case GL_BYTE:
+ return Py_BuildValue("b", self->buf.asbyte[i]);
+ case GL_SHORT:
+ return Py_BuildValue("h", self->buf.asshort[i]);
+ case GL_INT:
+ return Py_BuildValue("i", self->buf.asint[i]);
+ case GL_FLOAT:
+ return PyFloat_FromDouble(self->buf.asfloat[i]);
+ case GL_DOUBLE:
+ return Py_BuildValue("d", self->buf.asdouble[i]);
+ }
+ }
+ else {
+ int j, offset = i * BGL_typeSize(self->type);
+
+ for (j = 1; j < self->ndimensions; j++) {
+ offset *= self->dimensions[j];
+ }
+
+ return (PyObject *)BGL_MakeBuffer_FromData((PyObject *)self,
+ self->type,
+ self->ndimensions - 1,
+ self->dimensions + 1,
+ self->buf.asbyte + offset);
+ }
+
+ return NULL;
}
static PyObject *Buffer_slice(Buffer *self, int begin, int end)
{
- PyObject *list;
- int count;
-
- if (begin < 0) {
- begin = 0;
- }
- if (end > self->dimensions[0]) {
- end = self->dimensions[0];
- }
- if (begin > end) {
- begin = end;
- }
-
- list = PyList_New(end - begin);
-
- for (count = begin; count < end; count++) {
- PyList_SET_ITEM(list, count - begin, Buffer_item(self, count));
- }
- return list;
+ PyObject *list;
+ int count;
+
+ if (begin < 0) {
+ begin = 0;
+ }
+ if (end > self->dimensions[0]) {
+ end = self->dimensions[0];
+ }
+ if (begin > end) {
+ begin = end;
+ }
+
+ list = PyList_New(end - begin);
+
+ for (count = begin; count < end; count++) {
+ PyList_SET_ITEM(list, count - begin, Buffer_item(self, count));
+ }
+ return list;
}
static int Buffer_ass_item(Buffer *self, int i, PyObject *v)
{
- if (i >= self->dimensions[0] || i < 0) {
- PyErr_SetString(PyExc_IndexError,
- "array assignment index out of range");
- return -1;
- }
-
- if (self->ndimensions != 1) {
- Buffer *row = (Buffer *)Buffer_item(self, i);
-
- if (row) {
- int ret = Buffer_ass_slice(row, 0, self->dimensions[1], v);
- Py_DECREF(row);
- return ret;
- }
- else {
- return -1;
- }
- }
-
- switch (self->type) {
- case GL_BYTE: return PyArg_Parse(v, "b:Expected ints", &self->buf.asbyte[i]) ? 0 : -1;
- case GL_SHORT: return PyArg_Parse(v, "h:Expected ints", &self->buf.asshort[i]) ? 0 : -1;
- case GL_INT: return PyArg_Parse(v, "i:Expected ints", &self->buf.asint[i]) ? 0 : -1;
- case GL_FLOAT: return PyArg_Parse(v, "f:Expected floats", &self->buf.asfloat[i]) ? 0 : -1;
- case GL_DOUBLE: return PyArg_Parse(v, "d:Expected floats", &self->buf.asdouble[i]) ? 0 : -1;
- default: return 0; /* should never happen */
- }
+ if (i >= self->dimensions[0] || i < 0) {
+ PyErr_SetString(PyExc_IndexError, "array assignment index out of range");
+ return -1;
+ }
+
+ if (self->ndimensions != 1) {
+ Buffer *row = (Buffer *)Buffer_item(self, i);
+
+ if (row) {
+ int ret = Buffer_ass_slice(row, 0, self->dimensions[1], v);
+ Py_DECREF(row);
+ return ret;
+ }
+ else {
+ return -1;
+ }
+ }
+
+ switch (self->type) {
+ case GL_BYTE:
+ return PyArg_Parse(v, "b:Expected ints", &self->buf.asbyte[i]) ? 0 : -1;
+ case GL_SHORT:
+ return PyArg_Parse(v, "h:Expected ints", &self->buf.asshort[i]) ? 0 : -1;
+ case GL_INT:
+ return PyArg_Parse(v, "i:Expected ints", &self->buf.asint[i]) ? 0 : -1;
+ case GL_FLOAT:
+ return PyArg_Parse(v, "f:Expected floats", &self->buf.asfloat[i]) ? 0 : -1;
+ case GL_DOUBLE:
+ return PyArg_Parse(v, "d:Expected floats", &self->buf.asdouble[i]) ? 0 : -1;
+ default:
+ return 0; /* should never happen */
+ }
}
static int Buffer_ass_slice(Buffer *self, int begin, int end, PyObject *seq)
{
- PyObject *item;
- int count, err = 0;
-
- if (begin < 0) {
- begin = 0;
- }
- if (end > self->dimensions[0]) {
- end = self->dimensions[0];
- }
- if (begin > end) {
- begin = end;
- }
-
- if (!PySequence_Check(seq)) {
- PyErr_Format(PyExc_TypeError,
- "buffer[:] = value, invalid assignment. "
- "Expected a sequence, not an %.200s type",
- Py_TYPE(seq)->tp_name);
- return -1;
- }
-
- /* re-use count var */
- if ((count = PySequence_Size(seq)) != (end - begin)) {
- PyErr_Format(PyExc_TypeError,
- "buffer[:] = value, size mismatch in assignment. "
- "Expected: %d (given: %d)", count, end - begin);
- return -1;
- }
-
- for (count = begin; count < end; count++) {
- item = PySequence_GetItem(seq, count - begin);
- if (item) {
- err = Buffer_ass_item(self, count, item);
- Py_DECREF(item);
- }
- else {
- err = -1;
- }
- if (err) {
- break;
- }
- }
- return err;
+ PyObject *item;
+ int count, err = 0;
+
+ if (begin < 0) {
+ begin = 0;
+ }
+ if (end > self->dimensions[0]) {
+ end = self->dimensions[0];
+ }
+ if (begin > end) {
+ begin = end;
+ }
+
+ if (!PySequence_Check(seq)) {
+ PyErr_Format(PyExc_TypeError,
+ "buffer[:] = value, invalid assignment. "
+ "Expected a sequence, not an %.200s type",
+ Py_TYPE(seq)->tp_name);
+ return -1;
+ }
+
+ /* re-use count var */
+ if ((count = PySequence_Size(seq)) != (end - begin)) {
+ PyErr_Format(PyExc_TypeError,
+ "buffer[:] = value, size mismatch in assignment. "
+ "Expected: %d (given: %d)",
+ count,
+ end - begin);
+ return -1;
+ }
+
+ for (count = begin; count < end; count++) {
+ item = PySequence_GetItem(seq, count - begin);
+ if (item) {
+ err = Buffer_ass_item(self, count, item);
+ Py_DECREF(item);
+ }
+ else {
+ err = -1;
+ }
+ if (err) {
+ break;
+ }
+ }
+ return err;
}
static PyObject *Buffer_subscript(Buffer *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 += self->dimensions[0];
- }
- return Buffer_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->dimensions[0], &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Buffer_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with vectors");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "buffer indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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 += self->dimensions[0];
+ }
+ return Buffer_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->dimensions[0], &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Buffer_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "buffer indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static int Buffer_ass_subscript(Buffer *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 += self->dimensions[0];
- }
- return Buffer_ass_item(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->dimensions[0], &start, &stop, &step, &slicelength) < 0) {
- return -1;
- }
-
- if (step == 1) {
- return Buffer_ass_slice(self, start, stop, value);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with vectors");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "buffer indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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 += self->dimensions[0];
+ }
+ return Buffer_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->dimensions[0], &start, &stop, &step, &slicelength) < 0) {
+ return -1;
+ }
+
+ if (step == 1) {
+ return Buffer_ass_slice(self, start, stop, value);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "buffer indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
-
static void Buffer_dealloc(Buffer *self)
{
- if (self->parent) {
- Py_DECREF(self->parent);
- }
- else {
- MEM_freeN(self->buf.asvoid);
- }
+ if (self->parent) {
+ Py_DECREF(self->parent);
+ }
+ else {
+ MEM_freeN(self->buf.asvoid);
+ }
- MEM_freeN(self->dimensions);
+ MEM_freeN(self->dimensions);
- PyObject_DEL(self);
+ PyObject_DEL(self);
}
-
static PyObject *Buffer_repr(Buffer *self)
{
- PyObject *list = Buffer_to_list_recursive(self);
- PyObject *repr;
- const char *typestr;
-
- switch (self->type) {
- case GL_BYTE: typestr = "GL_BYTE"; break;
- case GL_SHORT: typestr = "GL_SHORT"; break;
- case GL_INT: typestr = "GL_INT"; break;
- case GL_FLOAT: typestr = "GL_FLOAT"; break;
- case GL_DOUBLE: typestr = "GL_DOUBLE"; break;
- default: typestr = "UNKNOWN"; break;
- }
-
- repr = PyUnicode_FromFormat("Buffer(%s, %R)", typestr, list);
- Py_DECREF(list);
-
- return repr;
+ PyObject *list = Buffer_to_list_recursive(self);
+ PyObject *repr;
+ const char *typestr;
+
+ switch (self->type) {
+ case GL_BYTE:
+ typestr = "GL_BYTE";
+ break;
+ case GL_SHORT:
+ typestr = "GL_SHORT";
+ break;
+ case GL_INT:
+ typestr = "GL_INT";
+ break;
+ case GL_FLOAT:
+ typestr = "GL_FLOAT";
+ break;
+ case GL_DOUBLE:
+ typestr = "GL_DOUBLE";
+ break;
+ default:
+ typestr = "UNKNOWN";
+ break;
+ }
+
+ repr = PyUnicode_FromFormat("Buffer(%s, %R)", typestr, list);
+ Py_DECREF(list);
+
+ return repr;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name OpenGL API Wrapping
* \{ */
-#define BGL_Wrap(funcname, ret, arg_list) \
-static PyObject *Method_##funcname (PyObject *UNUSED(self), PyObject *args) \
-{ \
- arg_def arg_list; \
- ret_def_##ret; \
- if (!PyArg_ParseTuple(args, arg_str arg_list, arg_ref arg_list)) { \
- return NULL; \
- } \
- ret_set_##ret gl##funcname (arg_var arg_list); \
- ret_ret_##ret; \
-}
+#define BGL_Wrap(funcname, ret, arg_list) \
+ static PyObject *Method_##funcname(PyObject *UNUSED(self), PyObject *args) \
+ { \
+ arg_def arg_list; \
+ ret_def_##ret; \
+ if (!PyArg_ParseTuple(args, arg_str arg_list, arg_ref arg_list)) { \
+ return NULL; \
+ } \
+ ret_set_##ret gl##funcname(arg_var arg_list); \
+ ret_ret_##ret; \
+ }
/* GL_VERSION_1_0 */
-BGL_Wrap(BlendFunc, void, (GLenum, GLenum));
-BGL_Wrap(Clear, void, (GLbitfield));
-BGL_Wrap(ClearColor, void, (GLfloat, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(ClearDepth, void, (GLdouble));
-BGL_Wrap(ClearStencil, void, (GLint));
-BGL_Wrap(ColorMask, void, (GLboolean, GLboolean, GLboolean, GLboolean));
-BGL_Wrap(CullFace, void, (GLenum));
-BGL_Wrap(DepthFunc, void, (GLenum));
-BGL_Wrap(DepthMask, void, (GLboolean));
-BGL_Wrap(DepthRange, void, (GLdouble, GLdouble));
-BGL_Wrap(Disable, void, (GLenum));
-BGL_Wrap(DrawBuffer, void, (GLenum));
-BGL_Wrap(Enable, void, (GLenum));
-BGL_Wrap(Finish, void, (void));
-BGL_Wrap(Flush, void, (void));
-BGL_Wrap(FrontFace, void, (GLenum));
-BGL_Wrap(GetBooleanv, void, (GLenum, GLbooleanP));
-BGL_Wrap(GetDoublev, void, (GLenum, GLdoubleP));
-BGL_Wrap(GetError, GLenum, (void));
-BGL_Wrap(GetFloatv, void, (GLenum, GLfloatP));
-BGL_Wrap(GetIntegerv, void, (GLenum, GLintP));
-BGL_Wrap(GetString, GLstring, (GLenum));
-BGL_Wrap(GetTexImage, void, (GLenum, GLint, GLenum, GLenum, GLvoidP));
-BGL_Wrap(GetTexLevelParameterfv, void, (GLenum, GLint, GLenum, GLfloatP));
-BGL_Wrap(GetTexLevelParameteriv, void, (GLenum, GLint, GLenum, GLintP));
-BGL_Wrap(GetTexParameterfv, void, (GLenum, GLenum, GLfloatP));
-BGL_Wrap(GetTexParameteriv, void, (GLenum, GLenum, GLintP));
-BGL_Wrap(Hint, void, (GLenum, GLenum));
-BGL_Wrap(IsEnabled, GLboolean, (GLenum));
-BGL_Wrap(LineWidth, void, (GLfloat));
-BGL_Wrap(LogicOp, void, (GLenum));
-BGL_Wrap(PixelStoref, void, (GLenum, GLfloat));
-BGL_Wrap(PixelStorei, void, (GLenum, GLint));
-BGL_Wrap(PointSize, void, (GLfloat));
-BGL_Wrap(PolygonMode, void, (GLenum, GLenum));
-BGL_Wrap(ReadBuffer, void, (GLenum));
-BGL_Wrap(ReadPixels, void, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
-BGL_Wrap(Scissor, void, (GLint, GLint, GLsizei, GLsizei));
-BGL_Wrap(StencilFunc, void, (GLenum, GLint, GLuint));
-BGL_Wrap(StencilMask, void, (GLuint));
-BGL_Wrap(StencilOp, void, (GLenum, GLenum, GLenum));
-BGL_Wrap(TexImage1D, void, (GLenum, GLint, GLint, GLsizei, GLint, GLenum, GLenum, GLvoidP));
-BGL_Wrap(TexImage2D, void, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP));
-BGL_Wrap(TexParameterf, void, (GLenum, GLenum, GLfloat));
-BGL_Wrap(TexParameterfv, void, (GLenum, GLenum, GLfloatP));
-BGL_Wrap(TexParameteri, void, (GLenum, GLenum, GLint));
-BGL_Wrap(TexParameteriv, void, (GLenum, GLenum, GLintP));
-BGL_Wrap(Viewport, void, (GLint, GLint, GLsizei, GLsizei));
-
+BGL_Wrap(BlendFunc, void, (GLenum, GLenum));
+BGL_Wrap(Clear, void, (GLbitfield));
+BGL_Wrap(ClearColor, void, (GLfloat, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(ClearDepth, void, (GLdouble));
+BGL_Wrap(ClearStencil, void, (GLint));
+BGL_Wrap(ColorMask, void, (GLboolean, GLboolean, GLboolean, GLboolean));
+BGL_Wrap(CullFace, void, (GLenum));
+BGL_Wrap(DepthFunc, void, (GLenum));
+BGL_Wrap(DepthMask, void, (GLboolean));
+BGL_Wrap(DepthRange, void, (GLdouble, GLdouble));
+BGL_Wrap(Disable, void, (GLenum));
+BGL_Wrap(DrawBuffer, void, (GLenum));
+BGL_Wrap(Enable, void, (GLenum));
+BGL_Wrap(Finish, void, (void));
+BGL_Wrap(Flush, void, (void));
+BGL_Wrap(FrontFace, void, (GLenum));
+BGL_Wrap(GetBooleanv, void, (GLenum, GLbooleanP));
+BGL_Wrap(GetDoublev, void, (GLenum, GLdoubleP));
+BGL_Wrap(GetError, GLenum, (void));
+BGL_Wrap(GetFloatv, void, (GLenum, GLfloatP));
+BGL_Wrap(GetIntegerv, void, (GLenum, GLintP));
+BGL_Wrap(GetString, GLstring, (GLenum));
+BGL_Wrap(GetTexImage, void, (GLenum, GLint, GLenum, GLenum, GLvoidP));
+BGL_Wrap(GetTexLevelParameterfv, void, (GLenum, GLint, GLenum, GLfloatP));
+BGL_Wrap(GetTexLevelParameteriv, void, (GLenum, GLint, GLenum, GLintP));
+BGL_Wrap(GetTexParameterfv, void, (GLenum, GLenum, GLfloatP));
+BGL_Wrap(GetTexParameteriv, void, (GLenum, GLenum, GLintP));
+BGL_Wrap(Hint, void, (GLenum, GLenum));
+BGL_Wrap(IsEnabled, GLboolean, (GLenum));
+BGL_Wrap(LineWidth, void, (GLfloat));
+BGL_Wrap(LogicOp, void, (GLenum));
+BGL_Wrap(PixelStoref, void, (GLenum, GLfloat));
+BGL_Wrap(PixelStorei, void, (GLenum, GLint));
+BGL_Wrap(PointSize, void, (GLfloat));
+BGL_Wrap(PolygonMode, void, (GLenum, GLenum));
+BGL_Wrap(ReadBuffer, void, (GLenum));
+BGL_Wrap(ReadPixels, void, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
+BGL_Wrap(Scissor, void, (GLint, GLint, GLsizei, GLsizei));
+BGL_Wrap(StencilFunc, void, (GLenum, GLint, GLuint));
+BGL_Wrap(StencilMask, void, (GLuint));
+BGL_Wrap(StencilOp, void, (GLenum, GLenum, GLenum));
+BGL_Wrap(TexImage1D, void, (GLenum, GLint, GLint, GLsizei, GLint, GLenum, GLenum, GLvoidP));
+BGL_Wrap(TexImage2D,
+ void,
+ (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP));
+BGL_Wrap(TexParameterf, void, (GLenum, GLenum, GLfloat));
+BGL_Wrap(TexParameterfv, void, (GLenum, GLenum, GLfloatP));
+BGL_Wrap(TexParameteri, void, (GLenum, GLenum, GLint));
+BGL_Wrap(TexParameteriv, void, (GLenum, GLenum, GLintP));
+BGL_Wrap(Viewport, void, (GLint, GLint, GLsizei, GLsizei));
/* GL_VERSION_1_1 */
-BGL_Wrap(BindTexture, void, (GLenum, GLuint));
-BGL_Wrap(CopyTexImage1D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint));
-BGL_Wrap(CopyTexImage2D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint));
-BGL_Wrap(CopyTexSubImage1D, void, (GLenum, GLint, GLint, GLint, GLint, GLsizei));
-BGL_Wrap(CopyTexSubImage2D, void, (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei));
-BGL_Wrap(DeleteTextures, void, (GLsizei, GLuintP));
-BGL_Wrap(DrawArrays, void, (GLenum, GLint, GLsizei));
-BGL_Wrap(DrawElements, void, (GLenum, GLsizei, GLenum, GLvoidP));
-BGL_Wrap(GenTextures, void, (GLsizei, GLuintP));
-BGL_Wrap(IsTexture, GLboolean, (GLuint));
-BGL_Wrap(PolygonOffset, void, (GLfloat, GLfloat));
-BGL_Wrap(TexSubImage1D, void, (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, GLvoidP));
-BGL_Wrap(TexSubImage2D, void, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
-
+BGL_Wrap(BindTexture, void, (GLenum, GLuint));
+BGL_Wrap(CopyTexImage1D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint));
+BGL_Wrap(CopyTexImage2D, void, (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint));
+BGL_Wrap(CopyTexSubImage1D, void, (GLenum, GLint, GLint, GLint, GLint, GLsizei));
+BGL_Wrap(CopyTexSubImage2D, void, (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei));
+BGL_Wrap(DeleteTextures, void, (GLsizei, GLuintP));
+BGL_Wrap(DrawArrays, void, (GLenum, GLint, GLsizei));
+BGL_Wrap(DrawElements, void, (GLenum, GLsizei, GLenum, GLvoidP));
+BGL_Wrap(GenTextures, void, (GLsizei, GLuintP));
+BGL_Wrap(IsTexture, GLboolean, (GLuint));
+BGL_Wrap(PolygonOffset, void, (GLfloat, GLfloat));
+BGL_Wrap(TexSubImage1D, void, (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, GLvoidP));
+BGL_Wrap(TexSubImage2D,
+ void,
+ (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
/* GL_VERSION_1_2 */
-BGL_Wrap(CopyTexSubImage3D, void, (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei));
-BGL_Wrap(DrawRangeElements, void, (GLenum, GLuint, GLuint, GLsizei, GLenum, GLvoidP));
-BGL_Wrap(TexImage3D, void, (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP));
-BGL_Wrap(TexSubImage3D, void, (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
-
+BGL_Wrap(CopyTexSubImage3D,
+ void,
+ (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei));
+BGL_Wrap(DrawRangeElements, void, (GLenum, GLuint, GLuint, GLsizei, GLenum, GLvoidP));
+BGL_Wrap(TexImage3D,
+ void,
+ (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, GLvoidP));
+BGL_Wrap(TexSubImage3D,
+ void,
+ (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, GLvoidP));
/* GL_VERSION_1_3 */
-BGL_Wrap(ActiveTexture, void, (GLenum));
-BGL_Wrap(CompressedTexImage1D, void, (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, GLvoidP));
-BGL_Wrap(CompressedTexImage2D, void, (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, GLvoidP));
-BGL_Wrap(CompressedTexImage3D, void, (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, GLvoidP));
-BGL_Wrap(CompressedTexSubImage1D, void, (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, GLvoidP));
-BGL_Wrap(CompressedTexSubImage2D, void, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, GLvoidP));
-BGL_Wrap(CompressedTexSubImage3D, void, (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, GLvoidP));
-BGL_Wrap(GetCompressedTexImage, void, (GLenum, GLint, GLvoidP));
-BGL_Wrap(SampleCoverage, void, (GLfloat, GLboolean));
-
+BGL_Wrap(ActiveTexture, void, (GLenum));
+BGL_Wrap(CompressedTexImage1D, void, (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, GLvoidP));
+BGL_Wrap(CompressedTexImage2D,
+ void,
+ (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, GLvoidP));
+BGL_Wrap(CompressedTexImage3D,
+ void,
+ (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, GLvoidP));
+BGL_Wrap(CompressedTexSubImage1D, void, (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, GLvoidP));
+BGL_Wrap(CompressedTexSubImage2D,
+ void,
+ (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, GLvoidP));
+BGL_Wrap(
+ CompressedTexSubImage3D,
+ void,
+ (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, GLvoidP));
+BGL_Wrap(GetCompressedTexImage, void, (GLenum, GLint, GLvoidP));
+BGL_Wrap(SampleCoverage, void, (GLfloat, GLboolean));
/* GL_VERSION_1_4 */
-BGL_Wrap(BlendColor, void, (GLfloat, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(BlendEquation, void, (GLenum));
-
+BGL_Wrap(BlendColor, void, (GLfloat, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(BlendEquation, void, (GLenum));
/* GL_VERSION_1_5 */
-BGL_Wrap(BeginQuery, void, (GLenum, GLuint));
-BGL_Wrap(BindBuffer, void, (GLenum, GLuint));
-BGL_Wrap(BufferData, void, (GLenum, GLsizeiptr, GLvoidP, GLenum));
-BGL_Wrap(BufferSubData, void, (GLenum, GLintptr, GLsizeiptr, GLvoidP));
-BGL_Wrap(DeleteBuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(DeleteQueries, void, (GLsizei, GLuintP));
-BGL_Wrap(EndQuery, void, (GLenum));
-BGL_Wrap(GenBuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(GenQueries, void, (GLsizei, GLuintP));
-BGL_Wrap(GetBufferParameteriv, void, (GLenum, GLenum, GLintP));
-BGL_Wrap(GetBufferPointerv, void, (GLenum, GLenum, GLvoidP));
-BGL_Wrap(GetBufferSubData, void, (GLenum, GLintptr, GLsizeiptr, GLvoidP));
-BGL_Wrap(GetQueryObjectiv, void, (GLuint, GLenum, GLintP));
-BGL_Wrap(GetQueryObjectuiv, void, (GLuint, GLenum, GLuintP));
-BGL_Wrap(GetQueryiv, void, (GLenum, GLenum, GLintP));
-BGL_Wrap(IsBuffer, GLboolean, (GLuint));
-BGL_Wrap(IsQuery, GLboolean, (GLuint));
-BGL_Wrap(MapBuffer, void, (GLenum, GLenum));
-BGL_Wrap(UnmapBuffer, GLboolean, (GLenum));
-
+BGL_Wrap(BeginQuery, void, (GLenum, GLuint));
+BGL_Wrap(BindBuffer, void, (GLenum, GLuint));
+BGL_Wrap(BufferData, void, (GLenum, GLsizeiptr, GLvoidP, GLenum));
+BGL_Wrap(BufferSubData, void, (GLenum, GLintptr, GLsizeiptr, GLvoidP));
+BGL_Wrap(DeleteBuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(DeleteQueries, void, (GLsizei, GLuintP));
+BGL_Wrap(EndQuery, void, (GLenum));
+BGL_Wrap(GenBuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(GenQueries, void, (GLsizei, GLuintP));
+BGL_Wrap(GetBufferParameteriv, void, (GLenum, GLenum, GLintP));
+BGL_Wrap(GetBufferPointerv, void, (GLenum, GLenum, GLvoidP));
+BGL_Wrap(GetBufferSubData, void, (GLenum, GLintptr, GLsizeiptr, GLvoidP));
+BGL_Wrap(GetQueryObjectiv, void, (GLuint, GLenum, GLintP));
+BGL_Wrap(GetQueryObjectuiv, void, (GLuint, GLenum, GLuintP));
+BGL_Wrap(GetQueryiv, void, (GLenum, GLenum, GLintP));
+BGL_Wrap(IsBuffer, GLboolean, (GLuint));
+BGL_Wrap(IsQuery, GLboolean, (GLuint));
+BGL_Wrap(MapBuffer, void, (GLenum, GLenum));
+BGL_Wrap(UnmapBuffer, GLboolean, (GLenum));
/* GL_VERSION_2_0 */
-BGL_Wrap(AttachShader, void, (GLuint, GLuint));
-BGL_Wrap(BindAttribLocation, void, (GLuint, GLuint, GLstring));
-BGL_Wrap(BlendEquationSeparate, void, (GLenum, GLenum));
-BGL_Wrap(CompileShader, void, (GLuint));
-BGL_Wrap(CreateProgram, GLuint, (void));
-BGL_Wrap(CreateShader, GLuint, (GLenum));
-BGL_Wrap(DeleteProgram, void, (GLuint));
-BGL_Wrap(DeleteShader, void, (GLuint));
-BGL_Wrap(DetachShader, void, (GLuint, GLuint));
-BGL_Wrap(DisableVertexAttribArray, void, (GLuint));
-BGL_Wrap(DrawBuffers, void, (GLsizei, GLenumP));
-BGL_Wrap(EnableVertexAttribArray, void, (GLuint));
-BGL_Wrap(GetActiveAttrib, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLintP, GLenumP, GLcharP));
-BGL_Wrap(GetActiveUniform, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLintP, GLenumP, GLcharP));
-BGL_Wrap(GetAttachedShaders, void, (GLuint, GLsizei, GLsizeiP, GLuintP));
-BGL_Wrap(GetAttribLocation, GLint, (GLuint, GLstring));
-BGL_Wrap(GetProgramInfoLog, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
-BGL_Wrap(GetProgramiv, void, (GLuint, GLenum, GLintP));
-BGL_Wrap(GetShaderInfoLog, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
-BGL_Wrap(GetShaderSource, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
-BGL_Wrap(GetShaderiv, void, (GLuint, GLenum, GLintP));
-BGL_Wrap(GetUniformLocation, GLint, (GLuint, GLstring));
-BGL_Wrap(GetUniformfv, void, (GLuint, GLint, GLfloatP));
-BGL_Wrap(GetUniformiv, void, (GLuint, GLint, GLintP));
-BGL_Wrap(GetVertexAttribPointerv, void, (GLuint, GLenum, GLvoidP));
-BGL_Wrap(GetVertexAttribdv, void, (GLuint, GLenum, GLdoubleP));
-BGL_Wrap(GetVertexAttribfv, void, (GLuint, GLenum, GLfloatP));
-BGL_Wrap(GetVertexAttribiv, void, (GLuint, GLenum, GLintP));
-BGL_Wrap(IsProgram, GLboolean, (GLuint));
-BGL_Wrap(IsShader, GLboolean, (GLuint));
-BGL_Wrap(LinkProgram, void, (GLuint));
-BGL_Wrap(StencilFuncSeparate, void, (GLenum, GLenum, GLint, GLuint));
-BGL_Wrap(StencilMaskSeparate, void, (GLenum, GLuint));
-BGL_Wrap(StencilOpSeparate, void, (GLenum, GLenum, GLenum, GLenum));
-BGL_Wrap(Uniform1f, void, (GLint, GLfloat));
-BGL_Wrap(Uniform1fv, void, (GLint, GLsizei, GLfloatP));
-BGL_Wrap(Uniform1i, void, (GLint, GLint));
-BGL_Wrap(Uniform1iv, void, (GLint, GLsizei, GLintP));
-BGL_Wrap(Uniform2f, void, (GLint, GLfloat, GLfloat));
-BGL_Wrap(Uniform2fv, void, (GLint, GLsizei, GLfloatP));
-BGL_Wrap(Uniform2i, void, (GLint, GLint, GLint));
-BGL_Wrap(Uniform2iv, void, (GLint, GLsizei, GLintP));
-BGL_Wrap(Uniform3f, void, (GLint, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(Uniform3fv, void, (GLint, GLsizei, GLfloatP));
-BGL_Wrap(Uniform3i, void, (GLint, GLint, GLint, GLint));
-BGL_Wrap(Uniform3iv, void, (GLint, GLsizei, GLintP));
-BGL_Wrap(Uniform4f, void, (GLint, GLfloat, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(Uniform4fv, void, (GLint, GLsizei, GLfloatP));
-BGL_Wrap(Uniform4i, void, (GLint, GLint, GLint, GLint, GLint));
-BGL_Wrap(Uniform4iv, void, (GLint, GLsizei, GLintP));
-BGL_Wrap(UniformMatrix2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UseProgram, void, (GLuint));
-BGL_Wrap(ValidateProgram, void, (GLuint));
-BGL_Wrap(VertexAttrib1d, void, (GLuint, GLdouble));
-BGL_Wrap(VertexAttrib1dv, void, (GLuint, GLdoubleP));
-BGL_Wrap(VertexAttrib1f, void, (GLuint, GLfloat));
-BGL_Wrap(VertexAttrib1fv, void, (GLuint, GLfloatP));
-BGL_Wrap(VertexAttrib1s, void, (GLuint, GLshort));
-BGL_Wrap(VertexAttrib1sv, void, (GLuint, GLshortP));
-BGL_Wrap(VertexAttrib2d, void, (GLuint, GLdouble, GLdouble));
-BGL_Wrap(VertexAttrib2dv, void, (GLuint, GLdoubleP));
-BGL_Wrap(VertexAttrib2f, void, (GLuint, GLfloat, GLfloat));
-BGL_Wrap(VertexAttrib2fv, void, (GLuint, GLfloatP));
-BGL_Wrap(VertexAttrib2s, void, (GLuint, GLshort, GLshort));
-BGL_Wrap(VertexAttrib2sv, void, (GLuint, GLshortP));
-BGL_Wrap(VertexAttrib3d, void, (GLuint, GLdouble, GLdouble, GLdouble));
-BGL_Wrap(VertexAttrib3dv, void, (GLuint, GLdoubleP));
-BGL_Wrap(VertexAttrib3f, void, (GLuint, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(VertexAttrib3fv, void, (GLuint, GLfloatP));
-BGL_Wrap(VertexAttrib3s, void, (GLuint, GLshort, GLshort, GLshort));
-BGL_Wrap(VertexAttrib3sv, void, (GLuint, GLshortP));
-BGL_Wrap(VertexAttrib4Nbv, void, (GLuint, GLbyteP));
-BGL_Wrap(VertexAttrib4Niv, void, (GLuint, GLintP));
-BGL_Wrap(VertexAttrib4Nsv, void, (GLuint, GLshortP));
-BGL_Wrap(VertexAttrib4Nub, void, (GLuint, GLubyte, GLubyte, GLubyte, GLubyte));
-BGL_Wrap(VertexAttrib4Nubv, void, (GLuint, GLubyteP));
-BGL_Wrap(VertexAttrib4Nuiv, void, (GLuint, GLuintP));
-BGL_Wrap(VertexAttrib4Nusv, void, (GLuint, GLushortP));
-BGL_Wrap(VertexAttrib4bv, void, (GLuint, GLbyteP));
-BGL_Wrap(VertexAttrib4d, void, (GLuint, GLdouble, GLdouble, GLdouble, GLdouble));
-BGL_Wrap(VertexAttrib4dv, void, (GLuint, GLdoubleP));
-BGL_Wrap(VertexAttrib4f, void, (GLuint, GLfloat, GLfloat, GLfloat, GLfloat));
-BGL_Wrap(VertexAttrib4fv, void, (GLuint, GLfloatP));
-BGL_Wrap(VertexAttrib4iv, void, (GLuint, GLintP));
-BGL_Wrap(VertexAttrib4s, void, (GLuint, GLshort, GLshort, GLshort, GLshort));
-BGL_Wrap(VertexAttrib4sv, void, (GLuint, GLshortP));
-BGL_Wrap(VertexAttrib4ubv, void, (GLuint, GLubyteP));
-BGL_Wrap(VertexAttrib4uiv, void, (GLuint, GLuintP));
-BGL_Wrap(VertexAttrib4usv, void, (GLuint, GLushortP));
-BGL_Wrap(VertexAttribPointer, void, (GLuint, GLint, GLenum, GLboolean, GLsizei, GLvoidP));
-
+BGL_Wrap(AttachShader, void, (GLuint, GLuint));
+BGL_Wrap(BindAttribLocation, void, (GLuint, GLuint, GLstring));
+BGL_Wrap(BlendEquationSeparate, void, (GLenum, GLenum));
+BGL_Wrap(CompileShader, void, (GLuint));
+BGL_Wrap(CreateProgram, GLuint, (void));
+BGL_Wrap(CreateShader, GLuint, (GLenum));
+BGL_Wrap(DeleteProgram, void, (GLuint));
+BGL_Wrap(DeleteShader, void, (GLuint));
+BGL_Wrap(DetachShader, void, (GLuint, GLuint));
+BGL_Wrap(DisableVertexAttribArray, void, (GLuint));
+BGL_Wrap(DrawBuffers, void, (GLsizei, GLenumP));
+BGL_Wrap(EnableVertexAttribArray, void, (GLuint));
+BGL_Wrap(GetActiveAttrib, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLintP, GLenumP, GLcharP));
+BGL_Wrap(GetActiveUniform, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLintP, GLenumP, GLcharP));
+BGL_Wrap(GetAttachedShaders, void, (GLuint, GLsizei, GLsizeiP, GLuintP));
+BGL_Wrap(GetAttribLocation, GLint, (GLuint, GLstring));
+BGL_Wrap(GetProgramInfoLog, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
+BGL_Wrap(GetProgramiv, void, (GLuint, GLenum, GLintP));
+BGL_Wrap(GetShaderInfoLog, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
+BGL_Wrap(GetShaderSource, void, (GLuint, GLsizei, GLsizeiP, GLcharP));
+BGL_Wrap(GetShaderiv, void, (GLuint, GLenum, GLintP));
+BGL_Wrap(GetUniformLocation, GLint, (GLuint, GLstring));
+BGL_Wrap(GetUniformfv, void, (GLuint, GLint, GLfloatP));
+BGL_Wrap(GetUniformiv, void, (GLuint, GLint, GLintP));
+BGL_Wrap(GetVertexAttribPointerv, void, (GLuint, GLenum, GLvoidP));
+BGL_Wrap(GetVertexAttribdv, void, (GLuint, GLenum, GLdoubleP));
+BGL_Wrap(GetVertexAttribfv, void, (GLuint, GLenum, GLfloatP));
+BGL_Wrap(GetVertexAttribiv, void, (GLuint, GLenum, GLintP));
+BGL_Wrap(IsProgram, GLboolean, (GLuint));
+BGL_Wrap(IsShader, GLboolean, (GLuint));
+BGL_Wrap(LinkProgram, void, (GLuint));
+BGL_Wrap(StencilFuncSeparate, void, (GLenum, GLenum, GLint, GLuint));
+BGL_Wrap(StencilMaskSeparate, void, (GLenum, GLuint));
+BGL_Wrap(StencilOpSeparate, void, (GLenum, GLenum, GLenum, GLenum));
+BGL_Wrap(Uniform1f, void, (GLint, GLfloat));
+BGL_Wrap(Uniform1fv, void, (GLint, GLsizei, GLfloatP));
+BGL_Wrap(Uniform1i, void, (GLint, GLint));
+BGL_Wrap(Uniform1iv, void, (GLint, GLsizei, GLintP));
+BGL_Wrap(Uniform2f, void, (GLint, GLfloat, GLfloat));
+BGL_Wrap(Uniform2fv, void, (GLint, GLsizei, GLfloatP));
+BGL_Wrap(Uniform2i, void, (GLint, GLint, GLint));
+BGL_Wrap(Uniform2iv, void, (GLint, GLsizei, GLintP));
+BGL_Wrap(Uniform3f, void, (GLint, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(Uniform3fv, void, (GLint, GLsizei, GLfloatP));
+BGL_Wrap(Uniform3i, void, (GLint, GLint, GLint, GLint));
+BGL_Wrap(Uniform3iv, void, (GLint, GLsizei, GLintP));
+BGL_Wrap(Uniform4f, void, (GLint, GLfloat, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(Uniform4fv, void, (GLint, GLsizei, GLfloatP));
+BGL_Wrap(Uniform4i, void, (GLint, GLint, GLint, GLint, GLint));
+BGL_Wrap(Uniform4iv, void, (GLint, GLsizei, GLintP));
+BGL_Wrap(UniformMatrix2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UseProgram, void, (GLuint));
+BGL_Wrap(ValidateProgram, void, (GLuint));
+BGL_Wrap(VertexAttrib1d, void, (GLuint, GLdouble));
+BGL_Wrap(VertexAttrib1dv, void, (GLuint, GLdoubleP));
+BGL_Wrap(VertexAttrib1f, void, (GLuint, GLfloat));
+BGL_Wrap(VertexAttrib1fv, void, (GLuint, GLfloatP));
+BGL_Wrap(VertexAttrib1s, void, (GLuint, GLshort));
+BGL_Wrap(VertexAttrib1sv, void, (GLuint, GLshortP));
+BGL_Wrap(VertexAttrib2d, void, (GLuint, GLdouble, GLdouble));
+BGL_Wrap(VertexAttrib2dv, void, (GLuint, GLdoubleP));
+BGL_Wrap(VertexAttrib2f, void, (GLuint, GLfloat, GLfloat));
+BGL_Wrap(VertexAttrib2fv, void, (GLuint, GLfloatP));
+BGL_Wrap(VertexAttrib2s, void, (GLuint, GLshort, GLshort));
+BGL_Wrap(VertexAttrib2sv, void, (GLuint, GLshortP));
+BGL_Wrap(VertexAttrib3d, void, (GLuint, GLdouble, GLdouble, GLdouble));
+BGL_Wrap(VertexAttrib3dv, void, (GLuint, GLdoubleP));
+BGL_Wrap(VertexAttrib3f, void, (GLuint, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(VertexAttrib3fv, void, (GLuint, GLfloatP));
+BGL_Wrap(VertexAttrib3s, void, (GLuint, GLshort, GLshort, GLshort));
+BGL_Wrap(VertexAttrib3sv, void, (GLuint, GLshortP));
+BGL_Wrap(VertexAttrib4Nbv, void, (GLuint, GLbyteP));
+BGL_Wrap(VertexAttrib4Niv, void, (GLuint, GLintP));
+BGL_Wrap(VertexAttrib4Nsv, void, (GLuint, GLshortP));
+BGL_Wrap(VertexAttrib4Nub, void, (GLuint, GLubyte, GLubyte, GLubyte, GLubyte));
+BGL_Wrap(VertexAttrib4Nubv, void, (GLuint, GLubyteP));
+BGL_Wrap(VertexAttrib4Nuiv, void, (GLuint, GLuintP));
+BGL_Wrap(VertexAttrib4Nusv, void, (GLuint, GLushortP));
+BGL_Wrap(VertexAttrib4bv, void, (GLuint, GLbyteP));
+BGL_Wrap(VertexAttrib4d, void, (GLuint, GLdouble, GLdouble, GLdouble, GLdouble));
+BGL_Wrap(VertexAttrib4dv, void, (GLuint, GLdoubleP));
+BGL_Wrap(VertexAttrib4f, void, (GLuint, GLfloat, GLfloat, GLfloat, GLfloat));
+BGL_Wrap(VertexAttrib4fv, void, (GLuint, GLfloatP));
+BGL_Wrap(VertexAttrib4iv, void, (GLuint, GLintP));
+BGL_Wrap(VertexAttrib4s, void, (GLuint, GLshort, GLshort, GLshort, GLshort));
+BGL_Wrap(VertexAttrib4sv, void, (GLuint, GLshortP));
+BGL_Wrap(VertexAttrib4ubv, void, (GLuint, GLubyteP));
+BGL_Wrap(VertexAttrib4uiv, void, (GLuint, GLuintP));
+BGL_Wrap(VertexAttrib4usv, void, (GLuint, GLushortP));
+BGL_Wrap(VertexAttribPointer, void, (GLuint, GLint, GLenum, GLboolean, GLsizei, GLvoidP));
/* GL_VERSION_2_1 */
-BGL_Wrap(UniformMatrix2x3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix2x4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix3x2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix3x4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix4x2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-BGL_Wrap(UniformMatrix4x3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
-
+BGL_Wrap(UniformMatrix2x3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix2x4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix3x2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix3x4fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix4x2fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
+BGL_Wrap(UniformMatrix4x3fv, void, (GLint, GLsizei, GLboolean, GLfloatP));
/* GL_VERSION_3_0 */
-BGL_Wrap(BindFramebuffer, void, (GLenum, GLuint));
-BGL_Wrap(BindRenderbuffer, void, (GLenum, GLuint));
-BGL_Wrap(BindVertexArray, void, (GLuint));
-BGL_Wrap(BlitFramebuffer, void, (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum));
-BGL_Wrap(CheckFramebufferStatus, GLenum, (GLenum));
-BGL_Wrap(DeleteFramebuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(DeleteRenderbuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(DeleteVertexArrays, void, (GLsizei, GLuintP));
-BGL_Wrap(FramebufferRenderbuffer, void, (GLenum, GLenum, GLenum, GLuint));
-BGL_Wrap(GenFramebuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(GenRenderbuffers, void, (GLsizei, GLuintP));
-BGL_Wrap(GenVertexArrays, void, (GLsizei, GLuintP));
-BGL_Wrap(GetStringi, GLstring, (GLenum, GLuint));
-BGL_Wrap(IsVertexArray, GLboolean, (GLuint));
-BGL_Wrap(RenderbufferStorage, void, (GLenum, GLenum, GLsizei, GLsizei));
-
+BGL_Wrap(BindFramebuffer, void, (GLenum, GLuint));
+BGL_Wrap(BindRenderbuffer, void, (GLenum, GLuint));
+BGL_Wrap(BindVertexArray, void, (GLuint));
+BGL_Wrap(BlitFramebuffer,
+ void,
+ (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum));
+BGL_Wrap(CheckFramebufferStatus, GLenum, (GLenum));
+BGL_Wrap(DeleteFramebuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(DeleteRenderbuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(DeleteVertexArrays, void, (GLsizei, GLuintP));
+BGL_Wrap(FramebufferRenderbuffer, void, (GLenum, GLenum, GLenum, GLuint));
+BGL_Wrap(GenFramebuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(GenRenderbuffers, void, (GLsizei, GLuintP));
+BGL_Wrap(GenVertexArrays, void, (GLsizei, GLuintP));
+BGL_Wrap(GetStringi, GLstring, (GLenum, GLuint));
+BGL_Wrap(IsVertexArray, GLboolean, (GLuint));
+BGL_Wrap(RenderbufferStorage, void, (GLenum, GLenum, GLsizei, GLsizei));
/* GL_VERSION_3_1 */
-BGL_Wrap(BindBufferBase, void, (GLenum, GLuint, GLuint));
-BGL_Wrap(BindBufferRange, void, (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr));
-BGL_Wrap(GetActiveUniformBlockName, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLcharP));
-BGL_Wrap(GetActiveUniformBlockiv, void, (GLuint, GLuint, GLenum, GLintP));
-BGL_Wrap(GetActiveUniformName, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLcharP));
-BGL_Wrap(GetActiveUniformsiv, void, (GLuint, GLsizei, GLuintP, GLenum, GLintP));
-BGL_Wrap(GetIntegeri_v, void, (GLenum, GLuint, GLintP));
-BGL_Wrap(GetUniformBlockIndex, GLuint, (GLuint, GLstring));
-BGL_Wrap(GetUniformIndices, void, (GLuint, GLsizei, GLcharP, GLuintP));
-BGL_Wrap(UniformBlockBinding, void, (GLuint, GLuint, GLuint));
-
+BGL_Wrap(BindBufferBase, void, (GLenum, GLuint, GLuint));
+BGL_Wrap(BindBufferRange, void, (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr));
+BGL_Wrap(GetActiveUniformBlockName, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLcharP));
+BGL_Wrap(GetActiveUniformBlockiv, void, (GLuint, GLuint, GLenum, GLintP));
+BGL_Wrap(GetActiveUniformName, void, (GLuint, GLuint, GLsizei, GLsizeiP, GLcharP));
+BGL_Wrap(GetActiveUniformsiv, void, (GLuint, GLsizei, GLuintP, GLenum, GLintP));
+BGL_Wrap(GetIntegeri_v, void, (GLenum, GLuint, GLintP));
+BGL_Wrap(GetUniformBlockIndex, GLuint, (GLuint, GLstring));
+BGL_Wrap(GetUniformIndices, void, (GLuint, GLsizei, GLcharP, GLuintP));
+BGL_Wrap(UniformBlockBinding, void, (GLuint, GLuint, GLuint));
/* GL_VERSION_3_2 */
-BGL_Wrap(FramebufferTexture, void, (GLenum, GLenum, GLuint, GLint));
-BGL_Wrap(GetBufferParameteri64v, void, (GLenum, GLenum, GLint64P));
-BGL_Wrap(GetInteger64i_v, void, (GLenum, GLuint, GLint64P));
-BGL_Wrap(GetMultisamplefv, void, (GLenum, GLuint, GLfloatP));
-BGL_Wrap(SampleMaski, void, (GLuint, GLbitfield));
-BGL_Wrap(TexImage2DMultisample, void, (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean));
-BGL_Wrap(TexImage3DMultisample, void, (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei, GLboolean));
-
+BGL_Wrap(FramebufferTexture, void, (GLenum, GLenum, GLuint, GLint));
+BGL_Wrap(GetBufferParameteri64v, void, (GLenum, GLenum, GLint64P));
+BGL_Wrap(GetInteger64i_v, void, (GLenum, GLuint, GLint64P));
+BGL_Wrap(GetMultisamplefv, void, (GLenum, GLuint, GLfloatP));
+BGL_Wrap(SampleMaski, void, (GLuint, GLbitfield));
+BGL_Wrap(TexImage2DMultisample, void, (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean));
+BGL_Wrap(TexImage3DMultisample,
+ void,
+ (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLsizei, GLboolean));
/* GL_VERSION_3_3 */
/* no new functions besides packed immediate mode (not part of core profile) */
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Module Definition
* \{ */
static struct PyModuleDef BGL_module_def = {
- PyModuleDef_HEAD_INIT,
- "bgl", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bgl", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
static void py_module_dict_add_int(PyObject *dict, const char *name, int value)
{
- PyObject *item;
- PyDict_SetItemString(dict, name, item = PyLong_FromLong(value));
- Py_DECREF(item);
+ PyObject *item;
+ PyDict_SetItemString(dict, name, item = PyLong_FromLong(value));
+ Py_DECREF(item);
}
static void py_module_dict_add_int64(PyObject *dict, const char *name, int64_t value)
{
- PyObject *item;
- PyDict_SetItemString(dict, name, item = PyLong_FromLongLong(value));
- Py_DECREF(item);
+ PyObject *item;
+ PyDict_SetItemString(dict, name, item = PyLong_FromLongLong(value));
+ Py_DECREF(item);
}
-static void py_module_dict_add_method(PyObject *submodule, PyObject *dict, PyMethodDef *method_def, bool is_valid)
+static void py_module_dict_add_method(PyObject *submodule,
+ PyObject *dict,
+ PyMethodDef *method_def,
+ bool is_valid)
{
- if (is_valid) {
- PyObject *m;
- m = PyCFunction_NewEx(method_def, NULL, submodule);
- PyDict_SetItemString(dict, method_def->ml_name, m);
- Py_DECREF(m);
- }
- else {
- PyDict_SetItemString(dict, method_def->ml_name, Py_None);
- }
+ if (is_valid) {
+ PyObject *m;
+ m = PyCFunction_NewEx(method_def, NULL, submodule);
+ PyDict_SetItemString(dict, method_def->ml_name, m);
+ Py_DECREF(m);
+ }
+ else {
+ PyDict_SetItemString(dict, method_def->ml_name, Py_None);
+ }
}
PyObject *BPyInit_bgl(void)
{
- PyObject *submodule, *dict;
- submodule = PyModule_Create(&BGL_module_def);
- dict = PyModule_GetDict(submodule);
+ PyObject *submodule, *dict;
+ submodule = PyModule_Create(&BGL_module_def);
+ dict = PyModule_GetDict(submodule);
- if (PyType_Ready(&BGL_bufferType) < 0) {
- return NULL; /* should never happen */
- }
+ if (PyType_Ready(&BGL_bufferType) < 0) {
+ return NULL; /* should never happen */
+ }
- PyModule_AddObject(submodule, "Buffer", (PyObject *)&BGL_bufferType);
- Py_INCREF((PyObject *)&BGL_bufferType);
+ PyModule_AddObject(submodule, "Buffer", (PyObject *)&BGL_bufferType);
+ Py_INCREF((PyObject *)&BGL_bufferType);
/* needed since some function pointers won't be NULL */
#ifdef __GNUC__
@@ -1434,1166 +1439,1166 @@ PyObject *BPyInit_bgl(void)
#endif
#define PY_MOD_ADD_METHOD(func) \
- { \
- static PyMethodDef method_def = {"gl"#func, Method_##func, METH_VARARGS}; \
- py_module_dict_add_method(submodule, dict, &method_def, (gl##func != NULL)); \
- } ((void)0)
-
- /* GL_VERSION_1_0 */
- {
- PY_MOD_ADD_METHOD(BlendFunc);
- PY_MOD_ADD_METHOD(Clear);
- PY_MOD_ADD_METHOD(ClearColor);
- PY_MOD_ADD_METHOD(ClearDepth);
- PY_MOD_ADD_METHOD(ClearStencil);
- PY_MOD_ADD_METHOD(ColorMask);
- PY_MOD_ADD_METHOD(CullFace);
- PY_MOD_ADD_METHOD(DepthFunc);
- PY_MOD_ADD_METHOD(DepthMask);
- PY_MOD_ADD_METHOD(DepthRange);
- PY_MOD_ADD_METHOD(Disable);
- PY_MOD_ADD_METHOD(DrawBuffer);
- PY_MOD_ADD_METHOD(Enable);
- PY_MOD_ADD_METHOD(Finish);
- PY_MOD_ADD_METHOD(Flush);
- PY_MOD_ADD_METHOD(FrontFace);
- PY_MOD_ADD_METHOD(GetBooleanv);
- PY_MOD_ADD_METHOD(GetDoublev);
- PY_MOD_ADD_METHOD(GetError);
- PY_MOD_ADD_METHOD(GetFloatv);
- PY_MOD_ADD_METHOD(GetIntegerv);
- PY_MOD_ADD_METHOD(GetString);
- PY_MOD_ADD_METHOD(GetTexImage);
- PY_MOD_ADD_METHOD(GetTexLevelParameterfv);
- PY_MOD_ADD_METHOD(GetTexLevelParameteriv);
- PY_MOD_ADD_METHOD(GetTexParameterfv);
- PY_MOD_ADD_METHOD(GetTexParameteriv);
- PY_MOD_ADD_METHOD(Hint);
- PY_MOD_ADD_METHOD(IsEnabled);
- PY_MOD_ADD_METHOD(LineWidth);
- PY_MOD_ADD_METHOD(LogicOp);
- PY_MOD_ADD_METHOD(PixelStoref);
- PY_MOD_ADD_METHOD(PixelStorei);
- PY_MOD_ADD_METHOD(PointSize);
- PY_MOD_ADD_METHOD(PolygonMode);
- PY_MOD_ADD_METHOD(ReadBuffer);
- PY_MOD_ADD_METHOD(ReadPixels);
- PY_MOD_ADD_METHOD(Scissor);
- PY_MOD_ADD_METHOD(StencilFunc);
- PY_MOD_ADD_METHOD(StencilMask);
- PY_MOD_ADD_METHOD(StencilOp);
- PY_MOD_ADD_METHOD(TexImage1D);
- PY_MOD_ADD_METHOD(TexImage2D);
- PY_MOD_ADD_METHOD(TexParameterf);
- PY_MOD_ADD_METHOD(TexParameterfv);
- PY_MOD_ADD_METHOD(TexParameteri);
- PY_MOD_ADD_METHOD(TexParameteriv);
- PY_MOD_ADD_METHOD(Viewport);
- }
-
- /* GL_VERSION_1_1 */
- {
- PY_MOD_ADD_METHOD(BindTexture);
- PY_MOD_ADD_METHOD(CopyTexImage1D);
- PY_MOD_ADD_METHOD(CopyTexImage2D);
- PY_MOD_ADD_METHOD(CopyTexSubImage1D);
- PY_MOD_ADD_METHOD(CopyTexSubImage2D);
- PY_MOD_ADD_METHOD(DeleteTextures);
- PY_MOD_ADD_METHOD(DrawArrays);
- PY_MOD_ADD_METHOD(DrawElements);
- PY_MOD_ADD_METHOD(GenTextures);
- PY_MOD_ADD_METHOD(IsTexture);
- PY_MOD_ADD_METHOD(PolygonOffset);
- PY_MOD_ADD_METHOD(TexSubImage1D);
- PY_MOD_ADD_METHOD(TexSubImage2D);
- }
-
- /* GL_VERSION_1_2 */
- {
- PY_MOD_ADD_METHOD(CopyTexSubImage3D);
- PY_MOD_ADD_METHOD(DrawRangeElements);
- PY_MOD_ADD_METHOD(TexImage3D);
- PY_MOD_ADD_METHOD(TexSubImage3D);
- }
-
- /* GL_VERSION_1_3 */
- {
- PY_MOD_ADD_METHOD(ActiveTexture);
- PY_MOD_ADD_METHOD(CompressedTexImage1D);
- PY_MOD_ADD_METHOD(CompressedTexImage2D);
- PY_MOD_ADD_METHOD(CompressedTexImage3D);
- PY_MOD_ADD_METHOD(CompressedTexSubImage1D);
- PY_MOD_ADD_METHOD(CompressedTexSubImage2D);
- PY_MOD_ADD_METHOD(CompressedTexSubImage3D);
- PY_MOD_ADD_METHOD(GetCompressedTexImage);
- PY_MOD_ADD_METHOD(SampleCoverage);
- }
-
- /* GL_VERSION_1_4 */
- {
- PY_MOD_ADD_METHOD(BlendColor);
- PY_MOD_ADD_METHOD(BlendEquation);
- }
-
- /* GL_VERSION_1_5 */
- {
- PY_MOD_ADD_METHOD(BeginQuery);
- PY_MOD_ADD_METHOD(BindBuffer);
- PY_MOD_ADD_METHOD(BufferData);
- PY_MOD_ADD_METHOD(BufferSubData);
- PY_MOD_ADD_METHOD(DeleteBuffers);
- PY_MOD_ADD_METHOD(DeleteQueries);
- PY_MOD_ADD_METHOD(EndQuery);
- PY_MOD_ADD_METHOD(GenBuffers);
- PY_MOD_ADD_METHOD(GenQueries);
- PY_MOD_ADD_METHOD(GetBufferParameteriv);
- PY_MOD_ADD_METHOD(GetBufferPointerv);
- PY_MOD_ADD_METHOD(GetBufferSubData);
- PY_MOD_ADD_METHOD(GetQueryObjectiv);
- PY_MOD_ADD_METHOD(GetQueryObjectuiv);
- PY_MOD_ADD_METHOD(GetQueryiv);
- PY_MOD_ADD_METHOD(IsBuffer);
- PY_MOD_ADD_METHOD(IsQuery);
- PY_MOD_ADD_METHOD(MapBuffer);
- PY_MOD_ADD_METHOD(UnmapBuffer);
- }
-
- /* GL_VERSION_2_0 */
- {
- PY_MOD_ADD_METHOD(AttachShader);
- PY_MOD_ADD_METHOD(BindAttribLocation);
- PY_MOD_ADD_METHOD(BlendEquationSeparate);
- PY_MOD_ADD_METHOD(CompileShader);
- PY_MOD_ADD_METHOD(CreateProgram);
- PY_MOD_ADD_METHOD(CreateShader);
- PY_MOD_ADD_METHOD(DeleteProgram);
- PY_MOD_ADD_METHOD(DeleteShader);
- PY_MOD_ADD_METHOD(DetachShader);
- PY_MOD_ADD_METHOD(DisableVertexAttribArray);
- PY_MOD_ADD_METHOD(DrawBuffers);
- PY_MOD_ADD_METHOD(EnableVertexAttribArray);
- PY_MOD_ADD_METHOD(GetActiveAttrib);
- PY_MOD_ADD_METHOD(GetActiveUniform);
- PY_MOD_ADD_METHOD(GetAttachedShaders);
- PY_MOD_ADD_METHOD(GetAttribLocation);
- PY_MOD_ADD_METHOD(GetProgramInfoLog);
- PY_MOD_ADD_METHOD(GetProgramiv);
- PY_MOD_ADD_METHOD(GetShaderInfoLog);
- PY_MOD_ADD_METHOD(GetShaderSource);
- PY_MOD_ADD_METHOD(GetShaderiv);
- PY_MOD_ADD_METHOD(GetUniformLocation);
- PY_MOD_ADD_METHOD(GetUniformfv);
- PY_MOD_ADD_METHOD(GetUniformiv);
- PY_MOD_ADD_METHOD(GetVertexAttribPointerv);
- PY_MOD_ADD_METHOD(GetVertexAttribdv);
- PY_MOD_ADD_METHOD(GetVertexAttribfv);
- PY_MOD_ADD_METHOD(GetVertexAttribiv);
- PY_MOD_ADD_METHOD(IsProgram);
- PY_MOD_ADD_METHOD(IsShader);
- PY_MOD_ADD_METHOD(LinkProgram);
- PY_MOD_ADD_METHOD(ShaderSource);
- PY_MOD_ADD_METHOD(StencilFuncSeparate);
- PY_MOD_ADD_METHOD(StencilMaskSeparate);
- PY_MOD_ADD_METHOD(StencilOpSeparate);
- PY_MOD_ADD_METHOD(Uniform1f);
- PY_MOD_ADD_METHOD(Uniform1fv);
- PY_MOD_ADD_METHOD(Uniform1i);
- PY_MOD_ADD_METHOD(Uniform1iv);
- PY_MOD_ADD_METHOD(Uniform2f);
- PY_MOD_ADD_METHOD(Uniform2fv);
- PY_MOD_ADD_METHOD(Uniform2i);
- PY_MOD_ADD_METHOD(Uniform2iv);
- PY_MOD_ADD_METHOD(Uniform3f);
- PY_MOD_ADD_METHOD(Uniform3fv);
- PY_MOD_ADD_METHOD(Uniform3i);
- PY_MOD_ADD_METHOD(Uniform3iv);
- PY_MOD_ADD_METHOD(Uniform4f);
- PY_MOD_ADD_METHOD(Uniform4fv);
- PY_MOD_ADD_METHOD(Uniform4i);
- PY_MOD_ADD_METHOD(Uniform4iv);
- PY_MOD_ADD_METHOD(UniformMatrix2fv);
- PY_MOD_ADD_METHOD(UniformMatrix3fv);
- PY_MOD_ADD_METHOD(UniformMatrix4fv);
- PY_MOD_ADD_METHOD(UseProgram);
- PY_MOD_ADD_METHOD(ValidateProgram);
- PY_MOD_ADD_METHOD(VertexAttrib1d);
- PY_MOD_ADD_METHOD(VertexAttrib1dv);
- PY_MOD_ADD_METHOD(VertexAttrib1f);
- PY_MOD_ADD_METHOD(VertexAttrib1fv);
- PY_MOD_ADD_METHOD(VertexAttrib1s);
- PY_MOD_ADD_METHOD(VertexAttrib1sv);
- PY_MOD_ADD_METHOD(VertexAttrib2d);
- PY_MOD_ADD_METHOD(VertexAttrib2dv);
- PY_MOD_ADD_METHOD(VertexAttrib2f);
- PY_MOD_ADD_METHOD(VertexAttrib2fv);
- PY_MOD_ADD_METHOD(VertexAttrib2s);
- PY_MOD_ADD_METHOD(VertexAttrib2sv);
- PY_MOD_ADD_METHOD(VertexAttrib3d);
- PY_MOD_ADD_METHOD(VertexAttrib3dv);
- PY_MOD_ADD_METHOD(VertexAttrib3f);
- PY_MOD_ADD_METHOD(VertexAttrib3fv);
- PY_MOD_ADD_METHOD(VertexAttrib3s);
- PY_MOD_ADD_METHOD(VertexAttrib3sv);
- PY_MOD_ADD_METHOD(VertexAttrib4Nbv);
- PY_MOD_ADD_METHOD(VertexAttrib4Niv);
- PY_MOD_ADD_METHOD(VertexAttrib4Nsv);
- PY_MOD_ADD_METHOD(VertexAttrib4Nub);
- PY_MOD_ADD_METHOD(VertexAttrib4Nubv);
- PY_MOD_ADD_METHOD(VertexAttrib4Nuiv);
- PY_MOD_ADD_METHOD(VertexAttrib4Nusv);
- PY_MOD_ADD_METHOD(VertexAttrib4bv);
- PY_MOD_ADD_METHOD(VertexAttrib4d);
- PY_MOD_ADD_METHOD(VertexAttrib4dv);
- PY_MOD_ADD_METHOD(VertexAttrib4f);
- PY_MOD_ADD_METHOD(VertexAttrib4fv);
- PY_MOD_ADD_METHOD(VertexAttrib4iv);
- PY_MOD_ADD_METHOD(VertexAttrib4s);
- PY_MOD_ADD_METHOD(VertexAttrib4sv);
- PY_MOD_ADD_METHOD(VertexAttrib4ubv);
- PY_MOD_ADD_METHOD(VertexAttrib4uiv);
- PY_MOD_ADD_METHOD(VertexAttrib4usv);
- PY_MOD_ADD_METHOD(VertexAttribPointer);
- }
-
- /* GL_VERSION_2_1 */
- {
- PY_MOD_ADD_METHOD(UniformMatrix2x3fv);
- PY_MOD_ADD_METHOD(UniformMatrix2x4fv);
- PY_MOD_ADD_METHOD(UniformMatrix3x2fv);
- PY_MOD_ADD_METHOD(UniformMatrix3x4fv);
- PY_MOD_ADD_METHOD(UniformMatrix4x2fv);
- PY_MOD_ADD_METHOD(UniformMatrix4x3fv);
- }
-
- /* GL_VERSION_3_0 */
- {
- PY_MOD_ADD_METHOD(BindFramebuffer);
- PY_MOD_ADD_METHOD(BindRenderbuffer);
- PY_MOD_ADD_METHOD(BindVertexArray);
- PY_MOD_ADD_METHOD(BlitFramebuffer);
- PY_MOD_ADD_METHOD(CheckFramebufferStatus);
- PY_MOD_ADD_METHOD(DeleteFramebuffers);
- PY_MOD_ADD_METHOD(DeleteRenderbuffers);
- PY_MOD_ADD_METHOD(DeleteVertexArrays);
- PY_MOD_ADD_METHOD(FramebufferRenderbuffer);
- PY_MOD_ADD_METHOD(GenFramebuffers);
- PY_MOD_ADD_METHOD(GenRenderbuffers);
- PY_MOD_ADD_METHOD(GenVertexArrays);
- PY_MOD_ADD_METHOD(GetStringi);
- PY_MOD_ADD_METHOD(IsVertexArray);
- PY_MOD_ADD_METHOD(RenderbufferStorage);
- }
-
- /* GL_VERSION_3_1 */
- {
- PY_MOD_ADD_METHOD(BindBufferBase);
- PY_MOD_ADD_METHOD(BindBufferRange);
- PY_MOD_ADD_METHOD(GetActiveUniformBlockName);
- PY_MOD_ADD_METHOD(GetActiveUniformBlockiv);
- PY_MOD_ADD_METHOD(GetActiveUniformName);
- PY_MOD_ADD_METHOD(GetActiveUniformsiv);
- PY_MOD_ADD_METHOD(GetIntegeri_v);
- PY_MOD_ADD_METHOD(GetUniformBlockIndex);
- PY_MOD_ADD_METHOD(GetUniformIndices);
- PY_MOD_ADD_METHOD(UniformBlockBinding);
- }
-
- /* GL_VERSION_3_2 */
- {
- PY_MOD_ADD_METHOD(FramebufferTexture);
- PY_MOD_ADD_METHOD(GetBufferParameteri64v);
- PY_MOD_ADD_METHOD(GetInteger64i_v);
- PY_MOD_ADD_METHOD(GetMultisamplefv);
- PY_MOD_ADD_METHOD(SampleMaski);
- PY_MOD_ADD_METHOD(TexImage2DMultisample);
- PY_MOD_ADD_METHOD(TexImage3DMultisample);
- }
-
- /* GL_VERSION_3_3 */
- {
- }
+ { \
+ static PyMethodDef method_def = {"gl" #func, Method_##func, METH_VARARGS}; \
+ py_module_dict_add_method(submodule, dict, &method_def, (gl##func != NULL)); \
+ } \
+ ((void)0)
+
+ /* GL_VERSION_1_0 */
+ {
+ PY_MOD_ADD_METHOD(BlendFunc);
+ PY_MOD_ADD_METHOD(Clear);
+ PY_MOD_ADD_METHOD(ClearColor);
+ PY_MOD_ADD_METHOD(ClearDepth);
+ PY_MOD_ADD_METHOD(ClearStencil);
+ PY_MOD_ADD_METHOD(ColorMask);
+ PY_MOD_ADD_METHOD(CullFace);
+ PY_MOD_ADD_METHOD(DepthFunc);
+ PY_MOD_ADD_METHOD(DepthMask);
+ PY_MOD_ADD_METHOD(DepthRange);
+ PY_MOD_ADD_METHOD(Disable);
+ PY_MOD_ADD_METHOD(DrawBuffer);
+ PY_MOD_ADD_METHOD(Enable);
+ PY_MOD_ADD_METHOD(Finish);
+ PY_MOD_ADD_METHOD(Flush);
+ PY_MOD_ADD_METHOD(FrontFace);
+ PY_MOD_ADD_METHOD(GetBooleanv);
+ PY_MOD_ADD_METHOD(GetDoublev);
+ PY_MOD_ADD_METHOD(GetError);
+ PY_MOD_ADD_METHOD(GetFloatv);
+ PY_MOD_ADD_METHOD(GetIntegerv);
+ PY_MOD_ADD_METHOD(GetString);
+ PY_MOD_ADD_METHOD(GetTexImage);
+ PY_MOD_ADD_METHOD(GetTexLevelParameterfv);
+ PY_MOD_ADD_METHOD(GetTexLevelParameteriv);
+ PY_MOD_ADD_METHOD(GetTexParameterfv);
+ PY_MOD_ADD_METHOD(GetTexParameteriv);
+ PY_MOD_ADD_METHOD(Hint);
+ PY_MOD_ADD_METHOD(IsEnabled);
+ PY_MOD_ADD_METHOD(LineWidth);
+ PY_MOD_ADD_METHOD(LogicOp);
+ PY_MOD_ADD_METHOD(PixelStoref);
+ PY_MOD_ADD_METHOD(PixelStorei);
+ PY_MOD_ADD_METHOD(PointSize);
+ PY_MOD_ADD_METHOD(PolygonMode);
+ PY_MOD_ADD_METHOD(ReadBuffer);
+ PY_MOD_ADD_METHOD(ReadPixels);
+ PY_MOD_ADD_METHOD(Scissor);
+ PY_MOD_ADD_METHOD(StencilFunc);
+ PY_MOD_ADD_METHOD(StencilMask);
+ PY_MOD_ADD_METHOD(StencilOp);
+ PY_MOD_ADD_METHOD(TexImage1D);
+ PY_MOD_ADD_METHOD(TexImage2D);
+ PY_MOD_ADD_METHOD(TexParameterf);
+ PY_MOD_ADD_METHOD(TexParameterfv);
+ PY_MOD_ADD_METHOD(TexParameteri);
+ PY_MOD_ADD_METHOD(TexParameteriv);
+ PY_MOD_ADD_METHOD(Viewport);
+ }
+
+ /* GL_VERSION_1_1 */
+ {
+ PY_MOD_ADD_METHOD(BindTexture);
+ PY_MOD_ADD_METHOD(CopyTexImage1D);
+ PY_MOD_ADD_METHOD(CopyTexImage2D);
+ PY_MOD_ADD_METHOD(CopyTexSubImage1D);
+ PY_MOD_ADD_METHOD(CopyTexSubImage2D);
+ PY_MOD_ADD_METHOD(DeleteTextures);
+ PY_MOD_ADD_METHOD(DrawArrays);
+ PY_MOD_ADD_METHOD(DrawElements);
+ PY_MOD_ADD_METHOD(GenTextures);
+ PY_MOD_ADD_METHOD(IsTexture);
+ PY_MOD_ADD_METHOD(PolygonOffset);
+ PY_MOD_ADD_METHOD(TexSubImage1D);
+ PY_MOD_ADD_METHOD(TexSubImage2D);
+ }
+
+ /* GL_VERSION_1_2 */
+ {
+ PY_MOD_ADD_METHOD(CopyTexSubImage3D);
+ PY_MOD_ADD_METHOD(DrawRangeElements);
+ PY_MOD_ADD_METHOD(TexImage3D);
+ PY_MOD_ADD_METHOD(TexSubImage3D);
+ }
+
+ /* GL_VERSION_1_3 */
+ {
+ PY_MOD_ADD_METHOD(ActiveTexture);
+ PY_MOD_ADD_METHOD(CompressedTexImage1D);
+ PY_MOD_ADD_METHOD(CompressedTexImage2D);
+ PY_MOD_ADD_METHOD(CompressedTexImage3D);
+ PY_MOD_ADD_METHOD(CompressedTexSubImage1D);
+ PY_MOD_ADD_METHOD(CompressedTexSubImage2D);
+ PY_MOD_ADD_METHOD(CompressedTexSubImage3D);
+ PY_MOD_ADD_METHOD(GetCompressedTexImage);
+ PY_MOD_ADD_METHOD(SampleCoverage);
+ }
+
+ /* GL_VERSION_1_4 */
+ {
+ PY_MOD_ADD_METHOD(BlendColor);
+ PY_MOD_ADD_METHOD(BlendEquation);
+ }
+
+ /* GL_VERSION_1_5 */
+ {
+ PY_MOD_ADD_METHOD(BeginQuery);
+ PY_MOD_ADD_METHOD(BindBuffer);
+ PY_MOD_ADD_METHOD(BufferData);
+ PY_MOD_ADD_METHOD(BufferSubData);
+ PY_MOD_ADD_METHOD(DeleteBuffers);
+ PY_MOD_ADD_METHOD(DeleteQueries);
+ PY_MOD_ADD_METHOD(EndQuery);
+ PY_MOD_ADD_METHOD(GenBuffers);
+ PY_MOD_ADD_METHOD(GenQueries);
+ PY_MOD_ADD_METHOD(GetBufferParameteriv);
+ PY_MOD_ADD_METHOD(GetBufferPointerv);
+ PY_MOD_ADD_METHOD(GetBufferSubData);
+ PY_MOD_ADD_METHOD(GetQueryObjectiv);
+ PY_MOD_ADD_METHOD(GetQueryObjectuiv);
+ PY_MOD_ADD_METHOD(GetQueryiv);
+ PY_MOD_ADD_METHOD(IsBuffer);
+ PY_MOD_ADD_METHOD(IsQuery);
+ PY_MOD_ADD_METHOD(MapBuffer);
+ PY_MOD_ADD_METHOD(UnmapBuffer);
+ }
+
+ /* GL_VERSION_2_0 */
+ {
+ PY_MOD_ADD_METHOD(AttachShader);
+ PY_MOD_ADD_METHOD(BindAttribLocation);
+ PY_MOD_ADD_METHOD(BlendEquationSeparate);
+ PY_MOD_ADD_METHOD(CompileShader);
+ PY_MOD_ADD_METHOD(CreateProgram);
+ PY_MOD_ADD_METHOD(CreateShader);
+ PY_MOD_ADD_METHOD(DeleteProgram);
+ PY_MOD_ADD_METHOD(DeleteShader);
+ PY_MOD_ADD_METHOD(DetachShader);
+ PY_MOD_ADD_METHOD(DisableVertexAttribArray);
+ PY_MOD_ADD_METHOD(DrawBuffers);
+ PY_MOD_ADD_METHOD(EnableVertexAttribArray);
+ PY_MOD_ADD_METHOD(GetActiveAttrib);
+ PY_MOD_ADD_METHOD(GetActiveUniform);
+ PY_MOD_ADD_METHOD(GetAttachedShaders);
+ PY_MOD_ADD_METHOD(GetAttribLocation);
+ PY_MOD_ADD_METHOD(GetProgramInfoLog);
+ PY_MOD_ADD_METHOD(GetProgramiv);
+ PY_MOD_ADD_METHOD(GetShaderInfoLog);
+ PY_MOD_ADD_METHOD(GetShaderSource);
+ PY_MOD_ADD_METHOD(GetShaderiv);
+ PY_MOD_ADD_METHOD(GetUniformLocation);
+ PY_MOD_ADD_METHOD(GetUniformfv);
+ PY_MOD_ADD_METHOD(GetUniformiv);
+ PY_MOD_ADD_METHOD(GetVertexAttribPointerv);
+ PY_MOD_ADD_METHOD(GetVertexAttribdv);
+ PY_MOD_ADD_METHOD(GetVertexAttribfv);
+ PY_MOD_ADD_METHOD(GetVertexAttribiv);
+ PY_MOD_ADD_METHOD(IsProgram);
+ PY_MOD_ADD_METHOD(IsShader);
+ PY_MOD_ADD_METHOD(LinkProgram);
+ PY_MOD_ADD_METHOD(ShaderSource);
+ PY_MOD_ADD_METHOD(StencilFuncSeparate);
+ PY_MOD_ADD_METHOD(StencilMaskSeparate);
+ PY_MOD_ADD_METHOD(StencilOpSeparate);
+ PY_MOD_ADD_METHOD(Uniform1f);
+ PY_MOD_ADD_METHOD(Uniform1fv);
+ PY_MOD_ADD_METHOD(Uniform1i);
+ PY_MOD_ADD_METHOD(Uniform1iv);
+ PY_MOD_ADD_METHOD(Uniform2f);
+ PY_MOD_ADD_METHOD(Uniform2fv);
+ PY_MOD_ADD_METHOD(Uniform2i);
+ PY_MOD_ADD_METHOD(Uniform2iv);
+ PY_MOD_ADD_METHOD(Uniform3f);
+ PY_MOD_ADD_METHOD(Uniform3fv);
+ PY_MOD_ADD_METHOD(Uniform3i);
+ PY_MOD_ADD_METHOD(Uniform3iv);
+ PY_MOD_ADD_METHOD(Uniform4f);
+ PY_MOD_ADD_METHOD(Uniform4fv);
+ PY_MOD_ADD_METHOD(Uniform4i);
+ PY_MOD_ADD_METHOD(Uniform4iv);
+ PY_MOD_ADD_METHOD(UniformMatrix2fv);
+ PY_MOD_ADD_METHOD(UniformMatrix3fv);
+ PY_MOD_ADD_METHOD(UniformMatrix4fv);
+ PY_MOD_ADD_METHOD(UseProgram);
+ PY_MOD_ADD_METHOD(ValidateProgram);
+ PY_MOD_ADD_METHOD(VertexAttrib1d);
+ PY_MOD_ADD_METHOD(VertexAttrib1dv);
+ PY_MOD_ADD_METHOD(VertexAttrib1f);
+ PY_MOD_ADD_METHOD(VertexAttrib1fv);
+ PY_MOD_ADD_METHOD(VertexAttrib1s);
+ PY_MOD_ADD_METHOD(VertexAttrib1sv);
+ PY_MOD_ADD_METHOD(VertexAttrib2d);
+ PY_MOD_ADD_METHOD(VertexAttrib2dv);
+ PY_MOD_ADD_METHOD(VertexAttrib2f);
+ PY_MOD_ADD_METHOD(VertexAttrib2fv);
+ PY_MOD_ADD_METHOD(VertexAttrib2s);
+ PY_MOD_ADD_METHOD(VertexAttrib2sv);
+ PY_MOD_ADD_METHOD(VertexAttrib3d);
+ PY_MOD_ADD_METHOD(VertexAttrib3dv);
+ PY_MOD_ADD_METHOD(VertexAttrib3f);
+ PY_MOD_ADD_METHOD(VertexAttrib3fv);
+ PY_MOD_ADD_METHOD(VertexAttrib3s);
+ PY_MOD_ADD_METHOD(VertexAttrib3sv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nbv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Niv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nsv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nub);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nubv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nuiv);
+ PY_MOD_ADD_METHOD(VertexAttrib4Nusv);
+ PY_MOD_ADD_METHOD(VertexAttrib4bv);
+ PY_MOD_ADD_METHOD(VertexAttrib4d);
+ PY_MOD_ADD_METHOD(VertexAttrib4dv);
+ PY_MOD_ADD_METHOD(VertexAttrib4f);
+ PY_MOD_ADD_METHOD(VertexAttrib4fv);
+ PY_MOD_ADD_METHOD(VertexAttrib4iv);
+ PY_MOD_ADD_METHOD(VertexAttrib4s);
+ PY_MOD_ADD_METHOD(VertexAttrib4sv);
+ PY_MOD_ADD_METHOD(VertexAttrib4ubv);
+ PY_MOD_ADD_METHOD(VertexAttrib4uiv);
+ PY_MOD_ADD_METHOD(VertexAttrib4usv);
+ PY_MOD_ADD_METHOD(VertexAttribPointer);
+ }
+
+ /* GL_VERSION_2_1 */
+ {
+ PY_MOD_ADD_METHOD(UniformMatrix2x3fv);
+ PY_MOD_ADD_METHOD(UniformMatrix2x4fv);
+ PY_MOD_ADD_METHOD(UniformMatrix3x2fv);
+ PY_MOD_ADD_METHOD(UniformMatrix3x4fv);
+ PY_MOD_ADD_METHOD(UniformMatrix4x2fv);
+ PY_MOD_ADD_METHOD(UniformMatrix4x3fv);
+ }
+
+ /* GL_VERSION_3_0 */
+ {
+ PY_MOD_ADD_METHOD(BindFramebuffer);
+ PY_MOD_ADD_METHOD(BindRenderbuffer);
+ PY_MOD_ADD_METHOD(BindVertexArray);
+ PY_MOD_ADD_METHOD(BlitFramebuffer);
+ PY_MOD_ADD_METHOD(CheckFramebufferStatus);
+ PY_MOD_ADD_METHOD(DeleteFramebuffers);
+ PY_MOD_ADD_METHOD(DeleteRenderbuffers);
+ PY_MOD_ADD_METHOD(DeleteVertexArrays);
+ PY_MOD_ADD_METHOD(FramebufferRenderbuffer);
+ PY_MOD_ADD_METHOD(GenFramebuffers);
+ PY_MOD_ADD_METHOD(GenRenderbuffers);
+ PY_MOD_ADD_METHOD(GenVertexArrays);
+ PY_MOD_ADD_METHOD(GetStringi);
+ PY_MOD_ADD_METHOD(IsVertexArray);
+ PY_MOD_ADD_METHOD(RenderbufferStorage);
+ }
+
+ /* GL_VERSION_3_1 */
+ {
+ PY_MOD_ADD_METHOD(BindBufferBase);
+ PY_MOD_ADD_METHOD(BindBufferRange);
+ PY_MOD_ADD_METHOD(GetActiveUniformBlockName);
+ PY_MOD_ADD_METHOD(GetActiveUniformBlockiv);
+ PY_MOD_ADD_METHOD(GetActiveUniformName);
+ PY_MOD_ADD_METHOD(GetActiveUniformsiv);
+ PY_MOD_ADD_METHOD(GetIntegeri_v);
+ PY_MOD_ADD_METHOD(GetUniformBlockIndex);
+ PY_MOD_ADD_METHOD(GetUniformIndices);
+ PY_MOD_ADD_METHOD(UniformBlockBinding);
+ }
+
+ /* GL_VERSION_3_2 */
+ {
+ PY_MOD_ADD_METHOD(FramebufferTexture);
+ PY_MOD_ADD_METHOD(GetBufferParameteri64v);
+ PY_MOD_ADD_METHOD(GetInteger64i_v);
+ PY_MOD_ADD_METHOD(GetMultisamplefv);
+ PY_MOD_ADD_METHOD(SampleMaski);
+ PY_MOD_ADD_METHOD(TexImage2DMultisample);
+ PY_MOD_ADD_METHOD(TexImage3DMultisample);
+ }
+
+ /* GL_VERSION_3_3 */
+ {
+ }
#define PY_DICT_ADD_INT(x) py_module_dict_add_int(dict, #x, x)
#define PY_DICT_ADD_INT64(x) py_module_dict_add_int64(dict, #x, x)
- /* GL_VERSION_1_1 */
- {
- PY_DICT_ADD_INT(GL_ALPHA);
- PY_DICT_ADD_INT(GL_ALWAYS);
- PY_DICT_ADD_INT(GL_AND);
- PY_DICT_ADD_INT(GL_AND_INVERTED);
- PY_DICT_ADD_INT(GL_AND_REVERSE);
- PY_DICT_ADD_INT(GL_BACK);
- PY_DICT_ADD_INT(GL_BACK_LEFT);
- PY_DICT_ADD_INT(GL_BACK_RIGHT);
- PY_DICT_ADD_INT(GL_BLEND);
- PY_DICT_ADD_INT(GL_BLEND_DST);
- PY_DICT_ADD_INT(GL_BLEND_SRC);
- PY_DICT_ADD_INT(GL_BLUE);
- PY_DICT_ADD_INT(GL_BYTE);
- PY_DICT_ADD_INT(GL_CCW);
- PY_DICT_ADD_INT(GL_CLEAR);
- PY_DICT_ADD_INT(GL_COLOR);
- PY_DICT_ADD_INT(GL_COLOR_BUFFER_BIT);
- PY_DICT_ADD_INT(GL_COLOR_CLEAR_VALUE);
- PY_DICT_ADD_INT(GL_COLOR_LOGIC_OP);
- PY_DICT_ADD_INT(GL_COLOR_WRITEMASK);
- PY_DICT_ADD_INT(GL_COPY);
- PY_DICT_ADD_INT(GL_COPY_INVERTED);
- PY_DICT_ADD_INT(GL_CULL_FACE);
- PY_DICT_ADD_INT(GL_CULL_FACE_MODE);
- PY_DICT_ADD_INT(GL_CW);
- PY_DICT_ADD_INT(GL_DECR);
- PY_DICT_ADD_INT(GL_DEPTH);
- PY_DICT_ADD_INT(GL_DEPTH_BUFFER_BIT);
- PY_DICT_ADD_INT(GL_DEPTH_CLEAR_VALUE);
- PY_DICT_ADD_INT(GL_DEPTH_COMPONENT);
- PY_DICT_ADD_INT(GL_DEPTH_FUNC);
- PY_DICT_ADD_INT(GL_DEPTH_RANGE);
- PY_DICT_ADD_INT(GL_DEPTH_TEST);
- PY_DICT_ADD_INT(GL_DEPTH_WRITEMASK);
- PY_DICT_ADD_INT(GL_DITHER);
- PY_DICT_ADD_INT(GL_DONT_CARE);
- PY_DICT_ADD_INT(GL_DOUBLE);
- PY_DICT_ADD_INT(GL_DOUBLEBUFFER);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER);
- PY_DICT_ADD_INT(GL_DST_ALPHA);
- PY_DICT_ADD_INT(GL_DST_COLOR);
- PY_DICT_ADD_INT(GL_EQUAL);
- PY_DICT_ADD_INT(GL_EQUIV);
- PY_DICT_ADD_INT(GL_EXTENSIONS);
- PY_DICT_ADD_INT(GL_FALSE);
- PY_DICT_ADD_INT(GL_FASTEST);
- PY_DICT_ADD_INT(GL_FILL);
- PY_DICT_ADD_INT(GL_FLOAT);
- PY_DICT_ADD_INT(GL_FRONT);
- PY_DICT_ADD_INT(GL_FRONT_AND_BACK);
- PY_DICT_ADD_INT(GL_FRONT_FACE);
- PY_DICT_ADD_INT(GL_FRONT_LEFT);
- PY_DICT_ADD_INT(GL_FRONT_RIGHT);
- PY_DICT_ADD_INT(GL_GEQUAL);
- PY_DICT_ADD_INT(GL_GREATER);
- PY_DICT_ADD_INT(GL_GREEN);
- PY_DICT_ADD_INT(GL_INCR);
- PY_DICT_ADD_INT(GL_INT);
- PY_DICT_ADD_INT(GL_INVALID_ENUM);
- PY_DICT_ADD_INT(GL_INVALID_OPERATION);
- PY_DICT_ADD_INT(GL_INVALID_VALUE);
- PY_DICT_ADD_INT(GL_INVERT);
- PY_DICT_ADD_INT(GL_KEEP);
- PY_DICT_ADD_INT(GL_LEFT);
- PY_DICT_ADD_INT(GL_LEQUAL);
- PY_DICT_ADD_INT(GL_LESS);
- PY_DICT_ADD_INT(GL_LINE);
- PY_DICT_ADD_INT(GL_LINEAR);
- PY_DICT_ADD_INT(GL_LINEAR_MIPMAP_LINEAR);
- PY_DICT_ADD_INT(GL_LINEAR_MIPMAP_NEAREST);
- PY_DICT_ADD_INT(GL_LINES);
- PY_DICT_ADD_INT(GL_LINE_LOOP);
- PY_DICT_ADD_INT(GL_LINE_SMOOTH);
- PY_DICT_ADD_INT(GL_LINE_SMOOTH_HINT);
- PY_DICT_ADD_INT(GL_LINE_STRIP);
- PY_DICT_ADD_INT(GL_LINE_WIDTH);
- PY_DICT_ADD_INT(GL_LINE_WIDTH_GRANULARITY);
- PY_DICT_ADD_INT(GL_LINE_WIDTH_RANGE);
- PY_DICT_ADD_INT(GL_LOGIC_OP_MODE);
- PY_DICT_ADD_INT(GL_MAX_TEXTURE_SIZE);
- PY_DICT_ADD_INT(GL_MAX_VIEWPORT_DIMS);
- PY_DICT_ADD_INT(GL_NAND);
- PY_DICT_ADD_INT(GL_NEAREST);
- PY_DICT_ADD_INT(GL_NEAREST_MIPMAP_LINEAR);
- PY_DICT_ADD_INT(GL_NEAREST_MIPMAP_NEAREST);
- PY_DICT_ADD_INT(GL_NEVER);
- PY_DICT_ADD_INT(GL_NICEST);
- PY_DICT_ADD_INT(GL_NONE);
- PY_DICT_ADD_INT(GL_NOOP);
- PY_DICT_ADD_INT(GL_NOR);
- PY_DICT_ADD_INT(GL_NOTEQUAL);
- PY_DICT_ADD_INT(GL_NO_ERROR);
- PY_DICT_ADD_INT(GL_ONE);
- PY_DICT_ADD_INT(GL_ONE_MINUS_DST_ALPHA);
- PY_DICT_ADD_INT(GL_ONE_MINUS_DST_COLOR);
- PY_DICT_ADD_INT(GL_ONE_MINUS_SRC_ALPHA);
- PY_DICT_ADD_INT(GL_ONE_MINUS_SRC_COLOR);
- PY_DICT_ADD_INT(GL_OR);
- PY_DICT_ADD_INT(GL_OR_INVERTED);
- PY_DICT_ADD_INT(GL_OR_REVERSE);
- PY_DICT_ADD_INT(GL_OUT_OF_MEMORY);
- PY_DICT_ADD_INT(GL_PACK_ALIGNMENT);
- PY_DICT_ADD_INT(GL_PACK_LSB_FIRST);
- PY_DICT_ADD_INT(GL_PACK_ROW_LENGTH);
- PY_DICT_ADD_INT(GL_PACK_SKIP_PIXELS);
- PY_DICT_ADD_INT(GL_PACK_SKIP_ROWS);
- PY_DICT_ADD_INT(GL_PACK_SWAP_BYTES);
- PY_DICT_ADD_INT(GL_POINT);
- PY_DICT_ADD_INT(GL_POINTS);
- PY_DICT_ADD_INT(GL_POINT_SIZE);
- PY_DICT_ADD_INT(GL_POLYGON_MODE);
- PY_DICT_ADD_INT(GL_POLYGON_OFFSET_FACTOR);
- PY_DICT_ADD_INT(GL_POLYGON_OFFSET_FILL);
- PY_DICT_ADD_INT(GL_POLYGON_OFFSET_LINE);
- PY_DICT_ADD_INT(GL_POLYGON_OFFSET_POINT);
- PY_DICT_ADD_INT(GL_POLYGON_OFFSET_UNITS);
- PY_DICT_ADD_INT(GL_POLYGON_SMOOTH);
- PY_DICT_ADD_INT(GL_POLYGON_SMOOTH_HINT);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_1D);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D);
- PY_DICT_ADD_INT(GL_R3_G3_B2);
- PY_DICT_ADD_INT(GL_READ_BUFFER);
- PY_DICT_ADD_INT(GL_RED);
- PY_DICT_ADD_INT(GL_RENDERER);
- PY_DICT_ADD_INT(GL_REPEAT);
- PY_DICT_ADD_INT(GL_REPLACE);
- PY_DICT_ADD_INT(GL_RGB);
- PY_DICT_ADD_INT(GL_RGB10);
- PY_DICT_ADD_INT(GL_RGB10_A2);
- PY_DICT_ADD_INT(GL_RGB12);
- PY_DICT_ADD_INT(GL_RGB16);
- PY_DICT_ADD_INT(GL_RGB4);
- PY_DICT_ADD_INT(GL_RGB5);
- PY_DICT_ADD_INT(GL_RGB5_A1);
- PY_DICT_ADD_INT(GL_RGB8);
- PY_DICT_ADD_INT(GL_RGBA);
- PY_DICT_ADD_INT(GL_RGBA12);
- PY_DICT_ADD_INT(GL_RGBA16);
- PY_DICT_ADD_INT(GL_RGBA2);
- PY_DICT_ADD_INT(GL_RGBA4);
- PY_DICT_ADD_INT(GL_RGBA8);
- PY_DICT_ADD_INT(GL_RIGHT);
- PY_DICT_ADD_INT(GL_SCISSOR_BOX);
- PY_DICT_ADD_INT(GL_SCISSOR_TEST);
- PY_DICT_ADD_INT(GL_SET);
- PY_DICT_ADD_INT(GL_SHORT);
- PY_DICT_ADD_INT(GL_SRC_ALPHA);
- PY_DICT_ADD_INT(GL_SRC_ALPHA_SATURATE);
- PY_DICT_ADD_INT(GL_SRC_COLOR);
- PY_DICT_ADD_INT(GL_STENCIL);
- PY_DICT_ADD_INT(GL_STENCIL_BUFFER_BIT);
- PY_DICT_ADD_INT(GL_STENCIL_CLEAR_VALUE);
- PY_DICT_ADD_INT(GL_STENCIL_FAIL);
- PY_DICT_ADD_INT(GL_STENCIL_FUNC);
- PY_DICT_ADD_INT(GL_STENCIL_INDEX);
- PY_DICT_ADD_INT(GL_STENCIL_PASS_DEPTH_FAIL);
- PY_DICT_ADD_INT(GL_STENCIL_PASS_DEPTH_PASS);
- PY_DICT_ADD_INT(GL_STENCIL_REF);
- PY_DICT_ADD_INT(GL_STENCIL_TEST);
- PY_DICT_ADD_INT(GL_STENCIL_VALUE_MASK);
- PY_DICT_ADD_INT(GL_STENCIL_WRITEMASK);
- PY_DICT_ADD_INT(GL_STEREO);
- PY_DICT_ADD_INT(GL_SUBPIXEL_BITS);
- PY_DICT_ADD_INT(GL_TEXTURE);
- PY_DICT_ADD_INT(GL_TEXTURE_1D);
- PY_DICT_ADD_INT(GL_TEXTURE_2D);
- PY_DICT_ADD_INT(GL_TEXTURE_ALPHA_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_1D);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D);
- PY_DICT_ADD_INT(GL_TEXTURE_BLUE_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_BORDER_COLOR);
- PY_DICT_ADD_INT(GL_TEXTURE_GREEN_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_HEIGHT);
- PY_DICT_ADD_INT(GL_TEXTURE_INTERNAL_FORMAT);
- PY_DICT_ADD_INT(GL_TEXTURE_MAG_FILTER);
- PY_DICT_ADD_INT(GL_TEXTURE_MIN_FILTER);
- PY_DICT_ADD_INT(GL_TEXTURE_RED_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_WIDTH);
- PY_DICT_ADD_INT(GL_TEXTURE_WRAP_S);
- PY_DICT_ADD_INT(GL_TEXTURE_WRAP_T);
- PY_DICT_ADD_INT(GL_TRIANGLES);
- PY_DICT_ADD_INT(GL_TRIANGLE_FAN);
- PY_DICT_ADD_INT(GL_TRIANGLE_STRIP);
- PY_DICT_ADD_INT(GL_TRUE);
- PY_DICT_ADD_INT(GL_UNPACK_ALIGNMENT);
- PY_DICT_ADD_INT(GL_UNPACK_LSB_FIRST);
- PY_DICT_ADD_INT(GL_UNPACK_ROW_LENGTH);
- PY_DICT_ADD_INT(GL_UNPACK_SKIP_PIXELS);
- PY_DICT_ADD_INT(GL_UNPACK_SKIP_ROWS);
- PY_DICT_ADD_INT(GL_UNPACK_SWAP_BYTES);
- PY_DICT_ADD_INT(GL_UNSIGNED_BYTE);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT);
- PY_DICT_ADD_INT(GL_VENDOR);
- PY_DICT_ADD_INT(GL_VERSION);
- PY_DICT_ADD_INT(GL_VIEWPORT);
- PY_DICT_ADD_INT(GL_XOR);
- PY_DICT_ADD_INT(GL_ZERO);
- }
-
- /* GL_VERSION_1_2 */
- {
- PY_DICT_ADD_INT(GL_ALIASED_LINE_WIDTH_RANGE);
- PY_DICT_ADD_INT(GL_BGR);
- PY_DICT_ADD_INT(GL_BGRA);
- PY_DICT_ADD_INT(GL_CLAMP_TO_EDGE);
- PY_DICT_ADD_INT(GL_MAX_3D_TEXTURE_SIZE);
- PY_DICT_ADD_INT(GL_MAX_ELEMENTS_INDICES);
- PY_DICT_ADD_INT(GL_MAX_ELEMENTS_VERTICES);
- PY_DICT_ADD_INT(GL_PACK_IMAGE_HEIGHT);
- PY_DICT_ADD_INT(GL_PACK_SKIP_IMAGES);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_3D);
- PY_DICT_ADD_INT(GL_SMOOTH_LINE_WIDTH_GRANULARITY);
- PY_DICT_ADD_INT(GL_SMOOTH_LINE_WIDTH_RANGE);
- PY_DICT_ADD_INT(GL_SMOOTH_POINT_SIZE_GRANULARITY);
- PY_DICT_ADD_INT(GL_SMOOTH_POINT_SIZE_RANGE);
- PY_DICT_ADD_INT(GL_TEXTURE_3D);
- PY_DICT_ADD_INT(GL_TEXTURE_BASE_LEVEL);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_3D);
- PY_DICT_ADD_INT(GL_TEXTURE_DEPTH);
- PY_DICT_ADD_INT(GL_TEXTURE_MAX_LEVEL);
- PY_DICT_ADD_INT(GL_TEXTURE_MAX_LOD);
- PY_DICT_ADD_INT(GL_TEXTURE_MIN_LOD);
- PY_DICT_ADD_INT(GL_TEXTURE_WRAP_R);
- PY_DICT_ADD_INT(GL_UNPACK_IMAGE_HEIGHT);
- PY_DICT_ADD_INT(GL_UNPACK_SKIP_IMAGES);
- PY_DICT_ADD_INT(GL_UNSIGNED_BYTE_2_3_3_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_BYTE_3_3_2);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_10_10_10_2);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_2_10_10_10_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_8_8_8_8);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_8_8_8_8_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_1_5_5_5_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_4_4_4_4);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_4_4_4_4_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_5_5_1);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_6_5);
- PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_6_5_REV);
- }
-
- /* GL_VERSION_1_3 */
- {
- PY_DICT_ADD_INT(GL_ACTIVE_TEXTURE);
- PY_DICT_ADD_INT(GL_CLAMP_TO_BORDER);
- PY_DICT_ADD_INT(GL_COMPRESSED_RGB);
- PY_DICT_ADD_INT(GL_COMPRESSED_RGBA);
- PY_DICT_ADD_INT(GL_COMPRESSED_TEXTURE_FORMATS);
- PY_DICT_ADD_INT(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
- PY_DICT_ADD_INT(GL_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_CUBE_MAP);
- PY_DICT_ADD_INT(GL_SAMPLES);
- PY_DICT_ADD_INT(GL_SAMPLE_ALPHA_TO_COVERAGE);
- PY_DICT_ADD_INT(GL_SAMPLE_ALPHA_TO_ONE);
- PY_DICT_ADD_INT(GL_SAMPLE_BUFFERS);
- PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE);
- PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE_INVERT);
- PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE_VALUE);
- PY_DICT_ADD_INT(GL_TEXTURE0);
- PY_DICT_ADD_INT(GL_TEXTURE1);
- PY_DICT_ADD_INT(GL_TEXTURE10);
- PY_DICT_ADD_INT(GL_TEXTURE11);
- PY_DICT_ADD_INT(GL_TEXTURE12);
- PY_DICT_ADD_INT(GL_TEXTURE13);
- PY_DICT_ADD_INT(GL_TEXTURE14);
- PY_DICT_ADD_INT(GL_TEXTURE15);
- PY_DICT_ADD_INT(GL_TEXTURE16);
- PY_DICT_ADD_INT(GL_TEXTURE17);
- PY_DICT_ADD_INT(GL_TEXTURE18);
- PY_DICT_ADD_INT(GL_TEXTURE19);
- PY_DICT_ADD_INT(GL_TEXTURE2);
- PY_DICT_ADD_INT(GL_TEXTURE20);
- PY_DICT_ADD_INT(GL_TEXTURE21);
- PY_DICT_ADD_INT(GL_TEXTURE22);
- PY_DICT_ADD_INT(GL_TEXTURE23);
- PY_DICT_ADD_INT(GL_TEXTURE24);
- PY_DICT_ADD_INT(GL_TEXTURE25);
- PY_DICT_ADD_INT(GL_TEXTURE26);
- PY_DICT_ADD_INT(GL_TEXTURE27);
- PY_DICT_ADD_INT(GL_TEXTURE28);
- PY_DICT_ADD_INT(GL_TEXTURE29);
- PY_DICT_ADD_INT(GL_TEXTURE3);
- PY_DICT_ADD_INT(GL_TEXTURE30);
- PY_DICT_ADD_INT(GL_TEXTURE31);
- PY_DICT_ADD_INT(GL_TEXTURE4);
- PY_DICT_ADD_INT(GL_TEXTURE5);
- PY_DICT_ADD_INT(GL_TEXTURE6);
- PY_DICT_ADD_INT(GL_TEXTURE7);
- PY_DICT_ADD_INT(GL_TEXTURE8);
- PY_DICT_ADD_INT(GL_TEXTURE9);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_CUBE_MAP);
- PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSED);
- PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSED_IMAGE_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSION_HINT);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_X);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_Y);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_Z);
- }
-
- /* GL_VERSION_1_4 */
- {
- PY_DICT_ADD_INT(GL_BLEND_DST_ALPHA);
- PY_DICT_ADD_INT(GL_BLEND_DST_RGB);
- PY_DICT_ADD_INT(GL_BLEND_SRC_ALPHA);
- PY_DICT_ADD_INT(GL_BLEND_SRC_RGB);
- PY_DICT_ADD_INT(GL_CONSTANT_ALPHA);
- PY_DICT_ADD_INT(GL_CONSTANT_COLOR);
- PY_DICT_ADD_INT(GL_DECR_WRAP);
- PY_DICT_ADD_INT(GL_DEPTH_COMPONENT16);
- PY_DICT_ADD_INT(GL_DEPTH_COMPONENT24);
- PY_DICT_ADD_INT(GL_DEPTH_COMPONENT32);
- PY_DICT_ADD_INT(GL_FUNC_ADD);
- PY_DICT_ADD_INT(GL_FUNC_REVERSE_SUBTRACT);
- PY_DICT_ADD_INT(GL_FUNC_SUBTRACT);
- PY_DICT_ADD_INT(GL_INCR_WRAP);
- PY_DICT_ADD_INT(GL_MAX);
- PY_DICT_ADD_INT(GL_MAX_TEXTURE_LOD_BIAS);
- PY_DICT_ADD_INT(GL_MIN);
- PY_DICT_ADD_INT(GL_MIRRORED_REPEAT);
- PY_DICT_ADD_INT(GL_ONE_MINUS_CONSTANT_ALPHA);
- PY_DICT_ADD_INT(GL_ONE_MINUS_CONSTANT_COLOR);
- PY_DICT_ADD_INT(GL_POINT_FADE_THRESHOLD_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_COMPARE_FUNC);
- PY_DICT_ADD_INT(GL_TEXTURE_COMPARE_MODE);
- PY_DICT_ADD_INT(GL_TEXTURE_DEPTH_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_LOD_BIAS);
- }
-
- /* GL_VERSION_1_5 */
- {
- PY_DICT_ADD_INT(GL_ARRAY_BUFFER);
- PY_DICT_ADD_INT(GL_ARRAY_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_BUFFER_ACCESS);
- PY_DICT_ADD_INT(GL_BUFFER_MAPPED);
- PY_DICT_ADD_INT(GL_BUFFER_MAP_POINTER);
- PY_DICT_ADD_INT(GL_BUFFER_SIZE);
- PY_DICT_ADD_INT(GL_BUFFER_USAGE);
- PY_DICT_ADD_INT(GL_CURRENT_QUERY);
- PY_DICT_ADD_INT(GL_DYNAMIC_COPY);
- PY_DICT_ADD_INT(GL_DYNAMIC_DRAW);
- PY_DICT_ADD_INT(GL_DYNAMIC_READ);
- PY_DICT_ADD_INT(GL_ELEMENT_ARRAY_BUFFER);
- PY_DICT_ADD_INT(GL_ELEMENT_ARRAY_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_QUERY_COUNTER_BITS);
- PY_DICT_ADD_INT(GL_QUERY_RESULT);
- PY_DICT_ADD_INT(GL_QUERY_RESULT_AVAILABLE);
- PY_DICT_ADD_INT(GL_READ_ONLY);
- PY_DICT_ADD_INT(GL_READ_WRITE);
- PY_DICT_ADD_INT(GL_SAMPLES_PASSED);
- PY_DICT_ADD_INT(GL_STATIC_COPY);
- PY_DICT_ADD_INT(GL_STATIC_DRAW);
- PY_DICT_ADD_INT(GL_STATIC_READ);
- PY_DICT_ADD_INT(GL_STREAM_COPY);
- PY_DICT_ADD_INT(GL_STREAM_DRAW);
- PY_DICT_ADD_INT(GL_STREAM_READ);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_WRITE_ONLY);
- }
-
- /* GL_VERSION_2_0 */
- {
- PY_DICT_ADD_INT(GL_ACTIVE_ATTRIBUTES);
- PY_DICT_ADD_INT(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
- PY_DICT_ADD_INT(GL_ACTIVE_UNIFORMS);
- PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_MAX_LENGTH);
- PY_DICT_ADD_INT(GL_ATTACHED_SHADERS);
- PY_DICT_ADD_INT(GL_BLEND_EQUATION_ALPHA);
- PY_DICT_ADD_INT(GL_BLEND_EQUATION_RGB);
- PY_DICT_ADD_INT(GL_BOOL);
- PY_DICT_ADD_INT(GL_BOOL_VEC2);
- PY_DICT_ADD_INT(GL_BOOL_VEC3);
- PY_DICT_ADD_INT(GL_BOOL_VEC4);
- PY_DICT_ADD_INT(GL_COMPILE_STATUS);
- PY_DICT_ADD_INT(GL_CURRENT_PROGRAM);
- PY_DICT_ADD_INT(GL_CURRENT_VERTEX_ATTRIB);
- PY_DICT_ADD_INT(GL_DELETE_STATUS);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER0);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER1);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER10);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER11);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER12);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER13);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER14);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER15);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER2);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER3);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER4);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER5);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER6);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER7);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER8);
- PY_DICT_ADD_INT(GL_DRAW_BUFFER9);
- PY_DICT_ADD_INT(GL_FLOAT_MAT2);
- PY_DICT_ADD_INT(GL_FLOAT_MAT3);
- PY_DICT_ADD_INT(GL_FLOAT_MAT4);
- PY_DICT_ADD_INT(GL_FLOAT_VEC2);
- PY_DICT_ADD_INT(GL_FLOAT_VEC3);
- PY_DICT_ADD_INT(GL_FLOAT_VEC4);
- PY_DICT_ADD_INT(GL_FRAGMENT_SHADER);
- PY_DICT_ADD_INT(GL_FRAGMENT_SHADER_DERIVATIVE_HINT);
- PY_DICT_ADD_INT(GL_INFO_LOG_LENGTH);
- PY_DICT_ADD_INT(GL_INT_VEC2);
- PY_DICT_ADD_INT(GL_INT_VEC3);
- PY_DICT_ADD_INT(GL_INT_VEC4);
- PY_DICT_ADD_INT(GL_LINK_STATUS);
- PY_DICT_ADD_INT(GL_LOWER_LEFT);
- PY_DICT_ADD_INT(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
- PY_DICT_ADD_INT(GL_MAX_DRAW_BUFFERS);
- PY_DICT_ADD_INT(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_TEXTURE_IMAGE_UNITS);
- PY_DICT_ADD_INT(GL_MAX_VARYING_FLOATS);
- PY_DICT_ADD_INT(GL_MAX_VERTEX_ATTRIBS);
- PY_DICT_ADD_INT(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
- PY_DICT_ADD_INT(GL_MAX_VERTEX_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_POINT_SPRITE_COORD_ORIGIN);
- PY_DICT_ADD_INT(GL_SAMPLER_1D);
- PY_DICT_ADD_INT(GL_SAMPLER_1D_SHADOW);
- PY_DICT_ADD_INT(GL_SAMPLER_2D);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_SHADOW);
- PY_DICT_ADD_INT(GL_SAMPLER_3D);
- PY_DICT_ADD_INT(GL_SAMPLER_CUBE);
- PY_DICT_ADD_INT(GL_SHADER_SOURCE_LENGTH);
- PY_DICT_ADD_INT(GL_SHADER_TYPE);
- PY_DICT_ADD_INT(GL_SHADING_LANGUAGE_VERSION);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_FAIL);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_FUNC);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_PASS_DEPTH_FAIL);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_PASS_DEPTH_PASS);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_REF);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_VALUE_MASK);
- PY_DICT_ADD_INT(GL_STENCIL_BACK_WRITEMASK);
- PY_DICT_ADD_INT(GL_UPPER_LEFT);
- PY_DICT_ADD_INT(GL_VALIDATE_STATUS);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_ENABLED);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_NORMALIZED);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_POINTER);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_SIZE);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_STRIDE);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_TYPE);
- PY_DICT_ADD_INT(GL_VERTEX_PROGRAM_POINT_SIZE);
- PY_DICT_ADD_INT(GL_VERTEX_SHADER);
- }
-
- /* GL_VERSION_2_1 */
- {
- PY_DICT_ADD_INT(GL_COMPRESSED_SRGB);
- PY_DICT_ADD_INT(GL_COMPRESSED_SRGB_ALPHA);
- PY_DICT_ADD_INT(GL_FLOAT_MAT2x3);
- PY_DICT_ADD_INT(GL_FLOAT_MAT2x4);
- PY_DICT_ADD_INT(GL_FLOAT_MAT3x2);
- PY_DICT_ADD_INT(GL_FLOAT_MAT3x4);
- PY_DICT_ADD_INT(GL_FLOAT_MAT4x2);
- PY_DICT_ADD_INT(GL_FLOAT_MAT4x3);
- PY_DICT_ADD_INT(GL_PIXEL_PACK_BUFFER);
- PY_DICT_ADD_INT(GL_PIXEL_PACK_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_PIXEL_UNPACK_BUFFER);
- PY_DICT_ADD_INT(GL_PIXEL_UNPACK_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_SRGB);
- PY_DICT_ADD_INT(GL_SRGB8);
- PY_DICT_ADD_INT(GL_SRGB8_ALPHA8);
- PY_DICT_ADD_INT(GL_SRGB_ALPHA);
- }
-
- /* GL_VERSION_3_0 */
- {
- PY_DICT_ADD_INT(GL_BGRA_INTEGER);
- PY_DICT_ADD_INT(GL_BGR_INTEGER);
- PY_DICT_ADD_INT(GL_BLUE_INTEGER);
- PY_DICT_ADD_INT(GL_BUFFER_ACCESS_FLAGS);
- PY_DICT_ADD_INT(GL_BUFFER_MAP_LENGTH);
- PY_DICT_ADD_INT(GL_BUFFER_MAP_OFFSET);
- PY_DICT_ADD_INT(GL_CLAMP_READ_COLOR);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE0);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE1);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE2);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE3);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE4);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE5);
+ /* GL_VERSION_1_1 */
+ {
+ PY_DICT_ADD_INT(GL_ALPHA);
+ PY_DICT_ADD_INT(GL_ALWAYS);
+ PY_DICT_ADD_INT(GL_AND);
+ PY_DICT_ADD_INT(GL_AND_INVERTED);
+ PY_DICT_ADD_INT(GL_AND_REVERSE);
+ PY_DICT_ADD_INT(GL_BACK);
+ PY_DICT_ADD_INT(GL_BACK_LEFT);
+ PY_DICT_ADD_INT(GL_BACK_RIGHT);
+ PY_DICT_ADD_INT(GL_BLEND);
+ PY_DICT_ADD_INT(GL_BLEND_DST);
+ PY_DICT_ADD_INT(GL_BLEND_SRC);
+ PY_DICT_ADD_INT(GL_BLUE);
+ PY_DICT_ADD_INT(GL_BYTE);
+ PY_DICT_ADD_INT(GL_CCW);
+ PY_DICT_ADD_INT(GL_CLEAR);
+ PY_DICT_ADD_INT(GL_COLOR);
+ PY_DICT_ADD_INT(GL_COLOR_BUFFER_BIT);
+ PY_DICT_ADD_INT(GL_COLOR_CLEAR_VALUE);
+ PY_DICT_ADD_INT(GL_COLOR_LOGIC_OP);
+ PY_DICT_ADD_INT(GL_COLOR_WRITEMASK);
+ PY_DICT_ADD_INT(GL_COPY);
+ PY_DICT_ADD_INT(GL_COPY_INVERTED);
+ PY_DICT_ADD_INT(GL_CULL_FACE);
+ PY_DICT_ADD_INT(GL_CULL_FACE_MODE);
+ PY_DICT_ADD_INT(GL_CW);
+ PY_DICT_ADD_INT(GL_DECR);
+ PY_DICT_ADD_INT(GL_DEPTH);
+ PY_DICT_ADD_INT(GL_DEPTH_BUFFER_BIT);
+ PY_DICT_ADD_INT(GL_DEPTH_CLEAR_VALUE);
+ PY_DICT_ADD_INT(GL_DEPTH_COMPONENT);
+ PY_DICT_ADD_INT(GL_DEPTH_FUNC);
+ PY_DICT_ADD_INT(GL_DEPTH_RANGE);
+ PY_DICT_ADD_INT(GL_DEPTH_TEST);
+ PY_DICT_ADD_INT(GL_DEPTH_WRITEMASK);
+ PY_DICT_ADD_INT(GL_DITHER);
+ PY_DICT_ADD_INT(GL_DONT_CARE);
+ PY_DICT_ADD_INT(GL_DOUBLE);
+ PY_DICT_ADD_INT(GL_DOUBLEBUFFER);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER);
+ PY_DICT_ADD_INT(GL_DST_ALPHA);
+ PY_DICT_ADD_INT(GL_DST_COLOR);
+ PY_DICT_ADD_INT(GL_EQUAL);
+ PY_DICT_ADD_INT(GL_EQUIV);
+ PY_DICT_ADD_INT(GL_EXTENSIONS);
+ PY_DICT_ADD_INT(GL_FALSE);
+ PY_DICT_ADD_INT(GL_FASTEST);
+ PY_DICT_ADD_INT(GL_FILL);
+ PY_DICT_ADD_INT(GL_FLOAT);
+ PY_DICT_ADD_INT(GL_FRONT);
+ PY_DICT_ADD_INT(GL_FRONT_AND_BACK);
+ PY_DICT_ADD_INT(GL_FRONT_FACE);
+ PY_DICT_ADD_INT(GL_FRONT_LEFT);
+ PY_DICT_ADD_INT(GL_FRONT_RIGHT);
+ PY_DICT_ADD_INT(GL_GEQUAL);
+ PY_DICT_ADD_INT(GL_GREATER);
+ PY_DICT_ADD_INT(GL_GREEN);
+ PY_DICT_ADD_INT(GL_INCR);
+ PY_DICT_ADD_INT(GL_INT);
+ PY_DICT_ADD_INT(GL_INVALID_ENUM);
+ PY_DICT_ADD_INT(GL_INVALID_OPERATION);
+ PY_DICT_ADD_INT(GL_INVALID_VALUE);
+ PY_DICT_ADD_INT(GL_INVERT);
+ PY_DICT_ADD_INT(GL_KEEP);
+ PY_DICT_ADD_INT(GL_LEFT);
+ PY_DICT_ADD_INT(GL_LEQUAL);
+ PY_DICT_ADD_INT(GL_LESS);
+ PY_DICT_ADD_INT(GL_LINE);
+ PY_DICT_ADD_INT(GL_LINEAR);
+ PY_DICT_ADD_INT(GL_LINEAR_MIPMAP_LINEAR);
+ PY_DICT_ADD_INT(GL_LINEAR_MIPMAP_NEAREST);
+ PY_DICT_ADD_INT(GL_LINES);
+ PY_DICT_ADD_INT(GL_LINE_LOOP);
+ PY_DICT_ADD_INT(GL_LINE_SMOOTH);
+ PY_DICT_ADD_INT(GL_LINE_SMOOTH_HINT);
+ PY_DICT_ADD_INT(GL_LINE_STRIP);
+ PY_DICT_ADD_INT(GL_LINE_WIDTH);
+ PY_DICT_ADD_INT(GL_LINE_WIDTH_GRANULARITY);
+ PY_DICT_ADD_INT(GL_LINE_WIDTH_RANGE);
+ PY_DICT_ADD_INT(GL_LOGIC_OP_MODE);
+ PY_DICT_ADD_INT(GL_MAX_TEXTURE_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_VIEWPORT_DIMS);
+ PY_DICT_ADD_INT(GL_NAND);
+ PY_DICT_ADD_INT(GL_NEAREST);
+ PY_DICT_ADD_INT(GL_NEAREST_MIPMAP_LINEAR);
+ PY_DICT_ADD_INT(GL_NEAREST_MIPMAP_NEAREST);
+ PY_DICT_ADD_INT(GL_NEVER);
+ PY_DICT_ADD_INT(GL_NICEST);
+ PY_DICT_ADD_INT(GL_NONE);
+ PY_DICT_ADD_INT(GL_NOOP);
+ PY_DICT_ADD_INT(GL_NOR);
+ PY_DICT_ADD_INT(GL_NOTEQUAL);
+ PY_DICT_ADD_INT(GL_NO_ERROR);
+ PY_DICT_ADD_INT(GL_ONE);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_DST_ALPHA);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_DST_COLOR);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_SRC_ALPHA);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_SRC_COLOR);
+ PY_DICT_ADD_INT(GL_OR);
+ PY_DICT_ADD_INT(GL_OR_INVERTED);
+ PY_DICT_ADD_INT(GL_OR_REVERSE);
+ PY_DICT_ADD_INT(GL_OUT_OF_MEMORY);
+ PY_DICT_ADD_INT(GL_PACK_ALIGNMENT);
+ PY_DICT_ADD_INT(GL_PACK_LSB_FIRST);
+ PY_DICT_ADD_INT(GL_PACK_ROW_LENGTH);
+ PY_DICT_ADD_INT(GL_PACK_SKIP_PIXELS);
+ PY_DICT_ADD_INT(GL_PACK_SKIP_ROWS);
+ PY_DICT_ADD_INT(GL_PACK_SWAP_BYTES);
+ PY_DICT_ADD_INT(GL_POINT);
+ PY_DICT_ADD_INT(GL_POINTS);
+ PY_DICT_ADD_INT(GL_POINT_SIZE);
+ PY_DICT_ADD_INT(GL_POLYGON_MODE);
+ PY_DICT_ADD_INT(GL_POLYGON_OFFSET_FACTOR);
+ PY_DICT_ADD_INT(GL_POLYGON_OFFSET_FILL);
+ PY_DICT_ADD_INT(GL_POLYGON_OFFSET_LINE);
+ PY_DICT_ADD_INT(GL_POLYGON_OFFSET_POINT);
+ PY_DICT_ADD_INT(GL_POLYGON_OFFSET_UNITS);
+ PY_DICT_ADD_INT(GL_POLYGON_SMOOTH);
+ PY_DICT_ADD_INT(GL_POLYGON_SMOOTH_HINT);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_1D);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D);
+ PY_DICT_ADD_INT(GL_R3_G3_B2);
+ PY_DICT_ADD_INT(GL_READ_BUFFER);
+ PY_DICT_ADD_INT(GL_RED);
+ PY_DICT_ADD_INT(GL_RENDERER);
+ PY_DICT_ADD_INT(GL_REPEAT);
+ PY_DICT_ADD_INT(GL_REPLACE);
+ PY_DICT_ADD_INT(GL_RGB);
+ PY_DICT_ADD_INT(GL_RGB10);
+ PY_DICT_ADD_INT(GL_RGB10_A2);
+ PY_DICT_ADD_INT(GL_RGB12);
+ PY_DICT_ADD_INT(GL_RGB16);
+ PY_DICT_ADD_INT(GL_RGB4);
+ PY_DICT_ADD_INT(GL_RGB5);
+ PY_DICT_ADD_INT(GL_RGB5_A1);
+ PY_DICT_ADD_INT(GL_RGB8);
+ PY_DICT_ADD_INT(GL_RGBA);
+ PY_DICT_ADD_INT(GL_RGBA12);
+ PY_DICT_ADD_INT(GL_RGBA16);
+ PY_DICT_ADD_INT(GL_RGBA2);
+ PY_DICT_ADD_INT(GL_RGBA4);
+ PY_DICT_ADD_INT(GL_RGBA8);
+ PY_DICT_ADD_INT(GL_RIGHT);
+ PY_DICT_ADD_INT(GL_SCISSOR_BOX);
+ PY_DICT_ADD_INT(GL_SCISSOR_TEST);
+ PY_DICT_ADD_INT(GL_SET);
+ PY_DICT_ADD_INT(GL_SHORT);
+ PY_DICT_ADD_INT(GL_SRC_ALPHA);
+ PY_DICT_ADD_INT(GL_SRC_ALPHA_SATURATE);
+ PY_DICT_ADD_INT(GL_SRC_COLOR);
+ PY_DICT_ADD_INT(GL_STENCIL);
+ PY_DICT_ADD_INT(GL_STENCIL_BUFFER_BIT);
+ PY_DICT_ADD_INT(GL_STENCIL_CLEAR_VALUE);
+ PY_DICT_ADD_INT(GL_STENCIL_FAIL);
+ PY_DICT_ADD_INT(GL_STENCIL_FUNC);
+ PY_DICT_ADD_INT(GL_STENCIL_INDEX);
+ PY_DICT_ADD_INT(GL_STENCIL_PASS_DEPTH_FAIL);
+ PY_DICT_ADD_INT(GL_STENCIL_PASS_DEPTH_PASS);
+ PY_DICT_ADD_INT(GL_STENCIL_REF);
+ PY_DICT_ADD_INT(GL_STENCIL_TEST);
+ PY_DICT_ADD_INT(GL_STENCIL_VALUE_MASK);
+ PY_DICT_ADD_INT(GL_STENCIL_WRITEMASK);
+ PY_DICT_ADD_INT(GL_STEREO);
+ PY_DICT_ADD_INT(GL_SUBPIXEL_BITS);
+ PY_DICT_ADD_INT(GL_TEXTURE);
+ PY_DICT_ADD_INT(GL_TEXTURE_1D);
+ PY_DICT_ADD_INT(GL_TEXTURE_2D);
+ PY_DICT_ADD_INT(GL_TEXTURE_ALPHA_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_1D);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D);
+ PY_DICT_ADD_INT(GL_TEXTURE_BLUE_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_BORDER_COLOR);
+ PY_DICT_ADD_INT(GL_TEXTURE_GREEN_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_HEIGHT);
+ PY_DICT_ADD_INT(GL_TEXTURE_INTERNAL_FORMAT);
+ PY_DICT_ADD_INT(GL_TEXTURE_MAG_FILTER);
+ PY_DICT_ADD_INT(GL_TEXTURE_MIN_FILTER);
+ PY_DICT_ADD_INT(GL_TEXTURE_RED_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_WIDTH);
+ PY_DICT_ADD_INT(GL_TEXTURE_WRAP_S);
+ PY_DICT_ADD_INT(GL_TEXTURE_WRAP_T);
+ PY_DICT_ADD_INT(GL_TRIANGLES);
+ PY_DICT_ADD_INT(GL_TRIANGLE_FAN);
+ PY_DICT_ADD_INT(GL_TRIANGLE_STRIP);
+ PY_DICT_ADD_INT(GL_TRUE);
+ PY_DICT_ADD_INT(GL_UNPACK_ALIGNMENT);
+ PY_DICT_ADD_INT(GL_UNPACK_LSB_FIRST);
+ PY_DICT_ADD_INT(GL_UNPACK_ROW_LENGTH);
+ PY_DICT_ADD_INT(GL_UNPACK_SKIP_PIXELS);
+ PY_DICT_ADD_INT(GL_UNPACK_SKIP_ROWS);
+ PY_DICT_ADD_INT(GL_UNPACK_SWAP_BYTES);
+ PY_DICT_ADD_INT(GL_UNSIGNED_BYTE);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT);
+ PY_DICT_ADD_INT(GL_VENDOR);
+ PY_DICT_ADD_INT(GL_VERSION);
+ PY_DICT_ADD_INT(GL_VIEWPORT);
+ PY_DICT_ADD_INT(GL_XOR);
+ PY_DICT_ADD_INT(GL_ZERO);
+ }
+
+ /* GL_VERSION_1_2 */
+ {
+ PY_DICT_ADD_INT(GL_ALIASED_LINE_WIDTH_RANGE);
+ PY_DICT_ADD_INT(GL_BGR);
+ PY_DICT_ADD_INT(GL_BGRA);
+ PY_DICT_ADD_INT(GL_CLAMP_TO_EDGE);
+ PY_DICT_ADD_INT(GL_MAX_3D_TEXTURE_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_ELEMENTS_INDICES);
+ PY_DICT_ADD_INT(GL_MAX_ELEMENTS_VERTICES);
+ PY_DICT_ADD_INT(GL_PACK_IMAGE_HEIGHT);
+ PY_DICT_ADD_INT(GL_PACK_SKIP_IMAGES);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_3D);
+ PY_DICT_ADD_INT(GL_SMOOTH_LINE_WIDTH_GRANULARITY);
+ PY_DICT_ADD_INT(GL_SMOOTH_LINE_WIDTH_RANGE);
+ PY_DICT_ADD_INT(GL_SMOOTH_POINT_SIZE_GRANULARITY);
+ PY_DICT_ADD_INT(GL_SMOOTH_POINT_SIZE_RANGE);
+ PY_DICT_ADD_INT(GL_TEXTURE_3D);
+ PY_DICT_ADD_INT(GL_TEXTURE_BASE_LEVEL);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_3D);
+ PY_DICT_ADD_INT(GL_TEXTURE_DEPTH);
+ PY_DICT_ADD_INT(GL_TEXTURE_MAX_LEVEL);
+ PY_DICT_ADD_INT(GL_TEXTURE_MAX_LOD);
+ PY_DICT_ADD_INT(GL_TEXTURE_MIN_LOD);
+ PY_DICT_ADD_INT(GL_TEXTURE_WRAP_R);
+ PY_DICT_ADD_INT(GL_UNPACK_IMAGE_HEIGHT);
+ PY_DICT_ADD_INT(GL_UNPACK_SKIP_IMAGES);
+ PY_DICT_ADD_INT(GL_UNSIGNED_BYTE_2_3_3_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_BYTE_3_3_2);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_10_10_10_2);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_2_10_10_10_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_8_8_8_8);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_8_8_8_8_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_1_5_5_5_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_4_4_4_4);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_4_4_4_4_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_5_5_1);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_6_5);
+ PY_DICT_ADD_INT(GL_UNSIGNED_SHORT_5_6_5_REV);
+ }
+
+ /* GL_VERSION_1_3 */
+ {
+ PY_DICT_ADD_INT(GL_ACTIVE_TEXTURE);
+ PY_DICT_ADD_INT(GL_CLAMP_TO_BORDER);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RGB);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RGBA);
+ PY_DICT_ADD_INT(GL_COMPRESSED_TEXTURE_FORMATS);
+ PY_DICT_ADD_INT(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
+ PY_DICT_ADD_INT(GL_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_CUBE_MAP);
+ PY_DICT_ADD_INT(GL_SAMPLES);
+ PY_DICT_ADD_INT(GL_SAMPLE_ALPHA_TO_COVERAGE);
+ PY_DICT_ADD_INT(GL_SAMPLE_ALPHA_TO_ONE);
+ PY_DICT_ADD_INT(GL_SAMPLE_BUFFERS);
+ PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE);
+ PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE_INVERT);
+ PY_DICT_ADD_INT(GL_SAMPLE_COVERAGE_VALUE);
+ PY_DICT_ADD_INT(GL_TEXTURE0);
+ PY_DICT_ADD_INT(GL_TEXTURE1);
+ PY_DICT_ADD_INT(GL_TEXTURE10);
+ PY_DICT_ADD_INT(GL_TEXTURE11);
+ PY_DICT_ADD_INT(GL_TEXTURE12);
+ PY_DICT_ADD_INT(GL_TEXTURE13);
+ PY_DICT_ADD_INT(GL_TEXTURE14);
+ PY_DICT_ADD_INT(GL_TEXTURE15);
+ PY_DICT_ADD_INT(GL_TEXTURE16);
+ PY_DICT_ADD_INT(GL_TEXTURE17);
+ PY_DICT_ADD_INT(GL_TEXTURE18);
+ PY_DICT_ADD_INT(GL_TEXTURE19);
+ PY_DICT_ADD_INT(GL_TEXTURE2);
+ PY_DICT_ADD_INT(GL_TEXTURE20);
+ PY_DICT_ADD_INT(GL_TEXTURE21);
+ PY_DICT_ADD_INT(GL_TEXTURE22);
+ PY_DICT_ADD_INT(GL_TEXTURE23);
+ PY_DICT_ADD_INT(GL_TEXTURE24);
+ PY_DICT_ADD_INT(GL_TEXTURE25);
+ PY_DICT_ADD_INT(GL_TEXTURE26);
+ PY_DICT_ADD_INT(GL_TEXTURE27);
+ PY_DICT_ADD_INT(GL_TEXTURE28);
+ PY_DICT_ADD_INT(GL_TEXTURE29);
+ PY_DICT_ADD_INT(GL_TEXTURE3);
+ PY_DICT_ADD_INT(GL_TEXTURE30);
+ PY_DICT_ADD_INT(GL_TEXTURE31);
+ PY_DICT_ADD_INT(GL_TEXTURE4);
+ PY_DICT_ADD_INT(GL_TEXTURE5);
+ PY_DICT_ADD_INT(GL_TEXTURE6);
+ PY_DICT_ADD_INT(GL_TEXTURE7);
+ PY_DICT_ADD_INT(GL_TEXTURE8);
+ PY_DICT_ADD_INT(GL_TEXTURE9);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_CUBE_MAP);
+ PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSED);
+ PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSED_IMAGE_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_COMPRESSION_HINT);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_X);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_Y);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_POSITIVE_Z);
+ }
+
+ /* GL_VERSION_1_4 */
+ {
+ PY_DICT_ADD_INT(GL_BLEND_DST_ALPHA);
+ PY_DICT_ADD_INT(GL_BLEND_DST_RGB);
+ PY_DICT_ADD_INT(GL_BLEND_SRC_ALPHA);
+ PY_DICT_ADD_INT(GL_BLEND_SRC_RGB);
+ PY_DICT_ADD_INT(GL_CONSTANT_ALPHA);
+ PY_DICT_ADD_INT(GL_CONSTANT_COLOR);
+ PY_DICT_ADD_INT(GL_DECR_WRAP);
+ PY_DICT_ADD_INT(GL_DEPTH_COMPONENT16);
+ PY_DICT_ADD_INT(GL_DEPTH_COMPONENT24);
+ PY_DICT_ADD_INT(GL_DEPTH_COMPONENT32);
+ PY_DICT_ADD_INT(GL_FUNC_ADD);
+ PY_DICT_ADD_INT(GL_FUNC_REVERSE_SUBTRACT);
+ PY_DICT_ADD_INT(GL_FUNC_SUBTRACT);
+ PY_DICT_ADD_INT(GL_INCR_WRAP);
+ PY_DICT_ADD_INT(GL_MAX);
+ PY_DICT_ADD_INT(GL_MAX_TEXTURE_LOD_BIAS);
+ PY_DICT_ADD_INT(GL_MIN);
+ PY_DICT_ADD_INT(GL_MIRRORED_REPEAT);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_CONSTANT_ALPHA);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_CONSTANT_COLOR);
+ PY_DICT_ADD_INT(GL_POINT_FADE_THRESHOLD_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_COMPARE_FUNC);
+ PY_DICT_ADD_INT(GL_TEXTURE_COMPARE_MODE);
+ PY_DICT_ADD_INT(GL_TEXTURE_DEPTH_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_LOD_BIAS);
+ }
+
+ /* GL_VERSION_1_5 */
+ {
+ PY_DICT_ADD_INT(GL_ARRAY_BUFFER);
+ PY_DICT_ADD_INT(GL_ARRAY_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_BUFFER_ACCESS);
+ PY_DICT_ADD_INT(GL_BUFFER_MAPPED);
+ PY_DICT_ADD_INT(GL_BUFFER_MAP_POINTER);
+ PY_DICT_ADD_INT(GL_BUFFER_SIZE);
+ PY_DICT_ADD_INT(GL_BUFFER_USAGE);
+ PY_DICT_ADD_INT(GL_CURRENT_QUERY);
+ PY_DICT_ADD_INT(GL_DYNAMIC_COPY);
+ PY_DICT_ADD_INT(GL_DYNAMIC_DRAW);
+ PY_DICT_ADD_INT(GL_DYNAMIC_READ);
+ PY_DICT_ADD_INT(GL_ELEMENT_ARRAY_BUFFER);
+ PY_DICT_ADD_INT(GL_ELEMENT_ARRAY_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_QUERY_COUNTER_BITS);
+ PY_DICT_ADD_INT(GL_QUERY_RESULT);
+ PY_DICT_ADD_INT(GL_QUERY_RESULT_AVAILABLE);
+ PY_DICT_ADD_INT(GL_READ_ONLY);
+ PY_DICT_ADD_INT(GL_READ_WRITE);
+ PY_DICT_ADD_INT(GL_SAMPLES_PASSED);
+ PY_DICT_ADD_INT(GL_STATIC_COPY);
+ PY_DICT_ADD_INT(GL_STATIC_DRAW);
+ PY_DICT_ADD_INT(GL_STATIC_READ);
+ PY_DICT_ADD_INT(GL_STREAM_COPY);
+ PY_DICT_ADD_INT(GL_STREAM_DRAW);
+ PY_DICT_ADD_INT(GL_STREAM_READ);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_WRITE_ONLY);
+ }
+
+ /* GL_VERSION_2_0 */
+ {
+ PY_DICT_ADD_INT(GL_ACTIVE_ATTRIBUTES);
+ PY_DICT_ADD_INT(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
+ PY_DICT_ADD_INT(GL_ACTIVE_UNIFORMS);
+ PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_MAX_LENGTH);
+ PY_DICT_ADD_INT(GL_ATTACHED_SHADERS);
+ PY_DICT_ADD_INT(GL_BLEND_EQUATION_ALPHA);
+ PY_DICT_ADD_INT(GL_BLEND_EQUATION_RGB);
+ PY_DICT_ADD_INT(GL_BOOL);
+ PY_DICT_ADD_INT(GL_BOOL_VEC2);
+ PY_DICT_ADD_INT(GL_BOOL_VEC3);
+ PY_DICT_ADD_INT(GL_BOOL_VEC4);
+ PY_DICT_ADD_INT(GL_COMPILE_STATUS);
+ PY_DICT_ADD_INT(GL_CURRENT_PROGRAM);
+ PY_DICT_ADD_INT(GL_CURRENT_VERTEX_ATTRIB);
+ PY_DICT_ADD_INT(GL_DELETE_STATUS);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER0);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER1);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER10);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER11);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER12);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER13);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER14);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER15);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER2);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER3);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER4);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER5);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER6);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER7);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER8);
+ PY_DICT_ADD_INT(GL_DRAW_BUFFER9);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT2);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT3);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT4);
+ PY_DICT_ADD_INT(GL_FLOAT_VEC2);
+ PY_DICT_ADD_INT(GL_FLOAT_VEC3);
+ PY_DICT_ADD_INT(GL_FLOAT_VEC4);
+ PY_DICT_ADD_INT(GL_FRAGMENT_SHADER);
+ PY_DICT_ADD_INT(GL_FRAGMENT_SHADER_DERIVATIVE_HINT);
+ PY_DICT_ADD_INT(GL_INFO_LOG_LENGTH);
+ PY_DICT_ADD_INT(GL_INT_VEC2);
+ PY_DICT_ADD_INT(GL_INT_VEC3);
+ PY_DICT_ADD_INT(GL_INT_VEC4);
+ PY_DICT_ADD_INT(GL_LINK_STATUS);
+ PY_DICT_ADD_INT(GL_LOWER_LEFT);
+ PY_DICT_ADD_INT(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
+ PY_DICT_ADD_INT(GL_MAX_DRAW_BUFFERS);
+ PY_DICT_ADD_INT(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_TEXTURE_IMAGE_UNITS);
+ PY_DICT_ADD_INT(GL_MAX_VARYING_FLOATS);
+ PY_DICT_ADD_INT(GL_MAX_VERTEX_ATTRIBS);
+ PY_DICT_ADD_INT(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
+ PY_DICT_ADD_INT(GL_MAX_VERTEX_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_POINT_SPRITE_COORD_ORIGIN);
+ PY_DICT_ADD_INT(GL_SAMPLER_1D);
+ PY_DICT_ADD_INT(GL_SAMPLER_1D_SHADOW);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_SHADOW);
+ PY_DICT_ADD_INT(GL_SAMPLER_3D);
+ PY_DICT_ADD_INT(GL_SAMPLER_CUBE);
+ PY_DICT_ADD_INT(GL_SHADER_SOURCE_LENGTH);
+ PY_DICT_ADD_INT(GL_SHADER_TYPE);
+ PY_DICT_ADD_INT(GL_SHADING_LANGUAGE_VERSION);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_FAIL);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_FUNC);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_PASS_DEPTH_FAIL);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_PASS_DEPTH_PASS);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_REF);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_VALUE_MASK);
+ PY_DICT_ADD_INT(GL_STENCIL_BACK_WRITEMASK);
+ PY_DICT_ADD_INT(GL_UPPER_LEFT);
+ PY_DICT_ADD_INT(GL_VALIDATE_STATUS);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_ENABLED);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_NORMALIZED);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_POINTER);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_SIZE);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_STRIDE);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_TYPE);
+ PY_DICT_ADD_INT(GL_VERTEX_PROGRAM_POINT_SIZE);
+ PY_DICT_ADD_INT(GL_VERTEX_SHADER);
+ }
+
+ /* GL_VERSION_2_1 */
+ {
+ PY_DICT_ADD_INT(GL_COMPRESSED_SRGB);
+ PY_DICT_ADD_INT(GL_COMPRESSED_SRGB_ALPHA);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT2x3);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT2x4);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT3x2);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT3x4);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT4x2);
+ PY_DICT_ADD_INT(GL_FLOAT_MAT4x3);
+ PY_DICT_ADD_INT(GL_PIXEL_PACK_BUFFER);
+ PY_DICT_ADD_INT(GL_PIXEL_PACK_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_PIXEL_UNPACK_BUFFER);
+ PY_DICT_ADD_INT(GL_PIXEL_UNPACK_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_SRGB);
+ PY_DICT_ADD_INT(GL_SRGB8);
+ PY_DICT_ADD_INT(GL_SRGB8_ALPHA8);
+ PY_DICT_ADD_INT(GL_SRGB_ALPHA);
+ }
+
+ /* GL_VERSION_3_0 */
+ {
+ PY_DICT_ADD_INT(GL_BGRA_INTEGER);
+ PY_DICT_ADD_INT(GL_BGR_INTEGER);
+ PY_DICT_ADD_INT(GL_BLUE_INTEGER);
+ PY_DICT_ADD_INT(GL_BUFFER_ACCESS_FLAGS);
+ PY_DICT_ADD_INT(GL_BUFFER_MAP_LENGTH);
+ PY_DICT_ADD_INT(GL_BUFFER_MAP_OFFSET);
+ PY_DICT_ADD_INT(GL_CLAMP_READ_COLOR);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE0);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE1);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE2);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE3);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE4);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE5);
#if 0
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE6);
- PY_DICT_ADD_INT(GL_CLIP_DISTANCE7);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE6);
+ PY_DICT_ADD_INT(GL_CLIP_DISTANCE7);
#endif
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT0);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT1);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT2);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT3);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT4);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT5);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT6);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT7);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT8);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT9);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT10);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT11);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT12);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT13);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT14);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT15);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT0);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT1);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT2);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT3);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT4);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT5);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT6);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT7);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT8);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT9);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT10);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT11);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT12);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT13);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT14);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT15);
#if 0
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT16);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT17);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT18);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT19);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT20);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT21);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT22);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT23);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT24);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT25);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT26);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT27);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT28);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT29);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT30);
- PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT31);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT16);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT17);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT18);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT19);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT20);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT21);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT22);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT23);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT24);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT25);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT26);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT27);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT28);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT29);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT30);
+ PY_DICT_ADD_INT(GL_COLOR_ATTACHMENT31);
#endif
- PY_DICT_ADD_INT(GL_COMPARE_REF_TO_TEXTURE);
- PY_DICT_ADD_INT(GL_COMPRESSED_RED);
- PY_DICT_ADD_INT(GL_COMPRESSED_RED_RGTC1);
- PY_DICT_ADD_INT(GL_COMPRESSED_RG);
- PY_DICT_ADD_INT(GL_COMPRESSED_RG_RGTC2);
- PY_DICT_ADD_INT(GL_COMPRESSED_SIGNED_RED_RGTC1);
- PY_DICT_ADD_INT(GL_COMPRESSED_SIGNED_RG_RGTC2);
- PY_DICT_ADD_INT(GL_CONTEXT_FLAGS);
- PY_DICT_ADD_INT(GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT);
- PY_DICT_ADD_INT(GL_DEPTH24_STENCIL8);
- PY_DICT_ADD_INT(GL_DEPTH32F_STENCIL8);
- PY_DICT_ADD_INT(GL_DEPTH_ATTACHMENT);
- PY_DICT_ADD_INT(GL_DEPTH_COMPONENT32F);
- PY_DICT_ADD_INT(GL_DEPTH_STENCIL);
- PY_DICT_ADD_INT(GL_DEPTH_STENCIL_ATTACHMENT);
- PY_DICT_ADD_INT(GL_DRAW_FRAMEBUFFER);
- PY_DICT_ADD_INT(GL_DRAW_FRAMEBUFFER_BINDING);
- PY_DICT_ADD_INT(GL_FIXED_ONLY);
- PY_DICT_ADD_INT(GL_FLOAT_32_UNSIGNED_INT_24_8_REV);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_BINDING);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_COMPLETE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_DEFAULT);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_SRGB);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_UNDEFINED);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_UNSUPPORTED);
- PY_DICT_ADD_INT(GL_GREEN_INTEGER);
- PY_DICT_ADD_INT(GL_HALF_FLOAT);
- PY_DICT_ADD_INT(GL_INDEX);
- PY_DICT_ADD_INT(GL_INTERLEAVED_ATTRIBS);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_1D);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_1D_ARRAY);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_2D);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_ARRAY);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_3D);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_CUBE);
- PY_DICT_ADD_INT(GL_INVALID_FRAMEBUFFER_OPERATION);
- PY_DICT_ADD_INT(GL_MAJOR_VERSION);
- PY_DICT_ADD_INT(GL_MAP_FLUSH_EXPLICIT_BIT);
- PY_DICT_ADD_INT(GL_MAP_INVALIDATE_BUFFER_BIT);
- PY_DICT_ADD_INT(GL_MAP_INVALIDATE_RANGE_BIT);
- PY_DICT_ADD_INT(GL_MAP_READ_BIT);
- PY_DICT_ADD_INT(GL_MAP_UNSYNCHRONIZED_BIT);
- PY_DICT_ADD_INT(GL_MAP_WRITE_BIT);
- PY_DICT_ADD_INT(GL_MAX_ARRAY_TEXTURE_LAYERS);
- PY_DICT_ADD_INT(GL_MAX_CLIP_DISTANCES);
- PY_DICT_ADD_INT(GL_MAX_COLOR_ATTACHMENTS);
- PY_DICT_ADD_INT(GL_MAX_PROGRAM_TEXEL_OFFSET);
- PY_DICT_ADD_INT(GL_MAX_RENDERBUFFER_SIZE);
- PY_DICT_ADD_INT(GL_MAX_SAMPLES);
- PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);
- PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_VARYING_COMPONENTS);
- PY_DICT_ADD_INT(GL_MINOR_VERSION);
- PY_DICT_ADD_INT(GL_MIN_PROGRAM_TEXEL_OFFSET);
- PY_DICT_ADD_INT(GL_NUM_EXTENSIONS);
- PY_DICT_ADD_INT(GL_PRIMITIVES_GENERATED);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_1D_ARRAY);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_ARRAY);
- PY_DICT_ADD_INT(GL_QUERY_BY_REGION_NO_WAIT);
- PY_DICT_ADD_INT(GL_QUERY_BY_REGION_WAIT);
- PY_DICT_ADD_INT(GL_QUERY_NO_WAIT);
- PY_DICT_ADD_INT(GL_QUERY_WAIT);
- PY_DICT_ADD_INT(GL_R11F_G11F_B10F);
- PY_DICT_ADD_INT(GL_R16);
- PY_DICT_ADD_INT(GL_R16F);
- PY_DICT_ADD_INT(GL_R16I);
- PY_DICT_ADD_INT(GL_R16UI);
- PY_DICT_ADD_INT(GL_R32F);
- PY_DICT_ADD_INT(GL_R32I);
- PY_DICT_ADD_INT(GL_R32UI);
- PY_DICT_ADD_INT(GL_R8);
- PY_DICT_ADD_INT(GL_R8I);
- PY_DICT_ADD_INT(GL_R8UI);
- PY_DICT_ADD_INT(GL_RASTERIZER_DISCARD);
- PY_DICT_ADD_INT(GL_READ_FRAMEBUFFER);
- PY_DICT_ADD_INT(GL_READ_FRAMEBUFFER_BINDING);
- PY_DICT_ADD_INT(GL_RED_INTEGER);
- PY_DICT_ADD_INT(GL_RENDERBUFFER);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_ALPHA_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_BINDING);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_BLUE_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_DEPTH_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_GREEN_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_HEIGHT);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_INTERNAL_FORMAT);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_RED_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_SAMPLES);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_STENCIL_SIZE);
- PY_DICT_ADD_INT(GL_RENDERBUFFER_WIDTH);
- PY_DICT_ADD_INT(GL_RG);
- PY_DICT_ADD_INT(GL_RG16);
- PY_DICT_ADD_INT(GL_RG16F);
- PY_DICT_ADD_INT(GL_RG16I);
- PY_DICT_ADD_INT(GL_RG16UI);
- PY_DICT_ADD_INT(GL_RG32F);
- PY_DICT_ADD_INT(GL_RG32I);
- PY_DICT_ADD_INT(GL_RG32UI);
- PY_DICT_ADD_INT(GL_RG8);
- PY_DICT_ADD_INT(GL_RG8I);
- PY_DICT_ADD_INT(GL_RG8UI);
- PY_DICT_ADD_INT(GL_RGB16F);
- PY_DICT_ADD_INT(GL_RGB16I);
- PY_DICT_ADD_INT(GL_RGB16UI);
- PY_DICT_ADD_INT(GL_RGB32F);
- PY_DICT_ADD_INT(GL_RGB32I);
- PY_DICT_ADD_INT(GL_RGB32UI);
- PY_DICT_ADD_INT(GL_RGB8I);
- PY_DICT_ADD_INT(GL_RGB8UI);
- PY_DICT_ADD_INT(GL_RGB9_E5);
- PY_DICT_ADD_INT(GL_RGBA16F);
- PY_DICT_ADD_INT(GL_RGBA16I);
- PY_DICT_ADD_INT(GL_RGBA16UI);
- PY_DICT_ADD_INT(GL_RGBA32F);
- PY_DICT_ADD_INT(GL_RGBA32I);
- PY_DICT_ADD_INT(GL_RGBA32UI);
- PY_DICT_ADD_INT(GL_RGBA8I);
- PY_DICT_ADD_INT(GL_RGBA8UI);
- PY_DICT_ADD_INT(GL_RGBA_INTEGER);
- PY_DICT_ADD_INT(GL_RGB_INTEGER);
- PY_DICT_ADD_INT(GL_RG_INTEGER);
- PY_DICT_ADD_INT(GL_SAMPLER_1D_ARRAY);
- PY_DICT_ADD_INT(GL_SAMPLER_1D_ARRAY_SHADOW);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_ARRAY);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_ARRAY_SHADOW);
- PY_DICT_ADD_INT(GL_SAMPLER_CUBE_SHADOW);
- PY_DICT_ADD_INT(GL_SEPARATE_ATTRIBS);
- PY_DICT_ADD_INT(GL_STENCIL_ATTACHMENT);
- PY_DICT_ADD_INT(GL_STENCIL_INDEX1);
- PY_DICT_ADD_INT(GL_STENCIL_INDEX16);
- PY_DICT_ADD_INT(GL_STENCIL_INDEX4);
- PY_DICT_ADD_INT(GL_STENCIL_INDEX8);
- PY_DICT_ADD_INT(GL_TEXTURE_1D_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_2D_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_ALPHA_TYPE);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_1D_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_BLUE_TYPE);
- PY_DICT_ADD_INT(GL_TEXTURE_DEPTH_TYPE);
- PY_DICT_ADD_INT(GL_TEXTURE_GREEN_TYPE);
- PY_DICT_ADD_INT(GL_TEXTURE_RED_TYPE);
- PY_DICT_ADD_INT(GL_TEXTURE_SHARED_SIZE);
- PY_DICT_ADD_INT(GL_TEXTURE_STENCIL_SIZE);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_MODE);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_SIZE);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_START);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_VARYINGS);
- PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_10F_11F_11F_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_24_8);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_5_9_9_9_REV);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_1D);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_1D_ARRAY);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_3D);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_CUBE);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC2);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC3);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC4);
- PY_DICT_ADD_INT(GL_UNSIGNED_NORMALIZED);
- PY_DICT_ADD_INT(GL_VERTEX_ARRAY_BINDING);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_INTEGER);
- }
-
- /* GL_VERSION_3_1 */
- {
- PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_BLOCKS);
- PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH);
- PY_DICT_ADD_INT(GL_COPY_READ_BUFFER);
- PY_DICT_ADD_INT(GL_COPY_WRITE_BUFFER);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_RECT);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_BUFFER);
- PY_DICT_ADD_INT(GL_INVALID_INDEX);
- PY_DICT_ADD_INT(GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_COMBINED_UNIFORM_BLOCKS);
- PY_DICT_ADD_INT(GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_FRAGMENT_UNIFORM_BLOCKS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_UNIFORM_BLOCKS);
- PY_DICT_ADD_INT(GL_MAX_RECTANGLE_TEXTURE_SIZE);
- PY_DICT_ADD_INT(GL_MAX_TEXTURE_BUFFER_SIZE);
- PY_DICT_ADD_INT(GL_MAX_UNIFORM_BLOCK_SIZE);
- PY_DICT_ADD_INT(GL_MAX_UNIFORM_BUFFER_BINDINGS);
- PY_DICT_ADD_INT(GL_MAX_VERTEX_UNIFORM_BLOCKS);
- PY_DICT_ADD_INT(GL_PRIMITIVE_RESTART);
- PY_DICT_ADD_INT(GL_PRIMITIVE_RESTART_INDEX);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_RECTANGLE);
- PY_DICT_ADD_INT(GL_R16_SNORM);
- PY_DICT_ADD_INT(GL_R8_SNORM);
- PY_DICT_ADD_INT(GL_RG16_SNORM);
- PY_DICT_ADD_INT(GL_RG8_SNORM);
- PY_DICT_ADD_INT(GL_RGB16_SNORM);
- PY_DICT_ADD_INT(GL_RGB8_SNORM);
- PY_DICT_ADD_INT(GL_RGBA16_SNORM);
- PY_DICT_ADD_INT(GL_RGBA8_SNORM);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_RECT);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_RECT_SHADOW);
- PY_DICT_ADD_INT(GL_SAMPLER_BUFFER);
- PY_DICT_ADD_INT(GL_SIGNED_NORMALIZED);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_BUFFER);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_RECTANGLE);
- PY_DICT_ADD_INT(GL_TEXTURE_BUFFER);
- PY_DICT_ADD_INT(GL_TEXTURE_BUFFER_DATA_STORE_BINDING);
- PY_DICT_ADD_INT(GL_TEXTURE_RECTANGLE);
- PY_DICT_ADD_INT(GL_UNIFORM_ARRAY_STRIDE);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_BINDING);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_DATA_SIZE);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_INDEX);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_NAME_LENGTH);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER);
- PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER);
- PY_DICT_ADD_INT(GL_UNIFORM_BUFFER);
- PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_BINDING);
- PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT);
- PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_SIZE);
- PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_START);
- PY_DICT_ADD_INT(GL_UNIFORM_IS_ROW_MAJOR);
- PY_DICT_ADD_INT(GL_UNIFORM_MATRIX_STRIDE);
- PY_DICT_ADD_INT(GL_UNIFORM_NAME_LENGTH);
- PY_DICT_ADD_INT(GL_UNIFORM_OFFSET);
- PY_DICT_ADD_INT(GL_UNIFORM_SIZE);
- PY_DICT_ADD_INT(GL_UNIFORM_TYPE);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_RECT);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_BUFFER);
- }
-
- /* GL_VERSION_3_2 */
- {
- PY_DICT_ADD_INT(GL_ALREADY_SIGNALED);
- PY_DICT_ADD_INT(GL_CONDITION_SATISFIED);
- PY_DICT_ADD_INT(GL_CONTEXT_COMPATIBILITY_PROFILE_BIT);
- PY_DICT_ADD_INT(GL_CONTEXT_CORE_PROFILE_BIT);
- PY_DICT_ADD_INT(GL_CONTEXT_PROFILE_MASK);
- PY_DICT_ADD_INT(GL_DEPTH_CLAMP);
- PY_DICT_ADD_INT(GL_FIRST_VERTEX_CONVENTION);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_LAYERED);
- PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS);
- PY_DICT_ADD_INT(GL_GEOMETRY_INPUT_TYPE);
- PY_DICT_ADD_INT(GL_GEOMETRY_OUTPUT_TYPE);
- PY_DICT_ADD_INT(GL_GEOMETRY_SHADER);
- PY_DICT_ADD_INT(GL_GEOMETRY_VERTICES_OUT);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_LAST_VERTEX_CONVENTION);
- PY_DICT_ADD_INT(GL_LINES_ADJACENCY);
- PY_DICT_ADD_INT(GL_LINE_STRIP_ADJACENCY);
- PY_DICT_ADD_INT(GL_MAX_COLOR_TEXTURE_SAMPLES);
- PY_DICT_ADD_INT(GL_MAX_DEPTH_TEXTURE_SAMPLES);
- PY_DICT_ADD_INT(GL_MAX_FRAGMENT_INPUT_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_INPUT_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_OUTPUT_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_OUTPUT_VERTICES);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS);
- PY_DICT_ADD_INT(GL_MAX_INTEGER_SAMPLES);
- PY_DICT_ADD_INT(GL_MAX_SAMPLE_MASK_WORDS);
- PY_DICT_ADD_INT(GL_MAX_SERVER_WAIT_TIMEOUT);
- PY_DICT_ADD_INT(GL_MAX_VERTEX_OUTPUT_COMPONENTS);
- PY_DICT_ADD_INT(GL_OBJECT_TYPE);
- PY_DICT_ADD_INT(GL_PROGRAM_POINT_SIZE);
- PY_DICT_ADD_INT(GL_PROVOKING_VERTEX);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_SAMPLER_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_SAMPLE_MASK);
- PY_DICT_ADD_INT(GL_SAMPLE_MASK_VALUE);
- PY_DICT_ADD_INT(GL_SAMPLE_POSITION);
- PY_DICT_ADD_INT(GL_SIGNALED);
- PY_DICT_ADD_INT(GL_SYNC_CONDITION);
- PY_DICT_ADD_INT(GL_SYNC_FENCE);
- PY_DICT_ADD_INT(GL_SYNC_FLAGS);
- PY_DICT_ADD_INT(GL_SYNC_FLUSH_COMMANDS_BIT);
- PY_DICT_ADD_INT(GL_SYNC_GPU_COMMANDS_COMPLETE);
- PY_DICT_ADD_INT(GL_SYNC_STATUS);
- PY_DICT_ADD_INT(GL_TEXTURE_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_SEAMLESS);
- PY_DICT_ADD_INT(GL_TEXTURE_FIXED_SAMPLE_LOCATIONS);
- PY_DICT_ADD_INT(GL_TEXTURE_SAMPLES);
- PY_DICT_ADD_INT(GL_TIMEOUT_EXPIRED);
- PY_DICT_ADD_INT64(GL_TIMEOUT_IGNORED);
- PY_DICT_ADD_INT(GL_TRIANGLES_ADJACENCY);
- PY_DICT_ADD_INT(GL_TRIANGLE_STRIP_ADJACENCY);
- PY_DICT_ADD_INT(GL_UNSIGNALED);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE);
- PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY);
- PY_DICT_ADD_INT(GL_WAIT_FAILED);
- }
-
- /* GL_VERSION_3_3 */
- {
- PY_DICT_ADD_INT(GL_ANY_SAMPLES_PASSED);
- PY_DICT_ADD_INT(GL_INT_2_10_10_10_REV);
- PY_DICT_ADD_INT(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS);
- PY_DICT_ADD_INT(GL_ONE_MINUS_SRC1_ALPHA);
- PY_DICT_ADD_INT(GL_ONE_MINUS_SRC1_COLOR);
- PY_DICT_ADD_INT(GL_RGB10_A2UI);
- PY_DICT_ADD_INT(GL_SAMPLER_BINDING);
- PY_DICT_ADD_INT(GL_SRC1_COLOR);
- PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_A);
- PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_B);
- PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_G);
- PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_R);
- PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_RGBA);
- PY_DICT_ADD_INT(GL_TIMESTAMP);
- PY_DICT_ADD_INT(GL_TIME_ELAPSED);
- PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_DIVISOR);
- }
-
- return submodule;
+ PY_DICT_ADD_INT(GL_COMPARE_REF_TO_TEXTURE);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RED);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RED_RGTC1);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RG);
+ PY_DICT_ADD_INT(GL_COMPRESSED_RG_RGTC2);
+ PY_DICT_ADD_INT(GL_COMPRESSED_SIGNED_RED_RGTC1);
+ PY_DICT_ADD_INT(GL_COMPRESSED_SIGNED_RG_RGTC2);
+ PY_DICT_ADD_INT(GL_CONTEXT_FLAGS);
+ PY_DICT_ADD_INT(GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT);
+ PY_DICT_ADD_INT(GL_DEPTH24_STENCIL8);
+ PY_DICT_ADD_INT(GL_DEPTH32F_STENCIL8);
+ PY_DICT_ADD_INT(GL_DEPTH_ATTACHMENT);
+ PY_DICT_ADD_INT(GL_DEPTH_COMPONENT32F);
+ PY_DICT_ADD_INT(GL_DEPTH_STENCIL);
+ PY_DICT_ADD_INT(GL_DEPTH_STENCIL_ATTACHMENT);
+ PY_DICT_ADD_INT(GL_DRAW_FRAMEBUFFER);
+ PY_DICT_ADD_INT(GL_DRAW_FRAMEBUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_FIXED_ONLY);
+ PY_DICT_ADD_INT(GL_FLOAT_32_UNSIGNED_INT_24_8_REV);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_COMPLETE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_DEFAULT);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_SRGB);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_UNDEFINED);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_UNSUPPORTED);
+ PY_DICT_ADD_INT(GL_GREEN_INTEGER);
+ PY_DICT_ADD_INT(GL_HALF_FLOAT);
+ PY_DICT_ADD_INT(GL_INDEX);
+ PY_DICT_ADD_INT(GL_INTERLEAVED_ATTRIBS);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_1D);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_2D);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_3D);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_CUBE);
+ PY_DICT_ADD_INT(GL_INVALID_FRAMEBUFFER_OPERATION);
+ PY_DICT_ADD_INT(GL_MAJOR_VERSION);
+ PY_DICT_ADD_INT(GL_MAP_FLUSH_EXPLICIT_BIT);
+ PY_DICT_ADD_INT(GL_MAP_INVALIDATE_BUFFER_BIT);
+ PY_DICT_ADD_INT(GL_MAP_INVALIDATE_RANGE_BIT);
+ PY_DICT_ADD_INT(GL_MAP_READ_BIT);
+ PY_DICT_ADD_INT(GL_MAP_UNSYNCHRONIZED_BIT);
+ PY_DICT_ADD_INT(GL_MAP_WRITE_BIT);
+ PY_DICT_ADD_INT(GL_MAX_ARRAY_TEXTURE_LAYERS);
+ PY_DICT_ADD_INT(GL_MAX_CLIP_DISTANCES);
+ PY_DICT_ADD_INT(GL_MAX_COLOR_ATTACHMENTS);
+ PY_DICT_ADD_INT(GL_MAX_PROGRAM_TEXEL_OFFSET);
+ PY_DICT_ADD_INT(GL_MAX_RENDERBUFFER_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_SAMPLES);
+ PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);
+ PY_DICT_ADD_INT(GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_VARYING_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MINOR_VERSION);
+ PY_DICT_ADD_INT(GL_MIN_PROGRAM_TEXEL_OFFSET);
+ PY_DICT_ADD_INT(GL_NUM_EXTENSIONS);
+ PY_DICT_ADD_INT(GL_PRIMITIVES_GENERATED);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_QUERY_BY_REGION_NO_WAIT);
+ PY_DICT_ADD_INT(GL_QUERY_BY_REGION_WAIT);
+ PY_DICT_ADD_INT(GL_QUERY_NO_WAIT);
+ PY_DICT_ADD_INT(GL_QUERY_WAIT);
+ PY_DICT_ADD_INT(GL_R11F_G11F_B10F);
+ PY_DICT_ADD_INT(GL_R16);
+ PY_DICT_ADD_INT(GL_R16F);
+ PY_DICT_ADD_INT(GL_R16I);
+ PY_DICT_ADD_INT(GL_R16UI);
+ PY_DICT_ADD_INT(GL_R32F);
+ PY_DICT_ADD_INT(GL_R32I);
+ PY_DICT_ADD_INT(GL_R32UI);
+ PY_DICT_ADD_INT(GL_R8);
+ PY_DICT_ADD_INT(GL_R8I);
+ PY_DICT_ADD_INT(GL_R8UI);
+ PY_DICT_ADD_INT(GL_RASTERIZER_DISCARD);
+ PY_DICT_ADD_INT(GL_READ_FRAMEBUFFER);
+ PY_DICT_ADD_INT(GL_READ_FRAMEBUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_RED_INTEGER);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_ALPHA_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_BLUE_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_DEPTH_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_GREEN_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_HEIGHT);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_INTERNAL_FORMAT);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_RED_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_SAMPLES);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_STENCIL_SIZE);
+ PY_DICT_ADD_INT(GL_RENDERBUFFER_WIDTH);
+ PY_DICT_ADD_INT(GL_RG);
+ PY_DICT_ADD_INT(GL_RG16);
+ PY_DICT_ADD_INT(GL_RG16F);
+ PY_DICT_ADD_INT(GL_RG16I);
+ PY_DICT_ADD_INT(GL_RG16UI);
+ PY_DICT_ADD_INT(GL_RG32F);
+ PY_DICT_ADD_INT(GL_RG32I);
+ PY_DICT_ADD_INT(GL_RG32UI);
+ PY_DICT_ADD_INT(GL_RG8);
+ PY_DICT_ADD_INT(GL_RG8I);
+ PY_DICT_ADD_INT(GL_RG8UI);
+ PY_DICT_ADD_INT(GL_RGB16F);
+ PY_DICT_ADD_INT(GL_RGB16I);
+ PY_DICT_ADD_INT(GL_RGB16UI);
+ PY_DICT_ADD_INT(GL_RGB32F);
+ PY_DICT_ADD_INT(GL_RGB32I);
+ PY_DICT_ADD_INT(GL_RGB32UI);
+ PY_DICT_ADD_INT(GL_RGB8I);
+ PY_DICT_ADD_INT(GL_RGB8UI);
+ PY_DICT_ADD_INT(GL_RGB9_E5);
+ PY_DICT_ADD_INT(GL_RGBA16F);
+ PY_DICT_ADD_INT(GL_RGBA16I);
+ PY_DICT_ADD_INT(GL_RGBA16UI);
+ PY_DICT_ADD_INT(GL_RGBA32F);
+ PY_DICT_ADD_INT(GL_RGBA32I);
+ PY_DICT_ADD_INT(GL_RGBA32UI);
+ PY_DICT_ADD_INT(GL_RGBA8I);
+ PY_DICT_ADD_INT(GL_RGBA8UI);
+ PY_DICT_ADD_INT(GL_RGBA_INTEGER);
+ PY_DICT_ADD_INT(GL_RGB_INTEGER);
+ PY_DICT_ADD_INT(GL_RG_INTEGER);
+ PY_DICT_ADD_INT(GL_SAMPLER_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_SAMPLER_1D_ARRAY_SHADOW);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_ARRAY_SHADOW);
+ PY_DICT_ADD_INT(GL_SAMPLER_CUBE_SHADOW);
+ PY_DICT_ADD_INT(GL_SEPARATE_ATTRIBS);
+ PY_DICT_ADD_INT(GL_STENCIL_ATTACHMENT);
+ PY_DICT_ADD_INT(GL_STENCIL_INDEX1);
+ PY_DICT_ADD_INT(GL_STENCIL_INDEX16);
+ PY_DICT_ADD_INT(GL_STENCIL_INDEX4);
+ PY_DICT_ADD_INT(GL_STENCIL_INDEX8);
+ PY_DICT_ADD_INT(GL_TEXTURE_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_ALPHA_TYPE);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_BLUE_TYPE);
+ PY_DICT_ADD_INT(GL_TEXTURE_DEPTH_TYPE);
+ PY_DICT_ADD_INT(GL_TEXTURE_GREEN_TYPE);
+ PY_DICT_ADD_INT(GL_TEXTURE_RED_TYPE);
+ PY_DICT_ADD_INT(GL_TEXTURE_SHARED_SIZE);
+ PY_DICT_ADD_INT(GL_TEXTURE_STENCIL_SIZE);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_MODE);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_SIZE);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_BUFFER_START);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_VARYINGS);
+ PY_DICT_ADD_INT(GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_10F_11F_11F_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_24_8);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_5_9_9_9_REV);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_1D);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_1D_ARRAY);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_3D);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_CUBE);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC2);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC3);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_VEC4);
+ PY_DICT_ADD_INT(GL_UNSIGNED_NORMALIZED);
+ PY_DICT_ADD_INT(GL_VERTEX_ARRAY_BINDING);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_INTEGER);
+ }
+
+ /* GL_VERSION_3_1 */
+ {
+ PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_BLOCKS);
+ PY_DICT_ADD_INT(GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH);
+ PY_DICT_ADD_INT(GL_COPY_READ_BUFFER);
+ PY_DICT_ADD_INT(GL_COPY_WRITE_BUFFER);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_RECT);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_BUFFER);
+ PY_DICT_ADD_INT(GL_INVALID_INDEX);
+ PY_DICT_ADD_INT(GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_COMBINED_UNIFORM_BLOCKS);
+ PY_DICT_ADD_INT(GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_FRAGMENT_UNIFORM_BLOCKS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_UNIFORM_BLOCKS);
+ PY_DICT_ADD_INT(GL_MAX_RECTANGLE_TEXTURE_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_TEXTURE_BUFFER_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_UNIFORM_BLOCK_SIZE);
+ PY_DICT_ADD_INT(GL_MAX_UNIFORM_BUFFER_BINDINGS);
+ PY_DICT_ADD_INT(GL_MAX_VERTEX_UNIFORM_BLOCKS);
+ PY_DICT_ADD_INT(GL_PRIMITIVE_RESTART);
+ PY_DICT_ADD_INT(GL_PRIMITIVE_RESTART_INDEX);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_RECTANGLE);
+ PY_DICT_ADD_INT(GL_R16_SNORM);
+ PY_DICT_ADD_INT(GL_R8_SNORM);
+ PY_DICT_ADD_INT(GL_RG16_SNORM);
+ PY_DICT_ADD_INT(GL_RG8_SNORM);
+ PY_DICT_ADD_INT(GL_RGB16_SNORM);
+ PY_DICT_ADD_INT(GL_RGB8_SNORM);
+ PY_DICT_ADD_INT(GL_RGBA16_SNORM);
+ PY_DICT_ADD_INT(GL_RGBA8_SNORM);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_RECT);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_RECT_SHADOW);
+ PY_DICT_ADD_INT(GL_SAMPLER_BUFFER);
+ PY_DICT_ADD_INT(GL_SIGNED_NORMALIZED);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_BUFFER);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_RECTANGLE);
+ PY_DICT_ADD_INT(GL_TEXTURE_BUFFER);
+ PY_DICT_ADD_INT(GL_TEXTURE_BUFFER_DATA_STORE_BINDING);
+ PY_DICT_ADD_INT(GL_TEXTURE_RECTANGLE);
+ PY_DICT_ADD_INT(GL_UNIFORM_ARRAY_STRIDE);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_BINDING);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_DATA_SIZE);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_INDEX);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_NAME_LENGTH);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER);
+ PY_DICT_ADD_INT(GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER);
+ PY_DICT_ADD_INT(GL_UNIFORM_BUFFER);
+ PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_BINDING);
+ PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT);
+ PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_SIZE);
+ PY_DICT_ADD_INT(GL_UNIFORM_BUFFER_START);
+ PY_DICT_ADD_INT(GL_UNIFORM_IS_ROW_MAJOR);
+ PY_DICT_ADD_INT(GL_UNIFORM_MATRIX_STRIDE);
+ PY_DICT_ADD_INT(GL_UNIFORM_NAME_LENGTH);
+ PY_DICT_ADD_INT(GL_UNIFORM_OFFSET);
+ PY_DICT_ADD_INT(GL_UNIFORM_SIZE);
+ PY_DICT_ADD_INT(GL_UNIFORM_TYPE);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_RECT);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_BUFFER);
+ }
+
+ /* GL_VERSION_3_2 */
+ {
+ PY_DICT_ADD_INT(GL_ALREADY_SIGNALED);
+ PY_DICT_ADD_INT(GL_CONDITION_SATISFIED);
+ PY_DICT_ADD_INT(GL_CONTEXT_COMPATIBILITY_PROFILE_BIT);
+ PY_DICT_ADD_INT(GL_CONTEXT_CORE_PROFILE_BIT);
+ PY_DICT_ADD_INT(GL_CONTEXT_PROFILE_MASK);
+ PY_DICT_ADD_INT(GL_DEPTH_CLAMP);
+ PY_DICT_ADD_INT(GL_FIRST_VERTEX_CONVENTION);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_ATTACHMENT_LAYERED);
+ PY_DICT_ADD_INT(GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS);
+ PY_DICT_ADD_INT(GL_GEOMETRY_INPUT_TYPE);
+ PY_DICT_ADD_INT(GL_GEOMETRY_OUTPUT_TYPE);
+ PY_DICT_ADD_INT(GL_GEOMETRY_SHADER);
+ PY_DICT_ADD_INT(GL_GEOMETRY_VERTICES_OUT);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_LAST_VERTEX_CONVENTION);
+ PY_DICT_ADD_INT(GL_LINES_ADJACENCY);
+ PY_DICT_ADD_INT(GL_LINE_STRIP_ADJACENCY);
+ PY_DICT_ADD_INT(GL_MAX_COLOR_TEXTURE_SAMPLES);
+ PY_DICT_ADD_INT(GL_MAX_DEPTH_TEXTURE_SAMPLES);
+ PY_DICT_ADD_INT(GL_MAX_FRAGMENT_INPUT_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_INPUT_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_OUTPUT_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_OUTPUT_VERTICES);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS);
+ PY_DICT_ADD_INT(GL_MAX_INTEGER_SAMPLES);
+ PY_DICT_ADD_INT(GL_MAX_SAMPLE_MASK_WORDS);
+ PY_DICT_ADD_INT(GL_MAX_SERVER_WAIT_TIMEOUT);
+ PY_DICT_ADD_INT(GL_MAX_VERTEX_OUTPUT_COMPONENTS);
+ PY_DICT_ADD_INT(GL_OBJECT_TYPE);
+ PY_DICT_ADD_INT(GL_PROGRAM_POINT_SIZE);
+ PY_DICT_ADD_INT(GL_PROVOKING_VERTEX);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_SAMPLER_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_SAMPLE_MASK);
+ PY_DICT_ADD_INT(GL_SAMPLE_MASK_VALUE);
+ PY_DICT_ADD_INT(GL_SAMPLE_POSITION);
+ PY_DICT_ADD_INT(GL_SIGNALED);
+ PY_DICT_ADD_INT(GL_SYNC_CONDITION);
+ PY_DICT_ADD_INT(GL_SYNC_FENCE);
+ PY_DICT_ADD_INT(GL_SYNC_FLAGS);
+ PY_DICT_ADD_INT(GL_SYNC_FLUSH_COMMANDS_BIT);
+ PY_DICT_ADD_INT(GL_SYNC_GPU_COMMANDS_COMPLETE);
+ PY_DICT_ADD_INT(GL_SYNC_STATUS);
+ PY_DICT_ADD_INT(GL_TEXTURE_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_TEXTURE_CUBE_MAP_SEAMLESS);
+ PY_DICT_ADD_INT(GL_TEXTURE_FIXED_SAMPLE_LOCATIONS);
+ PY_DICT_ADD_INT(GL_TEXTURE_SAMPLES);
+ PY_DICT_ADD_INT(GL_TIMEOUT_EXPIRED);
+ PY_DICT_ADD_INT64(GL_TIMEOUT_IGNORED);
+ PY_DICT_ADD_INT(GL_TRIANGLES_ADJACENCY);
+ PY_DICT_ADD_INT(GL_TRIANGLE_STRIP_ADJACENCY);
+ PY_DICT_ADD_INT(GL_UNSIGNALED);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE);
+ PY_DICT_ADD_INT(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY);
+ PY_DICT_ADD_INT(GL_WAIT_FAILED);
+ }
+
+ /* GL_VERSION_3_3 */
+ {
+ PY_DICT_ADD_INT(GL_ANY_SAMPLES_PASSED);
+ PY_DICT_ADD_INT(GL_INT_2_10_10_10_REV);
+ PY_DICT_ADD_INT(GL_MAX_DUAL_SOURCE_DRAW_BUFFERS);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_SRC1_ALPHA);
+ PY_DICT_ADD_INT(GL_ONE_MINUS_SRC1_COLOR);
+ PY_DICT_ADD_INT(GL_RGB10_A2UI);
+ PY_DICT_ADD_INT(GL_SAMPLER_BINDING);
+ PY_DICT_ADD_INT(GL_SRC1_COLOR);
+ PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_A);
+ PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_B);
+ PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_G);
+ PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_R);
+ PY_DICT_ADD_INT(GL_TEXTURE_SWIZZLE_RGBA);
+ PY_DICT_ADD_INT(GL_TIMESTAMP);
+ PY_DICT_ADD_INT(GL_TIME_ELAPSED);
+ PY_DICT_ADD_INT(GL_VERTEX_ATTRIB_ARRAY_DIVISOR);
+ }
+
+ return submodule;
}
static PyObject *Method_ShaderSource(PyObject *UNUSED(self), PyObject *args)
{
- unsigned int shader;
- const char *source;
+ unsigned int shader;
+ const char *source;
- if (!PyArg_ParseTuple(args, "Is", &shader, &source)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "Is", &shader, &source)) {
+ return NULL;
+ }
- glShaderSource(shader, 1, (const char **)&source, NULL);
+ glShaderSource(shader, 1, (const char **)&source, NULL);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
/** \} */
diff --git a/source/blender/python/generic/bgl.h b/source/blender/python/generic/bgl.h
index 105056be5e6..8c81dc48340 100644
--- a/source/blender/python/generic/bgl.h
+++ b/source/blender/python/generic/bgl.h
@@ -33,22 +33,21 @@ int BGL_typeSize(int type);
* For Python access to OpenGL functions requiring a pointer.
*/
typedef struct _Buffer {
- PyObject_VAR_HEAD
- PyObject *parent;
-
- int type; /* GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT */
- int ndimensions;
- int *dimensions;
-
- union {
- char *asbyte;
- short *asshort;
- int *asint;
- float *asfloat;
- double *asdouble;
-
- void *asvoid;
- } buf;
+ PyObject_VAR_HEAD PyObject *parent;
+
+ int type; /* GL_BYTE, GL_SHORT, GL_INT, GL_FLOAT */
+ int ndimensions;
+ int *dimensions;
+
+ union {
+ char *asbyte;
+ short *asshort;
+ int *asint;
+ float *asfloat;
+ double *asdouble;
+
+ void *asvoid;
+ } buf;
} Buffer;
/** The type object */
diff --git a/source/blender/python/generic/blf_py_api.c b/source/blender/python/generic/blf_py_api.c
index 9161e5d979b..a2c7c9099c1 100644
--- a/source/blender/python/generic/blf_py_api.c
+++ b/source/blender/python/generic/blf_py_api.c
@@ -29,486 +29,470 @@
#include "python_utildefines.h"
-
PyDoc_STRVAR(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 z: float\n"
-);
+ ".. 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 z: float\n");
static PyObject *py_blf_position(PyObject *UNUSED(self), PyObject *args)
{
- int fontid;
- float x, y, z;
+ int fontid;
+ float x, y, z;
- if (!PyArg_ParseTuple(args, "ifff:blf.position", &fontid, &x, &y, &z)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ifff:blf.position", &fontid, &x, &y, &z)) {
+ return NULL;
+ }
- BLF_position(fontid, x, y, z);
+ BLF_position(fontid, x, y, z);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int fontid, size, dpi;
+ int fontid, size, dpi;
- if (!PyArg_ParseTuple(args, "iii:blf.size", &fontid, &size, &dpi)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iii:blf.size", &fontid, &size, &dpi)) {
+ return NULL;
+ }
- BLF_size(fontid, size, dpi);
+ BLF_size(fontid, size, dpi);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- float aspect;
- int fontid;
+ float aspect;
+ int fontid;
- if (!PyArg_ParseTuple(args, "if:blf.aspect", &fontid, &aspect)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "if:blf.aspect", &fontid, &aspect)) {
+ return NULL;
+ }
- BLF_aspect(fontid, aspect, aspect, 1.0);
+ BLF_aspect(fontid, aspect, aspect, 1.0);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(py_blf_color_doc,
-".. function:: color(fontid, r, g, b, a)\n"
-"\n"
-" Set the color 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 r: red channel 0.0 - 1.0.\n"
-" :type r: float\n"
-" :arg g: green channel 0.0 - 1.0.\n"
-" :type g: float\n"
-" :arg b: blue channel 0.0 - 1.0.\n"
-" :type b: float\n"
-" :arg a: alpha channel 0.0 - 1.0.\n"
-" :type a: float\n"
-);
+ ".. function:: color(fontid, r, g, b, a)\n"
+ "\n"
+ " Set the color 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 r: red channel 0.0 - 1.0.\n"
+ " :type r: float\n"
+ " :arg g: green channel 0.0 - 1.0.\n"
+ " :type g: float\n"
+ " :arg b: blue channel 0.0 - 1.0.\n"
+ " :type b: float\n"
+ " :arg a: alpha channel 0.0 - 1.0.\n"
+ " :type a: float\n");
static PyObject *py_blf_color(PyObject *UNUSED(self), PyObject *args)
{
- int fontid;
- float rgba[4];
+ int fontid;
+ float rgba[4];
- if (!PyArg_ParseTuple(
- args, "iffff:blf.color",
- &fontid, &rgba[0], &rgba[1], &rgba[2], &rgba[3]))
- {
- return NULL;
- }
+ if (!PyArg_ParseTuple(
+ args, "iffff:blf.color", &fontid, &rgba[0], &rgba[1], &rgba[2], &rgba[3])) {
+ return NULL;
+ }
- BLF_color4fv(fontid, rgba);
+ BLF_color4fv(fontid, rgba);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
#if BLF_BLUR_ENABLE
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int blur, fontid;
+ int blur, fontid;
- if (!PyArg_ParseTuple(args, "ii:blf.blur", &fontid, &blur)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ii:blf.blur", &fontid, &blur)) {
+ return NULL;
+ }
- BLF_blur(fontid, blur);
+ BLF_blur(fontid, blur);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
#endif
-
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- const char *text;
- int text_length;
- int fontid;
+ const char *text;
+ int text_length;
+ int fontid;
- if (!PyArg_ParseTuple(args, "is#:blf.draw", &fontid, &text, &text_length)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "is#:blf.draw", &fontid, &text, &text_length)) {
+ return NULL;
+ }
- BLF_draw(fontid, text, (unsigned int)text_length);
+ BLF_draw(fontid, text, (unsigned int)text_length);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(py_blf_dimensions_doc,
-".. function:: dimensions(fontid, text)\n"
-"\n"
-" Return the width and height 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"
-);
+ ".. function:: dimensions(fontid, text)\n"
+ "\n"
+ " Return the width and height 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 *UNUSED(self), PyObject *args)
{
- const 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, INT_MAX, &r_width, &r_height);
-
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- PyFloat_FromDouble(r_width),
- PyFloat_FromDouble(r_height));
- return ret;
+ const 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, INT_MAX, &r_width, &r_height);
+
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, PyFloat_FromDouble(r_width), PyFloat_FromDouble(r_height));
+ return ret;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- float xmin, ymin, xmax, ymax;
- int fontid;
+ float xmin, ymin, xmax, ymax;
+ int fontid;
- if (!PyArg_ParseTuple(args, "iffff:blf.clipping", &fontid, &xmin, &ymin, &xmax, &ymax)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iffff:blf.clipping", &fontid, &xmin, &ymin, &xmax, &ymax)) {
+ return NULL;
+ }
- BLF_clipping(fontid, xmin, ymin, xmax, ymax);
+ BLF_clipping(fontid, xmin, ymin, xmax, ymax);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(py_blf_word_wrap_doc,
-".. function:: word_wrap(fontid, wrap_width)\n"
-"\n"
-" Set the wrap width, enable/disable using WORD_WRAP.\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 wrap_width: The width (in pixels) to wrap words at.\n"
-" :type wrap_width: int\n"
-);
+ ".. function:: word_wrap(fontid, wrap_width)\n"
+ "\n"
+ " Set the wrap width, enable/disable using WORD_WRAP.\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 wrap_width: The width (in pixels) to wrap words at.\n"
+ " :type wrap_width: int\n");
static PyObject *py_blf_word_wrap(PyObject *UNUSED(self), PyObject *args)
{
- int wrap_width;
- int fontid;
+ int wrap_width;
+ int fontid;
- if (!PyArg_ParseTuple(args, "ii:blf.word_wrap", &fontid, &wrap_width)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ii:blf.word_wrap", &fontid, &wrap_width)) {
+ return NULL;
+ }
- BLF_wordwrap(fontid, wrap_width);
+ BLF_wordwrap(fontid, wrap_width);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int option, fontid;
+ int option, fontid;
- if (!PyArg_ParseTuple(args, "ii:blf.disable", &fontid, &option)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ii:blf.disable", &fontid, &option)) {
+ return NULL;
+ }
- BLF_disable(fontid, option);
+ BLF_disable(fontid, option);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int option, fontid;
+ int option, fontid;
- if (!PyArg_ParseTuple(args, "ii:blf.enable", &fontid, &option)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ii:blf.enable", &fontid, &option)) {
+ return NULL;
+ }
- BLF_enable(fontid, option);
+ BLF_enable(fontid, option);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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 angle: float\n"
-);
+ ".. 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 angle: float\n");
static PyObject *py_blf_rotation(PyObject *UNUSED(self), PyObject *args)
{
- float angle;
- int fontid;
+ float angle;
+ int fontid;
- if (!PyArg_ParseTuple(args, "if:blf.rotation", &fontid, &angle)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "if:blf.rotation", &fontid, &angle)) {
+ return NULL;
+ }
- BLF_rotation(fontid, angle);
+ BLF_rotation(fontid, angle);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int level, fontid;
- float rgba[4];
+ int level, fontid;
+ float rgba[4];
- if (!PyArg_ParseTuple(
- args, "iiffff:blf.shadow",
- &fontid, &level, &rgba[0], &rgba[1], &rgba[2], &rgba[3]))
- {
- return NULL;
- }
+ if (!PyArg_ParseTuple(
+ args, "iiffff:blf.shadow", &fontid, &level, &rgba[0], &rgba[1], &rgba[2], &rgba[3])) {
+ 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;
- }
+ 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, rgba);
+ BLF_shadow(fontid, level, rgba);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- int x, y, fontid;
+ int x, y, fontid;
- if (!PyArg_ParseTuple(args, "iii:blf.shadow_offset", &fontid, &x, &y)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iii:blf.shadow_offset", &fontid, &x, &y)) {
+ return NULL;
+ }
- BLF_shadow_offset(fontid, x, y);
+ BLF_shadow_offset(fontid, x, y);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(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"
-);
+ ".. 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 *UNUSED(self), PyObject *args)
{
- const char *filename;
+ const char *filename;
- if (!PyArg_ParseTuple(args, "s:blf.load", &filename)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:blf.load", &filename)) {
+ return NULL;
+ }
- return PyLong_FromLong(BLF_load(filename));
+ return PyLong_FromLong(BLF_load(filename));
}
PyDoc_STRVAR(py_blf_unload_doc,
-".. function:: unload(filename)\n"
-"\n"
-" Unload an existing font.\n"
-"\n"
-" :arg filename: the filename of the font.\n"
-" :type filename: string\n"
-);
+ ".. function:: unload(filename)\n"
+ "\n"
+ " Unload an existing font.\n"
+ "\n"
+ " :arg filename: the filename of the font.\n"
+ " :type filename: string\n");
static PyObject *py_blf_unload(PyObject *UNUSED(self), PyObject *args)
{
- const char *filename;
+ const char *filename;
- if (!PyArg_ParseTuple(args, "s:blf.unload", &filename)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:blf.unload", &filename)) {
+ return NULL;
+ }
- BLF_unload(filename);
+ BLF_unload(filename);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/*----------------------------MODULE INIT-------------------------*/
static PyMethodDef BLF_methods[] = {
- {"aspect", (PyCFunction) py_blf_aspect, METH_VARARGS, py_blf_aspect_doc},
+ {"aspect", (PyCFunction)py_blf_aspect, METH_VARARGS, py_blf_aspect_doc},
#if BLF_BLUR_ENABLE
- {"blur", (PyCFunction) py_blf_blur, METH_VARARGS, py_blf_blur_doc},
+ {"blur", (PyCFunction)py_blf_blur, METH_VARARGS, py_blf_blur_doc},
#endif
- {"clipping", (PyCFunction) py_blf_clipping, METH_VARARGS, py_blf_clipping_doc},
- {"word_wrap", (PyCFunction) py_blf_word_wrap, METH_VARARGS, py_blf_word_wrap_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},
- {"color", (PyCFunction) py_blf_color, METH_VARARGS, py_blf_color_doc},
- {"load", (PyCFunction) py_blf_load, METH_VARARGS, py_blf_load_doc},
- {"unload", (PyCFunction) py_blf_unload, METH_VARARGS, py_blf_unload_doc},
- {NULL, NULL, 0, NULL},
+ {"clipping", (PyCFunction)py_blf_clipping, METH_VARARGS, py_blf_clipping_doc},
+ {"word_wrap", (PyCFunction)py_blf_word_wrap, METH_VARARGS, py_blf_word_wrap_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},
+ {"color", (PyCFunction)py_blf_color, METH_VARARGS, py_blf_color_doc},
+ {"load", (PyCFunction)py_blf_load, METH_VARARGS, py_blf_load_doc},
+ {"unload", (PyCFunction)py_blf_unload, METH_VARARGS, py_blf_unload_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(BLF_doc,
-"This module provides access to blenders text drawing functions."
-);
+PyDoc_STRVAR(BLF_doc, "This module provides access to blenders text drawing functions.");
static struct PyModuleDef BLF_module_def = {
- PyModuleDef_HEAD_INIT,
- "blf", /* m_name */
- BLF_doc, /* m_doc */
- 0, /* m_size */
- BLF_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "blf", /* m_name */
+ BLF_doc, /* m_doc */
+ 0, /* m_size */
+ BLF_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit_blf(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BLF_module_def);
+ submodule = PyModule_Create(&BLF_module_def);
- 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);
- PyModule_AddIntConstant(submodule, "WORD_WRAP", BLF_WORD_WRAP);
- PyModule_AddIntConstant(submodule, "MONOCHROME", BLF_MONOCHROME);
+ 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);
+ PyModule_AddIntConstant(submodule, "WORD_WRAP", BLF_WORD_WRAP);
+ PyModule_AddIntConstant(submodule, "MONOCHROME", BLF_MONOCHROME);
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/generic/blf_py_api.h b/source/blender/python/generic/blf_py_api.h
index ba816016b4f..d55dd85854e 100644
--- a/source/blender/python/generic/blf_py_api.h
+++ b/source/blender/python/generic/blf_py_api.h
@@ -23,4 +23,4 @@
PyObject *BPyInit_blf(void);
-#endif /* __BLF_PY_API_H__ */
+#endif /* __BLF_PY_API_H__ */
diff --git a/source/blender/python/generic/bpy_internal_import.c b/source/blender/python/generic/bpy_internal_import.c
index 0baa4008f2d..2df828d89e0 100644
--- a/source/blender/python/generic/bpy_internal_import.c
+++ b/source/blender/python/generic/bpy_internal_import.c
@@ -24,7 +24,6 @@
* This should eventually be replaced by import hooks (pep 302).
*/
-
#include <Python.h>
#include <stddef.h>
@@ -39,18 +38,18 @@
#include "BKE_main.h"
/* UNUSED */
-#include "BKE_text.h" /* txt_to_buf */
+#include "BKE_text.h" /* txt_to_buf */
#include "py_capi_utils.h"
-#include "bpy_internal_import.h" /* own include */
+#include "bpy_internal_import.h" /* own include */
static Main *bpy_import_main = NULL;
static ListBase bpy_import_main_list;
static PyMethodDef bpy_import_meth;
static PyMethodDef bpy_reload_meth;
-static PyObject *imp_reload_orig = NULL;
+static PyObject *imp_reload_orig = NULL;
/* 'builtins' is most likely PyEval_GetBuiltins() */
@@ -68,304 +67,309 @@ static PyObject *imp_reload_orig = NULL;
*/
void bpy_import_init(PyObject *builtins)
{
- PyObject *item;
- PyObject *mod;
-
- PyDict_SetItemString(builtins, "__import__", item = PyCFunction_New(&bpy_import_meth, NULL)); Py_DECREF(item);
-
- /* move reload here
- * XXX, use import hooks */
- mod = PyImport_ImportModuleLevel("importlib", NULL, NULL, NULL, 0);
- if (mod) {
- PyObject *mod_dict = PyModule_GetDict(mod);
-
- /* blender owns the function */
- imp_reload_orig = PyDict_GetItemString(mod_dict, "reload");
- Py_INCREF(imp_reload_orig);
-
- PyDict_SetItemString(mod_dict, "reload", item = PyCFunction_New(&bpy_reload_meth, NULL)); Py_DECREF(item);
- Py_DECREF(mod);
- }
- else {
- BLI_assert(!"unable to load 'importlib' module.");
- }
+ PyObject *item;
+ PyObject *mod;
+
+ PyDict_SetItemString(builtins, "__import__", item = PyCFunction_New(&bpy_import_meth, NULL));
+ Py_DECREF(item);
+
+ /* move reload here
+ * XXX, use import hooks */
+ mod = PyImport_ImportModuleLevel("importlib", NULL, NULL, NULL, 0);
+ if (mod) {
+ PyObject *mod_dict = PyModule_GetDict(mod);
+
+ /* blender owns the function */
+ imp_reload_orig = PyDict_GetItemString(mod_dict, "reload");
+ Py_INCREF(imp_reload_orig);
+
+ PyDict_SetItemString(mod_dict, "reload", item = PyCFunction_New(&bpy_reload_meth, NULL));
+ Py_DECREF(item);
+ Py_DECREF(mod);
+ }
+ else {
+ BLI_assert(!"unable to load 'importlib' module.");
+ }
}
-
static void free_compiled_text(Text *text)
{
- if (text->compiled) {
- Py_DECREF((PyObject *)text->compiled);
- }
- text->compiled = NULL;
+ if (text->compiled) {
+ Py_DECREF((PyObject *)text->compiled);
+ }
+ text->compiled = NULL;
}
struct Main *bpy_import_main_get(void)
{
- return bpy_import_main;
+ return bpy_import_main;
}
void bpy_import_main_set(struct Main *maggie)
{
- bpy_import_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, size_t fn_len, Text *text)
{
- BLI_snprintf(fn, fn_len, "%s%c%s", ID_BLEND_PATH(bpy_import_main, &text->id), SEP, text->id.name + 2);
+ BLI_snprintf(
+ fn, fn_len, "%s%c%s", ID_BLEND_PATH(bpy_import_main, &text->id), SEP, text->id.name + 2);
}
bool bpy_text_compile(Text *text)
{
- char fn_dummy[FILE_MAX];
- PyObject *fn_dummy_py;
- char *buf;
+ char fn_dummy[FILE_MAX];
+ PyObject *fn_dummy_py;
+ char *buf;
- bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
+ bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
- /* if previously compiled, free the object */
- free_compiled_text(text);
+ /* if previously compiled, free the object */
+ free_compiled_text(text);
- fn_dummy_py = PyC_UnicodeFromByte(fn_dummy);
+ fn_dummy_py = PyC_UnicodeFromByte(fn_dummy);
- buf = txt_to_buf(text);
- text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1);
- MEM_freeN(buf);
+ buf = txt_to_buf(text);
+ text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1);
+ MEM_freeN(buf);
- Py_DECREF(fn_dummy_py);
+ Py_DECREF(fn_dummy_py);
- if (PyErr_Occurred()) {
- PyErr_Print();
- PyErr_Clear();
- PySys_SetObject("last_traceback", NULL);
- free_compiled_text(text);
- return false;
- }
- else {
- return true;
- }
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ PyErr_Clear();
+ PySys_SetObject("last_traceback", NULL);
+ free_compiled_text(text);
+ return false;
+ }
+ else {
+ return true;
+ }
}
PyObject *bpy_text_import(Text *text)
{
- char modulename[MAX_ID_NAME + 2];
- int len;
-
- if (!text->compiled) {
- if (bpy_text_compile(text) == false) {
- return NULL;
- }
- }
-
- len = strlen(text->id.name + 2);
- BLI_strncpy(modulename, text->id.name + 2, len);
- modulename[len - 3] = '\0'; /* remove .py */
- return PyImport_ExecCodeModule(modulename, text->compiled);
+ char modulename[MAX_ID_NAME + 2];
+ int len;
+
+ if (!text->compiled) {
+ if (bpy_text_compile(text) == false) {
+ return NULL;
+ }
+ }
+
+ len = strlen(text->id.name + 2);
+ BLI_strncpy(modulename, text->id.name + 2, len);
+ modulename[len - 3] = '\0'; /* remove .py */
+ return PyImport_ExecCodeModule(modulename, text->compiled);
}
PyObject *bpy_text_import_name(const char *name, int *found)
{
- Text *text;
- char txtname[MAX_ID_NAME - 2];
- int namelen = strlen(name);
-//XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN;
- Main *maggie = bpy_import_main;
-
- *found = 0;
-
- if (!maggie) {
- printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
- return NULL;
- }
-
- /* we know this cant be importable, the name is too long for blender! */
- if (namelen >= (MAX_ID_NAME - 2) - 3) {
- return NULL;
- }
-
- memcpy(txtname, name, namelen);
- memcpy(&txtname[namelen], ".py", 4);
-
- text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2);
-
- if (text) {
- *found = 1;
- return bpy_text_import(text);
- }
-
- /* If we still haven't found the module try additional modules form bpy_import_main_list */
- maggie = bpy_import_main_list.first;
- while (maggie && !text) {
- text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2);
- maggie = maggie->next;
- }
-
- if (!text) {
- return NULL;
- }
- else {
- *found = 1;
- }
-
- return bpy_text_import(text);
+ Text *text;
+ char txtname[MAX_ID_NAME - 2];
+ int namelen = strlen(name);
+ //XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN;
+ Main *maggie = bpy_import_main;
+
+ *found = 0;
+
+ if (!maggie) {
+ printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
+ return NULL;
+ }
+
+ /* we know this cant be importable, the name is too long for blender! */
+ if (namelen >= (MAX_ID_NAME - 2) - 3) {
+ return NULL;
+ }
+
+ memcpy(txtname, name, namelen);
+ memcpy(&txtname[namelen], ".py", 4);
+
+ text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2);
+
+ if (text) {
+ *found = 1;
+ return bpy_text_import(text);
+ }
+
+ /* If we still haven't found the module try additional modules form bpy_import_main_list */
+ maggie = bpy_import_main_list.first;
+ while (maggie && !text) {
+ text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2);
+ maggie = maggie->next;
+ }
+
+ if (!text) {
+ return NULL;
+ }
+ else {
+ *found = 1;
+ }
+
+ return bpy_text_import(text);
}
-
/*
* find in-memory module and recompile
*/
PyObject *bpy_text_reimport(PyObject *module, int *found)
{
- Text *text;
- const char *name;
- const char *filepath;
-//XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN;
- Main *maggie = bpy_import_main;
-
- if (!maggie) {
- printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
- return NULL;
- }
-
- *found = 0;
-
- /* get name, filename from the module itself */
- if ((name = PyModule_GetName(module)) == NULL) {
- return NULL;
- }
-
- {
- PyObject *module_file = PyModule_GetFilenameObject(module);
- if (module_file == NULL) {
- return NULL;
- }
- filepath = _PyUnicode_AsString(module_file);
- Py_DECREF(module_file);
- if (filepath == NULL) {
- return NULL;
- }
- }
-
- /* look up the text object */
- text = BLI_findstring(&maggie->texts, BLI_path_basename(filepath), offsetof(ID, name) + 2);
-
- /* uh-oh.... didn't find it */
- if (!text) {
- return NULL;
- }
- else {
- *found = 1;
- }
-
- if (bpy_text_compile(text) == false) {
- return NULL;
- }
-
- /* make into a module */
- return PyImport_ExecCodeModule(name, text->compiled);
+ Text *text;
+ const char *name;
+ const char *filepath;
+ //XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN;
+ Main *maggie = bpy_import_main;
+
+ if (!maggie) {
+ printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
+ return NULL;
+ }
+
+ *found = 0;
+
+ /* get name, filename from the module itself */
+ if ((name = PyModule_GetName(module)) == NULL) {
+ return NULL;
+ }
+
+ {
+ PyObject *module_file = PyModule_GetFilenameObject(module);
+ if (module_file == NULL) {
+ return NULL;
+ }
+ filepath = _PyUnicode_AsString(module_file);
+ Py_DECREF(module_file);
+ if (filepath == NULL) {
+ return NULL;
+ }
+ }
+
+ /* look up the text object */
+ text = BLI_findstring(&maggie->texts, BLI_path_basename(filepath), offsetof(ID, name) + 2);
+
+ /* uh-oh.... didn't find it */
+ if (!text) {
+ return NULL;
+ }
+ else {
+ *found = 1;
+ }
+
+ if (bpy_text_compile(text) == false) {
+ return NULL;
+ }
+
+ /* make into a module */
+ return PyImport_ExecCodeModule(name, text->compiled);
}
-
static PyObject *blender_import(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- PyObject *exception, *err, *tb;
- const char *name;
- int found = 0;
- PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
- int level = 0; /* relative imports */
- PyObject *newmodule;
-
- static const char *_keywords[] = {"name", "globals", "locals", "fromlist", "level", NULL};
- static _PyArg_Parser _parser = {"s|OOOi:bpy_import_meth", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &name, &globals, &locals, &fromlist, &level))
- {
- return NULL;
- }
-
- /* import existing builtin modules or modules that have been imported already */
- newmodule = PyImport_ImportModuleLevel(name, globals, locals, fromlist, level);
-
- if (newmodule) {
- return newmodule;
- }
-
- PyErr_Fetch(&exception, &err, &tb); /* get the python error in case we cant import as blender text either */
-
- /* importing from existing modules failed, see if we have this module as blender text */
- newmodule = bpy_text_import_name(name, &found);
-
- if (newmodule) { /* found module as blender text, ignore above exception */
- PyErr_Clear();
- Py_XDECREF(exception);
- Py_XDECREF(err);
- Py_XDECREF(tb);
- /* printf("imported from text buffer...\n"); */
- }
- else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
- Py_XDECREF(exception);
- Py_XDECREF(err);
- Py_XDECREF(tb);
- return NULL;
- }
- else {
- /* no blender text was found that could import the module
- * reuse the original error from PyImport_ImportModuleEx */
- PyErr_Restore(exception, err, tb);
- }
- return newmodule;
+ PyObject *exception, *err, *tb;
+ const char *name;
+ int found = 0;
+ PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
+ int level = 0; /* relative imports */
+ PyObject *newmodule;
+
+ static const char *_keywords[] = {"name", "globals", "locals", "fromlist", "level", NULL};
+ static _PyArg_Parser _parser = {"s|OOOi:bpy_import_meth", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &name, &globals, &locals, &fromlist, &level)) {
+ return NULL;
+ }
+
+ /* import existing builtin modules or modules that have been imported already */
+ newmodule = PyImport_ImportModuleLevel(name, globals, locals, fromlist, level);
+
+ if (newmodule) {
+ return newmodule;
+ }
+
+ PyErr_Fetch(&exception,
+ &err,
+ &tb); /* get the python error in case we cant import as blender text either */
+
+ /* importing from existing modules failed, see if we have this module as blender text */
+ newmodule = bpy_text_import_name(name, &found);
+
+ if (newmodule) { /* found module as blender text, ignore above exception */
+ PyErr_Clear();
+ Py_XDECREF(exception);
+ Py_XDECREF(err);
+ Py_XDECREF(tb);
+ /* printf("imported from text buffer...\n"); */
+ }
+ else if (found ==
+ 1) { /* blender text module failed to execute but was found, use its error message */
+ Py_XDECREF(exception);
+ Py_XDECREF(err);
+ Py_XDECREF(tb);
+ return NULL;
+ }
+ else {
+ /* no blender text was found that could import the module
+ * reuse the original error from PyImport_ImportModuleEx */
+ PyErr_Restore(exception, err, tb);
+ }
+ return newmodule;
}
-
/*
* our reload() module, to handle reloading in-memory scripts
*/
static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module)
{
- PyObject *exception, *err, *tb;
- PyObject *newmodule = NULL;
- int found = 0;
-
- /* try reimporting from file */
-
- /* in Py3.3 this just calls imp.reload() which we overwrite, causing recursive calls */
- //newmodule = PyImport_ReloadModule(module);
-
- newmodule = PyObject_CallFunctionObjArgs(imp_reload_orig, module, NULL);
-
- if (newmodule) {
- return newmodule;
- }
-
- /* no file, try importing from memory */
- PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */
-
- newmodule = bpy_text_reimport(module, &found);
- if (newmodule) { /* found module as blender text, ignore above exception */
- PyErr_Clear();
- Py_XDECREF(exception);
- Py_XDECREF(err);
- Py_XDECREF(tb);
- /* printf("imported from text buffer...\n"); */
- }
- else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
- Py_XDECREF(exception);
- Py_XDECREF(err);
- Py_XDECREF(tb);
- return NULL;
- }
- else {
- /* no blender text was found that could import the module
- * reuse the original error from PyImport_ImportModuleEx */
- PyErr_Restore(exception, err, tb);
- }
-
- return newmodule;
+ PyObject *exception, *err, *tb;
+ PyObject *newmodule = NULL;
+ int found = 0;
+
+ /* try reimporting from file */
+
+ /* in Py3.3 this just calls imp.reload() which we overwrite, causing recursive calls */
+ //newmodule = PyImport_ReloadModule(module);
+
+ newmodule = PyObject_CallFunctionObjArgs(imp_reload_orig, module, NULL);
+
+ if (newmodule) {
+ return newmodule;
+ }
+
+ /* no file, try importing from memory */
+ PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */
+
+ newmodule = bpy_text_reimport(module, &found);
+ if (newmodule) { /* found module as blender text, ignore above exception */
+ PyErr_Clear();
+ Py_XDECREF(exception);
+ Py_XDECREF(err);
+ Py_XDECREF(tb);
+ /* printf("imported from text buffer...\n"); */
+ }
+ else if (found ==
+ 1) { /* blender text module failed to execute but was found, use its error message */
+ Py_XDECREF(exception);
+ Py_XDECREF(err);
+ Py_XDECREF(tb);
+ return NULL;
+ }
+ else {
+ /* no blender text was found that could import the module
+ * reuse the original error from PyImport_ImportModuleEx */
+ PyErr_Restore(exception, err, tb);
+ }
+
+ return newmodule;
}
-static PyMethodDef bpy_import_meth = {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"};
-static PyMethodDef bpy_reload_meth = {"bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"};
+static PyMethodDef bpy_import_meth = {"bpy_import_meth",
+ (PyCFunction)blender_import,
+ METH_VARARGS | METH_KEYWORDS,
+ "blenders import"};
+static PyMethodDef bpy_reload_meth = {
+ "bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"};
diff --git a/source/blender/python/generic/bpy_internal_import.h b/source/blender/python/generic/bpy_internal_import.h
index bb02b7c2cfe..2ab535d1018 100644
--- a/source/blender/python/generic/bpy_internal_import.h
+++ b/source/blender/python/generic/bpy_internal_import.h
@@ -18,7 +18,6 @@
* \ingroup pygen
*/
-
/* Note, the BGE needs to use this too, keep it minimal */
#ifndef __BPY_INTERNAL_IMPORT_H__
@@ -26,26 +25,26 @@
/* python redefines :/ */
#ifdef _POSIX_C_SOURCE
-#undef _POSIX_C_SOURCE
+# undef _POSIX_C_SOURCE
#endif
#ifdef _XOPEN_SOURCE
-#undef _XOPEN_SOURCE
+# undef _XOPEN_SOURCE
#endif
struct Text;
void bpy_import_init(PyObject *builtins);
-bool bpy_text_compile(struct Text *text);
-PyObject *bpy_text_import(struct Text *text);
-PyObject *bpy_text_import_name(const char *name, int *found);
-PyObject *bpy_text_reimport(PyObject *module, int *found);
-/* void bpy_text_clear_modules(int clear_all);*/ /* Clear user modules */
+bool bpy_text_compile(struct Text *text);
+PyObject *bpy_text_import(struct Text *text);
+PyObject *bpy_text_import_name(const 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, size_t fn_len, struct Text *text);
struct Main *bpy_import_main_get(void);
void bpy_import_main_set(struct Main *maggie);
-#endif /* __BPY_INTERNAL_IMPORT_H__ */
+#endif /* __BPY_INTERNAL_IMPORT_H__ */
diff --git a/source/blender/python/generic/bpy_threads.c b/source/blender/python/generic/bpy_threads.c
index 1f80caa6182..2474b08180f 100644
--- a/source/blender/python/generic/bpy_threads.c
+++ b/source/blender/python/generic/bpy_threads.c
@@ -29,20 +29,20 @@
/* analogue of PyEval_SaveThread() */
BPy_ThreadStatePtr BPY_thread_save(void)
{
- PyThreadState *tstate = PyThreadState_Swap(NULL);
- /* note: tstate can be NULL when quitting Blender */
+ PyThreadState *tstate = PyThreadState_Swap(NULL);
+ /* note: tstate can be NULL when quitting Blender */
- if (tstate && PyEval_ThreadsInitialized()) {
- PyEval_ReleaseLock();
- }
+ if (tstate && PyEval_ThreadsInitialized()) {
+ PyEval_ReleaseLock();
+ }
- return (BPy_ThreadStatePtr)tstate;
+ return (BPy_ThreadStatePtr)tstate;
}
/* analogue of PyEval_RestoreThread() */
void BPY_thread_restore(BPy_ThreadStatePtr tstate)
{
- if (tstate) {
- PyEval_RestoreThread((PyThreadState *)tstate);
- }
+ if (tstate) {
+ PyEval_RestoreThread((PyThreadState *)tstate);
+ }
}
diff --git a/source/blender/python/generic/idprop_py_api.c b/source/blender/python/generic/idprop_py_api.c
index f18d02a4405..d96bef797cb 100644
--- a/source/blender/python/generic/idprop_py_api.c
+++ b/source/blender/python/generic/idprop_py_api.c
@@ -31,7 +31,7 @@
#define USE_STRING_COERCE
#ifdef USE_STRING_COERCE
-#include "py_capi_utils.h"
+# include "py_capi_utils.h"
#endif
#include "python_utildefines.h"
@@ -48,81 +48,80 @@ extern bool pyrna_id_CheckPyObject(PyObject *obj);
static PyObject *idprop_py_from_idp_string(const IDProperty *prop)
{
- if (prop->subtype == IDP_STRING_SUB_BYTE) {
- return PyBytes_FromStringAndSize(IDP_String(prop), prop->len);
- }
- else {
+ if (prop->subtype == IDP_STRING_SUB_BYTE) {
+ return PyBytes_FromStringAndSize(IDP_String(prop), prop->len);
+ }
+ else {
#ifdef USE_STRING_COERCE
- return PyC_UnicodeFromByteAndSize(IDP_Array(prop), prop->len - 1);
+ return PyC_UnicodeFromByteAndSize(IDP_Array(prop), prop->len - 1);
#else
- return PyUnicode_FromStringAndSize(IDP_String(prop), prop->len - 1);
+ return PyUnicode_FromStringAndSize(IDP_String(prop), prop->len - 1);
#endif
- }
+ }
}
static PyObject *idprop_py_from_idp_int(const IDProperty *prop)
{
- return PyLong_FromLong((long)IDP_Int(prop));
+ return PyLong_FromLong((long)IDP_Int(prop));
}
static PyObject *idprop_py_from_idp_float(const IDProperty *prop)
{
- return PyFloat_FromDouble((double)IDP_Float(prop));
+ return PyFloat_FromDouble((double)IDP_Float(prop));
}
static PyObject *idprop_py_from_idp_double(const IDProperty *prop)
{
- return PyFloat_FromDouble(IDP_Double(prop));
+ return PyFloat_FromDouble(IDP_Double(prop));
}
static PyObject *idprop_py_from_idp_group(ID *id, IDProperty *prop, IDProperty *parent)
{
- BPy_IDProperty *group = PyObject_New(BPy_IDProperty, &BPy_IDGroup_Type);
- group->id = id;
- group->prop = prop;
- group->parent = parent; /* can be NULL */
- return (PyObject *)group;
+ BPy_IDProperty *group = PyObject_New(BPy_IDProperty, &BPy_IDGroup_Type);
+ group->id = id;
+ group->prop = prop;
+ group->parent = parent; /* can be NULL */
+ return (PyObject *)group;
}
static PyObject *idprop_py_from_idp_id(IDProperty *prop)
{
- return pyrna_id_CreatePyObject(prop->data.pointer);
+ return pyrna_id_CreatePyObject(prop->data.pointer);
}
static PyObject *idprop_py_from_idp_array(ID *id, IDProperty *prop)
{
- BPy_IDProperty *array = PyObject_New(BPy_IDProperty, &BPy_IDArray_Type);
- array->id = id;
- array->prop = prop;
- return (PyObject *)array;
+ BPy_IDProperty *array = PyObject_New(BPy_IDProperty, &BPy_IDArray_Type);
+ array->id = id;
+ array->prop = prop;
+ return (PyObject *)array;
}
static PyObject *idprop_py_from_idp_idparray(ID *id, IDProperty *prop)
{
- PyObject *seq = PyList_New(prop->len);
- IDProperty *array = IDP_IDPArray(prop);
- int i;
+ PyObject *seq = PyList_New(prop->len);
+ IDProperty *array = IDP_IDPArray(prop);
+ int i;
- if (!seq) {
- PyErr_Format(PyExc_RuntimeError,
- "%s: IDP_IDPARRAY: PyList_New(%d) failed",
- __func__, prop->len);
- return NULL;
- }
+ if (!seq) {
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: IDP_IDPARRAY: PyList_New(%d) failed", __func__, prop->len);
+ return NULL;
+ }
- for (i = 0; i < prop->len; i++) {
- PyObject *wrap = BPy_IDGroup_WrapData(id, array++, prop);
+ for (i = 0; i < prop->len; i++) {
+ PyObject *wrap = BPy_IDGroup_WrapData(id, array++, prop);
- /* BPy_IDGroup_MapDataToPy sets the error */
- if (UNLIKELY(wrap == NULL)) {
- Py_DECREF(seq);
- return NULL;
- }
+ /* BPy_IDGroup_MapDataToPy sets the error */
+ if (UNLIKELY(wrap == NULL)) {
+ Py_DECREF(seq);
+ return NULL;
+ }
- PyList_SET_ITEM(seq, i, wrap);
- }
+ PyList_SET_ITEM(seq, i, wrap);
+ }
- return seq;
+ return seq;
}
/* -------------------------------------------------------------------------- */
@@ -130,236 +129,252 @@ static PyObject *idprop_py_from_idp_idparray(ID *id, IDProperty *prop)
/* use for both array and group */
static Py_hash_t BPy_IDGroup_hash(BPy_IDProperty *self)
{
- return _Py_HashPointer(self->prop);
+ return _Py_HashPointer(self->prop);
}
static PyObject *BPy_IDGroup_repr(BPy_IDProperty *self)
{
- return PyUnicode_FromFormat("<bpy id prop: owner=\"%s\", name=\"%s\", address=%p>",
- self->id ? self->id->name : "<NONE>", self->prop->name, self->prop);
+ return PyUnicode_FromFormat("<bpy id prop: owner=\"%s\", name=\"%s\", address=%p>",
+ self->id ? self->id->name : "<NONE>",
+ self->prop->name,
+ self->prop);
}
PyObject *BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent)
{
- switch (prop->type) {
- case IDP_STRING: return idprop_py_from_idp_string(prop);
- case IDP_INT: return idprop_py_from_idp_int(prop);
- case IDP_FLOAT: return idprop_py_from_idp_float(prop);
- case IDP_DOUBLE: return idprop_py_from_idp_double(prop);
- case IDP_GROUP: return idprop_py_from_idp_group(id, prop, parent);
- case IDP_ARRAY: return idprop_py_from_idp_array(id, prop);
- case IDP_IDPARRAY: return idprop_py_from_idp_idparray(id, prop); /* this could be better a internal type */
- case IDP_ID: return idprop_py_from_idp_id(prop);
- default: Py_RETURN_NONE;
- }
+ switch (prop->type) {
+ case IDP_STRING:
+ return idprop_py_from_idp_string(prop);
+ case IDP_INT:
+ return idprop_py_from_idp_int(prop);
+ case IDP_FLOAT:
+ return idprop_py_from_idp_float(prop);
+ case IDP_DOUBLE:
+ return idprop_py_from_idp_double(prop);
+ case IDP_GROUP:
+ return idprop_py_from_idp_group(id, prop, parent);
+ case IDP_ARRAY:
+ return idprop_py_from_idp_array(id, prop);
+ case IDP_IDPARRAY:
+ return idprop_py_from_idp_idparray(id, prop); /* this could be better a internal type */
+ case IDP_ID:
+ return idprop_py_from_idp_id(prop);
+ default:
+ Py_RETURN_NONE;
+ }
}
#if 0 /* UNUSED, currently assignment overwrites into new properties, rather than setting in-place */
static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject *value)
{
- switch (prop->type) {
- case IDP_STRING:
- {
- char *st;
- if (!PyUnicode_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "expected a string!");
- return -1;
- }
- /* NOTE: if this code is enabled, bytes support needs to be added */
-#ifdef USE_STRING_COERCE
- {
- int alloc_len;
- PyObject *value_coerce = NULL;
-
- st = (char *)PyC_UnicodeAsByte(value, &value_coerce);
- alloc_len = strlen(st) + 1;
-
- st = _PyUnicode_AsString(value);
- IDP_ResizeArray(prop, alloc_len);
- memcpy(IDP_Array(prop), st, alloc_len);
- Py_XDECREF(value_coerce);
- }
-#else
- st = _PyUnicode_AsString(value);
- IDP_ResizeArray(prop, strlen(st) + 1);
- strcpy(IDP_Array(prop), st);
-#endif
-
- return 0;
- }
-
- case IDP_INT:
- {
- int ivalue = PyLong_AsSsize_t(value);
- if (ivalue == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected an int type");
- return -1;
- }
- IDP_Int(prop) = ivalue;
- break;
- }
- case IDP_FLOAT:
- {
- float fvalue = (float)PyFloat_AsDouble(value);
- if (fvalue == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected a float");
- return -1;
- }
- IDP_Float(self->prop) = fvalue;
- break;
- }
- case IDP_DOUBLE:
- {
- double dvalue = PyFloat_AsDouble(value);
- if (dvalue == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected a float");
- return -1;
- }
- IDP_Double(self->prop) = dvalue;
- break;
- }
- default:
- PyErr_SetString(PyExc_AttributeError, "attempt to set read-only attribute!");
- return -1;
- }
- return 0;
+ switch (prop->type) {
+ case IDP_STRING:
+ {
+ char *st;
+ if (!PyUnicode_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "expected a string!");
+ return -1;
+ }
+ /* NOTE: if this code is enabled, bytes support needs to be added */
+# ifdef USE_STRING_COERCE
+ {
+ int alloc_len;
+ PyObject *value_coerce = NULL;
+
+ st = (char *)PyC_UnicodeAsByte(value, &value_coerce);
+ alloc_len = strlen(st) + 1;
+
+ st = _PyUnicode_AsString(value);
+ IDP_ResizeArray(prop, alloc_len);
+ memcpy(IDP_Array(prop), st, alloc_len);
+ Py_XDECREF(value_coerce);
+ }
+# else
+ st = _PyUnicode_AsString(value);
+ IDP_ResizeArray(prop, strlen(st) + 1);
+ strcpy(IDP_Array(prop), st);
+# endif
+
+ return 0;
+ }
+
+ case IDP_INT:
+ {
+ int ivalue = PyLong_AsSsize_t(value);
+ if (ivalue == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected an int type");
+ return -1;
+ }
+ IDP_Int(prop) = ivalue;
+ break;
+ }
+ case IDP_FLOAT:
+ {
+ float fvalue = (float)PyFloat_AsDouble(value);
+ if (fvalue == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected a float");
+ return -1;
+ }
+ IDP_Float(self->prop) = fvalue;
+ break;
+ }
+ case IDP_DOUBLE:
+ {
+ double dvalue = PyFloat_AsDouble(value);
+ if (dvalue == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected a float");
+ return -1;
+ }
+ IDP_Double(self->prop) = dvalue;
+ break;
+ }
+ default:
+ PyErr_SetString(PyExc_AttributeError, "attempt to set read-only attribute!");
+ return -1;
+ }
+ return 0;
}
#endif
static PyObject *BPy_IDGroup_GetName(BPy_IDProperty *self, void *UNUSED(closure))
{
- return PyUnicode_FromString(self->prop->name);
+ return PyUnicode_FromString(self->prop->name);
}
static int BPy_IDGroup_SetName(BPy_IDProperty *self, PyObject *value, void *UNUSED(closure))
{
- const char *name;
- Py_ssize_t name_size;
+ const char *name;
+ Py_ssize_t name_size;
- if (!PyUnicode_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "expected a string!");
- return -1;
- }
+ if (!PyUnicode_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "expected a string!");
+ return -1;
+ }
- name = _PyUnicode_AsStringAndSize(value, &name_size);
+ name = _PyUnicode_AsStringAndSize(value, &name_size);
- if (name_size > MAX_IDPROP_NAME) {
- PyErr_SetString(PyExc_TypeError, "string length cannot exceed 63 characters!");
- return -1;
- }
+ if (name_size > MAX_IDPROP_NAME) {
+ PyErr_SetString(PyExc_TypeError, "string length cannot exceed 63 characters!");
+ return -1;
+ }
- memcpy(self->prop->name, name, name_size);
- return 0;
+ memcpy(self->prop->name, name, name_size);
+ return 0;
}
#if 0
static PyObject *BPy_IDGroup_GetType(BPy_IDProperty *self)
{
- return PyLong_FromLong(self->prop->type);
+ return PyLong_FromLong(self->prop->type);
}
#endif
static PyGetSetDef BPy_IDGroup_getseters[] = {
- {(char *)"name", (getter)BPy_IDGroup_GetName, (setter)BPy_IDGroup_SetName, (char *)"The name of this Group.", NULL},
- {NULL, NULL, NULL, NULL, NULL},
+ {(char *)"name",
+ (getter)BPy_IDGroup_GetName,
+ (setter)BPy_IDGroup_SetName,
+ (char *)"The name of this Group.",
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL},
};
static Py_ssize_t BPy_IDGroup_Map_Len(BPy_IDProperty *self)
{
- if (self->prop->type != IDP_GROUP) {
- PyErr_SetString(PyExc_TypeError, "len() of unsized object");
- return -1;
- }
+ if (self->prop->type != IDP_GROUP) {
+ PyErr_SetString(PyExc_TypeError, "len() of unsized object");
+ return -1;
+ }
- return self->prop->len;
+ return self->prop->len;
}
static PyObject *BPy_IDGroup_Map_GetItem(BPy_IDProperty *self, PyObject *item)
{
- IDProperty *idprop;
- const char *name;
+ IDProperty *idprop;
+ const char *name;
- if (self->prop->type != IDP_GROUP) {
- PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
- return NULL;
- }
+ if (self->prop->type != IDP_GROUP) {
+ PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
+ return NULL;
+ }
- name = _PyUnicode_AsString(item);
+ name = _PyUnicode_AsString(item);
- if (name == NULL) {
- PyErr_SetString(PyExc_TypeError, "only strings are allowed as keys of ID properties");
- return NULL;
- }
+ if (name == NULL) {
+ PyErr_SetString(PyExc_TypeError, "only strings are allowed as keys of ID properties");
+ return NULL;
+ }
- idprop = IDP_GetPropertyFromGroup(self->prop, name);
+ idprop = IDP_GetPropertyFromGroup(self->prop, name);
- if (idprop == NULL) {
- PyErr_SetString(PyExc_KeyError, "key not in subgroup dict");
- return NULL;
- }
+ if (idprop == NULL) {
+ PyErr_SetString(PyExc_KeyError, "key not in subgroup dict");
+ return NULL;
+ }
- return BPy_IDGroup_WrapData(self->id, idprop, self->prop);
+ return BPy_IDGroup_WrapData(self->id, idprop, self->prop);
}
/* returns NULL on success, error string on failure */
static char idp_sequence_type(PyObject *seq_fast)
{
- PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
- PyObject *item;
- char type = IDP_INT;
-
- Py_ssize_t i, len = PySequence_Fast_GET_SIZE(seq_fast);
-
- for (i = 0; i < len; i++) {
- item = seq_fast_items[i];
- if (PyFloat_Check(item)) {
- if (type == IDP_IDPARRAY) { /* mixed dict/int */
- return -1;
- }
- type = IDP_DOUBLE;
- }
- else if (PyLong_Check(item)) {
- if (type == IDP_IDPARRAY) { /* mixed dict/int */
- return -1;
- }
- }
- else if (PyMapping_Check(item)) {
- if (i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
- return -1;
- }
- type = IDP_IDPARRAY;
- }
- else {
- return -1;
- }
- }
-
- return type;
+ PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
+ PyObject *item;
+ char type = IDP_INT;
+
+ Py_ssize_t i, len = PySequence_Fast_GET_SIZE(seq_fast);
+
+ for (i = 0; i < len; i++) {
+ item = seq_fast_items[i];
+ if (PyFloat_Check(item)) {
+ if (type == IDP_IDPARRAY) { /* mixed dict/int */
+ return -1;
+ }
+ type = IDP_DOUBLE;
+ }
+ else if (PyLong_Check(item)) {
+ if (type == IDP_IDPARRAY) { /* mixed dict/int */
+ return -1;
+ }
+ }
+ else if (PyMapping_Check(item)) {
+ if (i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
+ return -1;
+ }
+ type = IDP_IDPARRAY;
+ }
+ else {
+ return -1;
+ }
+ }
+
+ return type;
}
static const char *idp_try_read_name(PyObject *name_obj)
{
- const char *name = NULL;
- if (name_obj) {
- Py_ssize_t name_size;
- name = _PyUnicode_AsStringAndSize(name_obj, &name_size);
-
- if (name == NULL) {
- PyErr_Format(PyExc_KeyError,
- "invalid id-property key, expected a string, not a %.200s",
- Py_TYPE(name_obj)->tp_name);
- return NULL;
- }
-
- if (name_size > MAX_IDPROP_NAME) {
- PyErr_SetString(PyExc_KeyError, "the length of IDProperty names is limited to 63 characters");
- return NULL;
- }
- }
- else {
- name = "";
- }
- return name;
+ const char *name = NULL;
+ if (name_obj) {
+ Py_ssize_t name_size;
+ name = _PyUnicode_AsStringAndSize(name_obj, &name_size);
+
+ if (name == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "invalid id-property key, expected a string, not a %.200s",
+ Py_TYPE(name_obj)->tp_name);
+ return NULL;
+ }
+
+ if (name_size > MAX_IDPROP_NAME) {
+ PyErr_SetString(PyExc_KeyError,
+ "the length of IDProperty names is limited to 63 characters");
+ return NULL;
+ }
+ }
+ else {
+ name = "";
+ }
+ return name;
}
/* -------------------------------------------------------------------------- */
@@ -371,285 +386,280 @@ static const char *idp_try_read_name(PyObject *name_obj)
static IDProperty *idp_from_PyFloat(const char *name, PyObject *ob)
{
- IDPropertyTemplate val = {0};
- val.d = PyFloat_AsDouble(ob);
- return IDP_New(IDP_DOUBLE, &val, name);
+ IDPropertyTemplate val = {0};
+ val.d = PyFloat_AsDouble(ob);
+ return IDP_New(IDP_DOUBLE, &val, name);
}
static IDProperty *idp_from_PyLong(const char *name, PyObject *ob)
{
- IDPropertyTemplate val = {0};
- val.i = PyC_Long_AsI32(ob);
- if (val.i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- return IDP_New(IDP_INT, &val, name);
+ IDPropertyTemplate val = {0};
+ val.i = PyC_Long_AsI32(ob);
+ if (val.i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ return IDP_New(IDP_INT, &val, name);
}
static IDProperty *idp_from_PyUnicode(const char *name, PyObject *ob)
{
- IDProperty *prop;
- IDPropertyTemplate val = {0};
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
#ifdef USE_STRING_COERCE
- Py_ssize_t value_size;
- PyObject *value_coerce = NULL;
- val.string.str = PyC_UnicodeAsByteAndSize(ob, &value_size, &value_coerce);
- val.string.len = (int)value_size + 1;
- val.string.subtype = IDP_STRING_SUB_UTF8;
- prop = IDP_New(IDP_STRING, &val, name);
- Py_XDECREF(value_coerce);
+ Py_ssize_t value_size;
+ PyObject *value_coerce = NULL;
+ val.string.str = PyC_UnicodeAsByteAndSize(ob, &value_size, &value_coerce);
+ val.string.len = (int)value_size + 1;
+ val.string.subtype = IDP_STRING_SUB_UTF8;
+ prop = IDP_New(IDP_STRING, &val, name);
+ Py_XDECREF(value_coerce);
#else
- val.str = _PyUnicode_AsString(ob);
- prop = IDP_New(IDP_STRING, val, name);
+ val.str = _PyUnicode_AsString(ob);
+ prop = IDP_New(IDP_STRING, val, name);
#endif
- return prop;
+ return prop;
}
static IDProperty *idp_from_PyBytes(const char *name, PyObject *ob)
{
- IDPropertyTemplate val = {0};
- val.string.str = PyBytes_AS_STRING(ob);
- val.string.len = PyBytes_GET_SIZE(ob);
- val.string.subtype = IDP_STRING_SUB_BYTE;
- return IDP_New(IDP_STRING, &val, name);
+ IDPropertyTemplate val = {0};
+ val.string.str = PyBytes_AS_STRING(ob);
+ val.string.len = PyBytes_GET_SIZE(ob);
+ val.string.subtype = IDP_STRING_SUB_BYTE;
+ return IDP_New(IDP_STRING, &val, name);
}
static int idp_array_type_from_formatstr_and_size(const char *typestr, Py_ssize_t itemsize)
{
- char format = PyC_StructFmt_type_from_str(typestr);
+ char format = PyC_StructFmt_type_from_str(typestr);
- if (PyC_StructFmt_type_is_float_any(format)) {
- if (itemsize == 4) {
- return IDP_FLOAT;
- }
- if (itemsize == 8) {
- return IDP_DOUBLE;
- }
- }
- if (PyC_StructFmt_type_is_int_any(format)) {
- if (itemsize == 4) {
- return IDP_INT;
- }
- }
+ if (PyC_StructFmt_type_is_float_any(format)) {
+ if (itemsize == 4) {
+ return IDP_FLOAT;
+ }
+ if (itemsize == 8) {
+ return IDP_DOUBLE;
+ }
+ }
+ if (PyC_StructFmt_type_is_int_any(format)) {
+ if (itemsize == 4) {
+ return IDP_INT;
+ }
+ }
- return -1;
+ return -1;
}
static const char *idp_format_from_array_type(int type)
{
- if (type == IDP_INT) {
- return "i";
- }
- if (type == IDP_FLOAT) {
- return "f";
- }
- if (type == IDP_DOUBLE) {
- return "d";
- }
- return NULL;
+ if (type == IDP_INT) {
+ return "i";
+ }
+ if (type == IDP_FLOAT) {
+ return "f";
+ }
+ if (type == IDP_DOUBLE) {
+ return "d";
+ }
+ return NULL;
}
static IDProperty *idp_from_PySequence_Buffer(const char *name, Py_buffer *buffer)
{
- IDProperty *prop;
- IDPropertyTemplate val = {0};
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
- int id_type = idp_array_type_from_formatstr_and_size(buffer->format, buffer->itemsize);
- if (id_type == -1) {
- /* should never happen as the type has been checked before */
- return NULL;
- }
- else {
- val.array.type = id_type;
- val.array.len = buffer->len / buffer->itemsize;
- }
- prop = IDP_New(IDP_ARRAY, &val, name);
- memcpy(IDP_Array(prop), buffer->buf, buffer->len);
- return prop;
+ int id_type = idp_array_type_from_formatstr_and_size(buffer->format, buffer->itemsize);
+ if (id_type == -1) {
+ /* should never happen as the type has been checked before */
+ return NULL;
+ }
+ else {
+ val.array.type = id_type;
+ val.array.len = buffer->len / buffer->itemsize;
+ }
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ memcpy(IDP_Array(prop), buffer->buf, buffer->len);
+ return prop;
}
static IDProperty *idp_from_PySequence_Fast(const char *name, PyObject *ob)
{
- IDProperty *prop;
- IDPropertyTemplate val = {0};
-
- PyObject **ob_seq_fast_items;
- PyObject *item;
- int i;
-
- ob_seq_fast_items = PySequence_Fast_ITEMS(ob);
-
- if ((val.array.type = idp_sequence_type(ob)) == (char)-1) {
- PyErr_SetString(PyExc_TypeError, "only floats, ints and dicts are allowed in ID property arrays");
- return NULL;
- }
-
- /* validate sequence and derive type.
- * we assume IDP_INT unless we hit a float
- * number; then we assume it's */
-
- val.array.len = PySequence_Fast_GET_SIZE(ob);
-
- switch (val.array.type) {
- case IDP_DOUBLE:
- {
- double *prop_data;
- prop = IDP_New(IDP_ARRAY, &val, name);
- prop_data = IDP_Array(prop);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
- if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
- return NULL;
- }
- }
- break;
- }
- case IDP_INT:
- {
- int *prop_data;
- prop = IDP_New(IDP_ARRAY, &val, name);
- prop_data = IDP_Array(prop);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
- if (((prop_data[i] = PyC_Long_AsI32(item)) == -1) && PyErr_Occurred()) {
- return NULL;
- }
- }
- break;
- }
- case IDP_IDPARRAY:
- {
- prop = IDP_NewIDPArray(name);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
- if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
- return NULL;
- }
- }
- break;
- }
- default:
- /* should never happen */
- PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
- return NULL;
- }
- return prop;
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
+
+ PyObject **ob_seq_fast_items;
+ PyObject *item;
+ int i;
+
+ ob_seq_fast_items = PySequence_Fast_ITEMS(ob);
+
+ if ((val.array.type = idp_sequence_type(ob)) == (char)-1) {
+ PyErr_SetString(PyExc_TypeError,
+ "only floats, ints and dicts are allowed in ID property arrays");
+ return NULL;
+ }
+
+ /* validate sequence and derive type.
+ * we assume IDP_INT unless we hit a float
+ * number; then we assume it's */
+
+ val.array.len = PySequence_Fast_GET_SIZE(ob);
+
+ switch (val.array.type) {
+ case IDP_DOUBLE: {
+ double *prop_data;
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ prop_data = IDP_Array(prop);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
+ return NULL;
+ }
+ }
+ break;
+ }
+ case IDP_INT: {
+ int *prop_data;
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ prop_data = IDP_Array(prop);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (((prop_data[i] = PyC_Long_AsI32(item)) == -1) && PyErr_Occurred()) {
+ return NULL;
+ }
+ }
+ break;
+ }
+ case IDP_IDPARRAY: {
+ prop = IDP_NewIDPArray(name);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
+ return NULL;
+ }
+ }
+ break;
+ }
+ default:
+ /* should never happen */
+ PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
+ return NULL;
+ }
+ return prop;
}
-
static IDProperty *idp_from_PySequence(const char *name, PyObject *ob)
{
- Py_buffer buffer;
- bool use_buffer = false;
-
- if (PyObject_CheckBuffer(ob)) {
- PyObject_GetBuffer(ob, &buffer, PyBUF_SIMPLE | PyBUF_FORMAT);
- char format = PyC_StructFmt_type_from_str(buffer.format);
- if (PyC_StructFmt_type_is_float_any(format) ||
- (PyC_StructFmt_type_is_int_any(format) && buffer.itemsize == 4))
- {
- use_buffer = true;
- }
- else {
- PyBuffer_Release(&buffer);
- }
- }
-
- if (use_buffer) {
- IDProperty *prop = idp_from_PySequence_Buffer(name, &buffer);
- PyBuffer_Release(&buffer);
- return prop;
- }
- else {
- PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
- if (ob_seq_fast != NULL) {
- IDProperty *prop = idp_from_PySequence_Fast(name, ob_seq_fast);
- Py_DECREF(ob_seq_fast);
- return prop;
- }
- else {
- return NULL;
- }
- }
+ Py_buffer buffer;
+ bool use_buffer = false;
+
+ if (PyObject_CheckBuffer(ob)) {
+ PyObject_GetBuffer(ob, &buffer, PyBUF_SIMPLE | PyBUF_FORMAT);
+ char format = PyC_StructFmt_type_from_str(buffer.format);
+ if (PyC_StructFmt_type_is_float_any(format) ||
+ (PyC_StructFmt_type_is_int_any(format) && buffer.itemsize == 4)) {
+ use_buffer = true;
+ }
+ else {
+ PyBuffer_Release(&buffer);
+ }
+ }
+
+ if (use_buffer) {
+ IDProperty *prop = idp_from_PySequence_Buffer(name, &buffer);
+ PyBuffer_Release(&buffer);
+ return prop;
+ }
+ else {
+ PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
+ if (ob_seq_fast != NULL) {
+ IDProperty *prop = idp_from_PySequence_Fast(name, ob_seq_fast);
+ Py_DECREF(ob_seq_fast);
+ return prop;
+ }
+ else {
+ return NULL;
+ }
+ }
}
static IDProperty *idp_from_PyMapping(const char *name, PyObject *ob)
{
- IDProperty *prop;
- IDPropertyTemplate val = {0};
-
- PyObject *keys, *vals, *key, *pval;
- int i, len;
- /* yay! we get into recursive stuff now! */
- keys = PyMapping_Keys(ob);
- vals = PyMapping_Values(ob);
-
- /* we allocate the group first; if we hit any invalid data,
- * we can delete it easily enough.*/
- prop = IDP_New(IDP_GROUP, &val, name);
- len = PyMapping_Length(ob);
- for (i = 0; i < len; i++) {
- key = PySequence_GetItem(keys, i);
- pval = PySequence_GetItem(vals, i);
- if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
- IDP_FreeProperty(prop);
- MEM_freeN(prop);
- Py_XDECREF(keys);
- Py_XDECREF(vals);
- Py_XDECREF(key);
- Py_XDECREF(pval);
- /* error is already set */
- return NULL;
- }
- Py_XDECREF(key);
- Py_XDECREF(pval);
- }
- Py_XDECREF(keys);
- Py_XDECREF(vals);
- return prop;
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
+
+ PyObject *keys, *vals, *key, *pval;
+ int i, len;
+ /* yay! we get into recursive stuff now! */
+ keys = PyMapping_Keys(ob);
+ vals = PyMapping_Values(ob);
+
+ /* we allocate the group first; if we hit any invalid data,
+ * we can delete it easily enough.*/
+ prop = IDP_New(IDP_GROUP, &val, name);
+ len = PyMapping_Length(ob);
+ for (i = 0; i < len; i++) {
+ key = PySequence_GetItem(keys, i);
+ pval = PySequence_GetItem(vals, i);
+ if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
+ IDP_FreeProperty(prop);
+ MEM_freeN(prop);
+ Py_XDECREF(keys);
+ Py_XDECREF(vals);
+ Py_XDECREF(key);
+ Py_XDECREF(pval);
+ /* error is already set */
+ return NULL;
+ }
+ Py_XDECREF(key);
+ Py_XDECREF(pval);
+ }
+ Py_XDECREF(keys);
+ Py_XDECREF(vals);
+ return prop;
}
static IDProperty *idp_from_DatablockPointer(const char *name, PyObject *ob)
{
- IDPropertyTemplate val = {0};
- pyrna_id_FromPyObject(ob, &val.id);
- return IDP_New(IDP_ID, &val, name);
+ IDPropertyTemplate val = {0};
+ pyrna_id_FromPyObject(ob, &val.id);
+ return IDP_New(IDP_ID, &val, name);
}
static IDProperty *idp_from_PyObject(PyObject *name_obj, PyObject *ob)
{
- const char *name = idp_try_read_name(name_obj);
- if (name == NULL) {
- return NULL;
- }
-
- if (PyFloat_Check(ob)) {
- return idp_from_PyFloat(name, ob);
- }
- else if (PyLong_Check(ob)) {
- return idp_from_PyLong(name, ob);
- }
- else if (PyUnicode_Check(ob)) {
- return idp_from_PyUnicode(name, ob);
- }
- else if (PyBytes_Check(ob)) {
- return idp_from_PyBytes(name, ob);
- }
- else if (PySequence_Check(ob)) {
- return idp_from_PySequence(name, ob);
- }
- else if (ob == Py_None || pyrna_id_CheckPyObject(ob)) {
- return idp_from_DatablockPointer(name, ob);
- }
- else if (PyMapping_Check(ob)) {
- return idp_from_PyMapping(name, ob);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "invalid id-property type %.200s not supported",
- Py_TYPE(ob)->tp_name);
- return NULL;
- }
+ const char *name = idp_try_read_name(name_obj);
+ if (name == NULL) {
+ return NULL;
+ }
+
+ if (PyFloat_Check(ob)) {
+ return idp_from_PyFloat(name, ob);
+ }
+ else if (PyLong_Check(ob)) {
+ return idp_from_PyLong(name, ob);
+ }
+ else if (PyUnicode_Check(ob)) {
+ return idp_from_PyUnicode(name, ob);
+ }
+ else if (PyBytes_Check(ob)) {
+ return idp_from_PyBytes(name, ob);
+ }
+ else if (PySequence_Check(ob)) {
+ return idp_from_PySequence(name, ob);
+ }
+ else if (ob == Py_None || pyrna_id_CheckPyObject(ob)) {
+ return idp_from_DatablockPointer(name, ob);
+ }
+ else if (PyMapping_Check(ob)) {
+ return idp_from_PyMapping(name, ob);
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "invalid id-property type %.200s not supported", Py_TYPE(ob)->tp_name);
+ return NULL;
+ }
}
/* -------------------------------------------------------------------------- */
@@ -661,1101 +671,1081 @@ static IDProperty *idp_from_PyObject(PyObject *name_obj, PyObject *ob)
*/
bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
{
- IDProperty *prop = idp_from_PyObject(name_obj, ob);
- if (prop == NULL) {
- return false;
- }
-
- if (group->type == IDP_IDPARRAY) {
- IDP_AppendArray(group, prop);
- /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
- MEM_freeN(prop);
- }
- else {
- IDProperty *prop_exist;
-
- /* avoid freeing when types match in case they are referenced by the UI, see: T37073
- * obviously this isn't a complete solution, but helps for common cases. */
- prop_exist = IDP_GetPropertyFromGroup(group, prop->name);
- if ((prop_exist != NULL) &&
- (prop_exist->type == prop->type) &&
- (prop_exist->subtype == prop->subtype))
- {
- /* Preserve prev/next links!!! See T42593. */
- prop->prev = prop_exist->prev;
- prop->next = prop_exist->next;
-
- IDP_FreeProperty(prop_exist);
- *prop_exist = *prop;
- MEM_freeN(prop);
- }
- else {
- IDP_ReplaceInGroup_ex(group, prop, prop_exist);
- }
- }
-
- return true;
+ IDProperty *prop = idp_from_PyObject(name_obj, ob);
+ if (prop == NULL) {
+ return false;
+ }
+
+ if (group->type == IDP_IDPARRAY) {
+ IDP_AppendArray(group, prop);
+ /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
+ MEM_freeN(prop);
+ }
+ else {
+ IDProperty *prop_exist;
+
+ /* avoid freeing when types match in case they are referenced by the UI, see: T37073
+ * obviously this isn't a complete solution, but helps for common cases. */
+ prop_exist = IDP_GetPropertyFromGroup(group, prop->name);
+ if ((prop_exist != NULL) && (prop_exist->type == prop->type) &&
+ (prop_exist->subtype == prop->subtype)) {
+ /* Preserve prev/next links!!! See T42593. */
+ prop->prev = prop_exist->prev;
+ prop->next = prop_exist->next;
+
+ IDP_FreeProperty(prop_exist);
+ *prop_exist = *prop;
+ MEM_freeN(prop);
+ }
+ else {
+ IDP_ReplaceInGroup_ex(group, prop, prop_exist);
+ }
+ }
+
+ return true;
}
int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val)
{
- if (prop->type != IDP_GROUP) {
- PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
- return -1;
- }
-
- if (val == NULL) { /* del idprop[key] */
- IDProperty *pkey;
- const char *name = _PyUnicode_AsString(key);
-
- if (name == NULL) {
- PyErr_Format(PyExc_KeyError,
- "expected a string, not %.200s",
- Py_TYPE(key)->tp_name);
- return -1;
- }
-
- pkey = IDP_GetPropertyFromGroup(prop, name);
- if (pkey) {
- IDP_FreeFromGroup(prop, pkey);
- return 0;
- }
- else {
- PyErr_SetString(PyExc_KeyError, "property not found in group");
- return -1;
- }
- }
- else {
- bool ok;
-
- ok = BPy_IDProperty_Map_ValidateAndCreate(key, prop, val);
- if (ok == false) {
- return -1;
- }
-
- return 0;
- }
+ if (prop->type != IDP_GROUP) {
+ PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
+ return -1;
+ }
+
+ if (val == NULL) { /* del idprop[key] */
+ IDProperty *pkey;
+ const char *name = _PyUnicode_AsString(key);
+
+ if (name == NULL) {
+ PyErr_Format(PyExc_KeyError, "expected a string, not %.200s", Py_TYPE(key)->tp_name);
+ return -1;
+ }
+
+ pkey = IDP_GetPropertyFromGroup(prop, name);
+ if (pkey) {
+ IDP_FreeFromGroup(prop, pkey);
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_KeyError, "property not found in group");
+ return -1;
+ }
+ }
+ else {
+ bool ok;
+
+ ok = BPy_IDProperty_Map_ValidateAndCreate(key, prop, val);
+ if (ok == false) {
+ return -1;
+ }
+
+ return 0;
+ }
}
static int BPy_IDGroup_Map_SetItem(BPy_IDProperty *self, PyObject *key, PyObject *val)
{
- return BPy_Wrap_SetMapItem(self->prop, key, val);
+ return BPy_Wrap_SetMapItem(self->prop, key, val);
}
static PyObject *BPy_IDGroup_iter(BPy_IDProperty *self)
{
- BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
- iter->group = self;
- iter->mode = IDPROP_ITER_KEYS;
- iter->cur = self->prop->data.group.first;
- Py_XINCREF(iter);
- return (PyObject *)iter;
+ BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
+ iter->group = self;
+ iter->mode = IDPROP_ITER_KEYS;
+ iter->cur = self->prop->data.group.first;
+ Py_XINCREF(iter);
+ return (PyObject *)iter;
}
/* for simple, non nested types this is the same as BPy_IDGroup_WrapData */
static PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop)
{
- switch (prop->type) {
- case IDP_STRING:
- return idprop_py_from_idp_string(prop);
- case IDP_INT:
- return idprop_py_from_idp_int(prop);
- case IDP_FLOAT:
- return idprop_py_from_idp_float(prop);
- case IDP_DOUBLE:
- return idprop_py_from_idp_double(prop);
- case IDP_ID:
- return idprop_py_from_idp_id(prop);
- case IDP_ARRAY:
- {
- PyObject *seq = PyList_New(prop->len);
- int i;
-
- if (!seq) {
- PyErr_Format(PyExc_RuntimeError,
- "%s: IDP_ARRAY: PyList_New(%d) failed",
- __func__, prop->len);
- return NULL;
- }
-
- switch (prop->subtype) {
- case IDP_FLOAT:
- {
- const float *array = (float *)IDP_Array(prop);
- for (i = 0; i < prop->len; i++) {
- PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
- }
- break;
- }
- case IDP_DOUBLE:
- {
- const double *array = (double *)IDP_Array(prop);
- for (i = 0; i < prop->len; i++) {
- PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
- }
- break;
- }
- case IDP_INT:
- {
- const int *array = (int *)IDP_Array(prop);
- for (i = 0; i < prop->len; i++) {
- PyList_SET_ITEM(seq, i, PyLong_FromLong(array[i]));
- }
- break;
- }
- default:
- PyErr_Format(PyExc_RuntimeError,
- "%s: invalid/corrupt array type '%d'!",
- __func__, prop->subtype);
- Py_DECREF(seq);
- return NULL;
- }
-
- return seq;
- }
- case IDP_IDPARRAY:
- {
- PyObject *seq = PyList_New(prop->len);
- IDProperty *array = IDP_IDPArray(prop);
- int i;
-
- if (!seq) {
- PyErr_Format(PyExc_RuntimeError,
- "%s: IDP_IDPARRAY: PyList_New(%d) failed",
- __func__, prop->len);
- return NULL;
- }
-
- for (i = 0; i < prop->len; i++) {
- PyObject *wrap = BPy_IDGroup_MapDataToPy(array++);
-
- /* BPy_IDGroup_MapDataToPy sets the error */
- if (UNLIKELY(wrap == NULL)) {
- Py_DECREF(seq);
- return NULL;
- }
-
- PyList_SET_ITEM(seq, i, wrap);
- }
- return seq;
- }
- case IDP_GROUP:
- {
- PyObject *dict = _PyDict_NewPresized(prop->len);
- IDProperty *loop;
-
- for (loop = prop->data.group.first; loop; loop = loop->next) {
- PyObject *wrap = BPy_IDGroup_MapDataToPy(loop);
-
- /* BPy_IDGroup_MapDataToPy sets the error */
- if (UNLIKELY(wrap == NULL)) {
- Py_DECREF(dict);
- return NULL;
- }
-
- PyDict_SetItemString(dict, loop->name, wrap);
- Py_DECREF(wrap);
- }
- return dict;
- }
- }
-
- PyErr_Format(PyExc_RuntimeError,
- "%s ERROR: '%s' property exists with a bad type code '%d'!",
- __func__, prop->name, prop->type);
- return NULL;
-}
-
-PyDoc_STRVAR(BPy_IDGroup_pop_doc,
-".. method:: pop(key, default)\n"
-"\n"
-" Remove an item from the group, returning a Python representation.\n"
-"\n"
-" :raises KeyError: When the item doesn't exist.\n"
-"\n"
-" :arg key: Name of item to remove.\n"
-" :type key: string\n"
-" :arg default: Value to return when key isn't found, otherwise raise an exception.\n"
-" :type default: Undefined\n"
-);
+ switch (prop->type) {
+ case IDP_STRING:
+ return idprop_py_from_idp_string(prop);
+ case IDP_INT:
+ return idprop_py_from_idp_int(prop);
+ case IDP_FLOAT:
+ return idprop_py_from_idp_float(prop);
+ case IDP_DOUBLE:
+ return idprop_py_from_idp_double(prop);
+ case IDP_ID:
+ return idprop_py_from_idp_id(prop);
+ case IDP_ARRAY: {
+ PyObject *seq = PyList_New(prop->len);
+ int i;
+
+ if (!seq) {
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: IDP_ARRAY: PyList_New(%d) failed", __func__, prop->len);
+ return NULL;
+ }
+
+ switch (prop->subtype) {
+ case IDP_FLOAT: {
+ const float *array = (float *)IDP_Array(prop);
+ for (i = 0; i < prop->len; i++) {
+ PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
+ }
+ break;
+ }
+ case IDP_DOUBLE: {
+ const double *array = (double *)IDP_Array(prop);
+ for (i = 0; i < prop->len; i++) {
+ PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
+ }
+ break;
+ }
+ case IDP_INT: {
+ const int *array = (int *)IDP_Array(prop);
+ for (i = 0; i < prop->len; i++) {
+ PyList_SET_ITEM(seq, i, PyLong_FromLong(array[i]));
+ }
+ break;
+ }
+ default:
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: invalid/corrupt array type '%d'!", __func__, prop->subtype);
+ Py_DECREF(seq);
+ return NULL;
+ }
+
+ return seq;
+ }
+ case IDP_IDPARRAY: {
+ PyObject *seq = PyList_New(prop->len);
+ IDProperty *array = IDP_IDPArray(prop);
+ int i;
+
+ if (!seq) {
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: IDP_IDPARRAY: PyList_New(%d) failed", __func__, prop->len);
+ return NULL;
+ }
+
+ for (i = 0; i < prop->len; i++) {
+ PyObject *wrap = BPy_IDGroup_MapDataToPy(array++);
+
+ /* BPy_IDGroup_MapDataToPy sets the error */
+ if (UNLIKELY(wrap == NULL)) {
+ Py_DECREF(seq);
+ return NULL;
+ }
+
+ PyList_SET_ITEM(seq, i, wrap);
+ }
+ return seq;
+ }
+ case IDP_GROUP: {
+ PyObject *dict = _PyDict_NewPresized(prop->len);
+ IDProperty *loop;
+
+ for (loop = prop->data.group.first; loop; loop = loop->next) {
+ PyObject *wrap = BPy_IDGroup_MapDataToPy(loop);
+
+ /* BPy_IDGroup_MapDataToPy sets the error */
+ if (UNLIKELY(wrap == NULL)) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+
+ PyDict_SetItemString(dict, loop->name, wrap);
+ Py_DECREF(wrap);
+ }
+ return dict;
+ }
+ }
+
+ PyErr_Format(PyExc_RuntimeError,
+ "%s ERROR: '%s' property exists with a bad type code '%d'!",
+ __func__,
+ prop->name,
+ prop->type);
+ return NULL;
+}
+
+PyDoc_STRVAR(
+ BPy_IDGroup_pop_doc,
+ ".. method:: pop(key, default)\n"
+ "\n"
+ " Remove an item from the group, returning a Python representation.\n"
+ "\n"
+ " :raises KeyError: When the item doesn't exist.\n"
+ "\n"
+ " :arg key: Name of item to remove.\n"
+ " :type key: string\n"
+ " :arg default: Value to return when key isn't found, otherwise raise an exception.\n"
+ " :type default: Undefined\n");
static PyObject *BPy_IDGroup_pop(BPy_IDProperty *self, PyObject *args)
{
- IDProperty *idprop;
- PyObject *pyform;
-
- char *key;
- PyObject *def = NULL;
-
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
- return NULL;
- }
-
- idprop = IDP_GetPropertyFromGroup(self->prop, key);
- if (idprop == NULL) {
- if (def == NULL) {
- PyErr_SetString(PyExc_KeyError, "item not in group");
- return NULL;
- }
- return Py_INCREF_RET(def);
- }
-
- pyform = BPy_IDGroup_MapDataToPy(idprop);
- if (pyform == NULL) {
- /* ok something bad happened with the pyobject,
- * so don't remove the prop from the group. if pyform is
- * NULL, then it already should have raised an exception.*/
- return NULL;
- }
-
- IDP_RemoveFromGroup(self->prop, idprop);
- return pyform;
-}
-
-PyDoc_STRVAR(BPy_IDGroup_iter_items_doc,
-".. method:: iteritems()\n"
-"\n"
-" Iterate through the items in the dict; behaves like dictionary method iteritems.\n"
-);
+ IDProperty *idprop;
+ PyObject *pyform;
+
+ char *key;
+ PyObject *def = NULL;
+
+ if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
+ return NULL;
+ }
+
+ idprop = IDP_GetPropertyFromGroup(self->prop, key);
+ if (idprop == NULL) {
+ if (def == NULL) {
+ PyErr_SetString(PyExc_KeyError, "item not in group");
+ return NULL;
+ }
+ return Py_INCREF_RET(def);
+ }
+
+ pyform = BPy_IDGroup_MapDataToPy(idprop);
+ if (pyform == NULL) {
+ /* ok something bad happened with the pyobject,
+ * so don't remove the prop from the group. if pyform is
+ * NULL, then it already should have raised an exception.*/
+ return NULL;
+ }
+
+ IDP_RemoveFromGroup(self->prop, idprop);
+ return pyform;
+}
+
+PyDoc_STRVAR(
+ BPy_IDGroup_iter_items_doc,
+ ".. method:: iteritems()\n"
+ "\n"
+ " Iterate through the items in the dict; behaves like dictionary method iteritems.\n");
static PyObject *BPy_IDGroup_iter_items(BPy_IDProperty *self)
{
- BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
- iter->group = self;
- iter->mode = IDPROP_ITER_ITEMS;
- iter->cur = self->prop->data.group.first;
- Py_XINCREF(iter);
- return (PyObject *)iter;
+ BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
+ iter->group = self;
+ iter->mode = IDPROP_ITER_ITEMS;
+ iter->cur = self->prop->data.group.first;
+ Py_XINCREF(iter);
+ return (PyObject *)iter;
}
/* utility function */
static void BPy_IDGroup_CorrectListLen(IDProperty *prop, PyObject *seq, int len, const char *func)
{
- int j;
+ int j;
- printf("%s: ID Property Error found and corrected!\n", func);
+ printf("%s: ID Property Error found and corrected!\n", func);
- /* fill rest of list with valid references to None */
- for (j = len; j < prop->len; j++) {
- PyList_SET_ITEM(seq, j, Py_INCREF_RET(Py_None));
- }
+ /* fill rest of list with valid references to None */
+ for (j = len; j < prop->len; j++) {
+ PyList_SET_ITEM(seq, j, Py_INCREF_RET(Py_None));
+ }
- /*set correct group length*/
- prop->len = len;
+ /*set correct group length*/
+ prop->len = len;
}
PyObject *BPy_Wrap_GetKeys(IDProperty *prop)
{
- PyObject *list = PyList_New(prop->len);
- IDProperty *loop;
- int i;
+ PyObject *list = PyList_New(prop->len);
+ IDProperty *loop;
+ int i;
- for (i = 0, loop = prop->data.group.first; loop && (i < prop->len); loop = loop->next, i++) {
- PyList_SET_ITEM(list, i, PyUnicode_FromString(loop->name));
- }
+ for (i = 0, loop = prop->data.group.first; loop && (i < prop->len); loop = loop->next, i++) {
+ PyList_SET_ITEM(list, i, PyUnicode_FromString(loop->name));
+ }
- /* if the id prop is corrupt, count the remaining */
- for ( ; loop; loop = loop->next, i++) {
- /* pass */
- }
+ /* if the id prop is corrupt, count the remaining */
+ for (; loop; loop = loop->next, i++) {
+ /* pass */
+ }
- if (i != prop->len) { /* if the loop didn't finish, we know the length is wrong */
- BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
- Py_DECREF(list); /*free the list*/
- /*call self again*/
- return BPy_Wrap_GetKeys(prop);
- }
+ if (i != prop->len) { /* if the loop didn't finish, we know the length is wrong */
+ BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
+ Py_DECREF(list); /*free the list*/
+ /*call self again*/
+ return BPy_Wrap_GetKeys(prop);
+ }
- return list;
+ return list;
}
PyObject *BPy_Wrap_GetValues(ID *id, IDProperty *prop)
{
- PyObject *list = PyList_New(prop->len);
- IDProperty *loop;
- int i;
+ PyObject *list = PyList_New(prop->len);
+ IDProperty *loop;
+ int i;
- for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
- PyList_SET_ITEM(list, i, BPy_IDGroup_WrapData(id, loop, prop));
- }
+ for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
+ PyList_SET_ITEM(list, i, BPy_IDGroup_WrapData(id, loop, prop));
+ }
- if (i != prop->len) {
- BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
- Py_DECREF(list); /*free the list*/
- /*call self again*/
- return BPy_Wrap_GetValues(id, prop);
- }
+ if (i != prop->len) {
+ BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
+ Py_DECREF(list); /*free the list*/
+ /*call self again*/
+ return BPy_Wrap_GetValues(id, prop);
+ }
- return list;
+ return list;
}
PyObject *BPy_Wrap_GetItems(ID *id, IDProperty *prop)
{
- PyObject *seq = PyList_New(prop->len);
- IDProperty *loop;
- int i;
+ PyObject *seq = PyList_New(prop->len);
+ IDProperty *loop;
+ int i;
- for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
- PyObject *item = PyTuple_New(2);
- PyTuple_SET_ITEMS(item,
- PyUnicode_FromString(loop->name),
- BPy_IDGroup_WrapData(id, loop, prop));
- PyList_SET_ITEM(seq, i, item);
- }
+ for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
+ PyObject *item = PyTuple_New(2);
+ PyTuple_SET_ITEMS(
+ item, PyUnicode_FromString(loop->name), BPy_IDGroup_WrapData(id, loop, prop));
+ PyList_SET_ITEM(seq, i, item);
+ }
- if (i != prop->len) {
- BPy_IDGroup_CorrectListLen(prop, seq, i, __func__);
- Py_DECREF(seq); /*free the list*/
- /*call self again*/
- return BPy_Wrap_GetItems(id, prop);
- }
+ if (i != prop->len) {
+ BPy_IDGroup_CorrectListLen(prop, seq, i, __func__);
+ Py_DECREF(seq); /*free the list*/
+ /*call self again*/
+ return BPy_Wrap_GetItems(id, prop);
+ }
- return seq;
+ return seq;
}
PyDoc_STRVAR(BPy_IDGroup_keys_doc,
-".. method:: keys()\n"
-"\n"
-" Return the keys associated with this group as a list of strings.\n"
-);
+ ".. method:: keys()\n"
+ "\n"
+ " Return the keys associated with this group as a list of strings.\n");
static PyObject *BPy_IDGroup_keys(BPy_IDProperty *self)
{
- return BPy_Wrap_GetKeys(self->prop);
+ return BPy_Wrap_GetKeys(self->prop);
}
PyDoc_STRVAR(BPy_IDGroup_values_doc,
-".. method:: values()\n"
-"\n"
-" Return the values associated with this group.\n"
-);
+ ".. method:: values()\n"
+ "\n"
+ " Return the values associated with this group.\n");
static PyObject *BPy_IDGroup_values(BPy_IDProperty *self)
{
- return BPy_Wrap_GetValues(self->id, self->prop);
+ return BPy_Wrap_GetValues(self->id, self->prop);
}
PyDoc_STRVAR(BPy_IDGroup_items_doc,
-".. method:: items()\n"
-"\n"
-" Return the items associated with this group.\n"
-);
+ ".. method:: items()\n"
+ "\n"
+ " Return the items associated with this group.\n");
static PyObject *BPy_IDGroup_items(BPy_IDProperty *self)
{
- return BPy_Wrap_GetItems(self->id, self->prop);
+ return BPy_Wrap_GetItems(self->id, self->prop);
}
static int BPy_IDGroup_Contains(BPy_IDProperty *self, PyObject *value)
{
- const char *name = _PyUnicode_AsString(value);
+ const char *name = _PyUnicode_AsString(value);
- if (!name) {
- PyErr_Format(PyExc_TypeError,
- "expected a string, not a %.200s",
- Py_TYPE(value)->tp_name);
- return -1;
- }
+ if (!name) {
+ PyErr_Format(PyExc_TypeError, "expected a string, not a %.200s", Py_TYPE(value)->tp_name);
+ return -1;
+ }
- return IDP_GetPropertyFromGroup(self->prop, name) ? 1 : 0;
+ return IDP_GetPropertyFromGroup(self->prop, name) ? 1 : 0;
}
PyDoc_STRVAR(BPy_IDGroup_update_doc,
-".. method:: update(other)\n"
-"\n"
-" Update key, values.\n"
-"\n"
-" :arg other: Updates the values in the group with this.\n"
-" :type other: :class:`IDPropertyGroup` or dict\n"
-);
+ ".. method:: update(other)\n"
+ "\n"
+ " Update key, values.\n"
+ "\n"
+ " :arg other: Updates the values in the group with this.\n"
+ " :type other: :class:`IDPropertyGroup` or dict\n");
static PyObject *BPy_IDGroup_update(BPy_IDProperty *self, PyObject *value)
{
- PyObject *pkey, *pval;
- Py_ssize_t i = 0;
-
- if (BPy_IDGroup_Check(value)) {
- BPy_IDProperty *other = (BPy_IDProperty *)value;
- if (UNLIKELY(self->prop == other->prop)) {
- Py_RETURN_NONE;
- }
-
- /* XXX, possible one is inside the other */
- IDP_MergeGroup(self->prop, other->prop, true);
- }
- else if (PyDict_Check(value)) {
- while (PyDict_Next(value, &i, &pkey, &pval)) {
- BPy_IDGroup_Map_SetItem(self, pkey, pval);
- if (PyErr_Occurred()) {
- return NULL;
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "expected a dict or an IDPropertyGroup type, not a %.200s",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
-
-
- Py_RETURN_NONE;
+ PyObject *pkey, *pval;
+ Py_ssize_t i = 0;
+
+ if (BPy_IDGroup_Check(value)) {
+ BPy_IDProperty *other = (BPy_IDProperty *)value;
+ if (UNLIKELY(self->prop == other->prop)) {
+ Py_RETURN_NONE;
+ }
+
+ /* XXX, possible one is inside the other */
+ IDP_MergeGroup(self->prop, other->prop, true);
+ }
+ else if (PyDict_Check(value)) {
+ while (PyDict_Next(value, &i, &pkey, &pval)) {
+ BPy_IDGroup_Map_SetItem(self, pkey, pval);
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "expected a dict or an IDPropertyGroup type, not a %.200s",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_IDGroup_to_dict_doc,
-".. method:: to_dict()\n"
-"\n"
-" Return a purely python version of the group.\n"
-);
+ ".. method:: to_dict()\n"
+ "\n"
+ " Return a purely python version of the group.\n");
static PyObject *BPy_IDGroup_to_dict(BPy_IDProperty *self)
{
- return BPy_IDGroup_MapDataToPy(self->prop);
+ return BPy_IDGroup_MapDataToPy(self->prop);
}
PyDoc_STRVAR(BPy_IDGroup_clear_doc,
-".. method:: clear()\n"
-"\n"
-" Clear all members from this group.\n"
-);
+ ".. method:: clear()\n"
+ "\n"
+ " Clear all members from this group.\n");
static PyObject *BPy_IDGroup_clear(BPy_IDProperty *self)
{
- IDP_ClearProperty(self->prop);
- Py_RETURN_NONE;
+ IDP_ClearProperty(self->prop);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_IDGroup_get_doc,
-".. method:: get(key, default=None)\n"
-"\n"
-" Return the value for key, if it exists, else default.\n"
-);
+ ".. method:: get(key, default=None)\n"
+ "\n"
+ " Return the value for key, if it exists, else default.\n");
static PyObject *BPy_IDGroup_get(BPy_IDProperty *self, PyObject *args)
{
- IDProperty *idprop;
- const char *key;
- PyObject *def = Py_None;
+ IDProperty *idprop;
+ const char *key;
+ PyObject *def = Py_None;
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
+ return NULL;
+ }
- idprop = IDP_GetPropertyFromGroup(self->prop, key);
- if (idprop) {
- PyObject *pyobj = BPy_IDGroup_WrapData(self->id, idprop, self->prop);
- if (pyobj) {
- return pyobj;
- }
- }
+ idprop = IDP_GetPropertyFromGroup(self->prop, key);
+ if (idprop) {
+ PyObject *pyobj = BPy_IDGroup_WrapData(self->id, idprop, self->prop);
+ if (pyobj) {
+ return pyobj;
+ }
+ }
- Py_INCREF(def);
- return def;
+ Py_INCREF(def);
+ return def;
}
static struct PyMethodDef BPy_IDGroup_methods[] = {
- {"pop", (PyCFunction)BPy_IDGroup_pop, METH_VARARGS, BPy_IDGroup_pop_doc},
- {"iteritems", (PyCFunction)BPy_IDGroup_iter_items, METH_NOARGS, BPy_IDGroup_iter_items_doc},
- {"keys", (PyCFunction)BPy_IDGroup_keys, METH_NOARGS, BPy_IDGroup_keys_doc},
- {"values", (PyCFunction)BPy_IDGroup_values, METH_NOARGS, BPy_IDGroup_values_doc},
- {"items", (PyCFunction)BPy_IDGroup_items, METH_NOARGS, BPy_IDGroup_items_doc},
- {"update", (PyCFunction)BPy_IDGroup_update, METH_O, BPy_IDGroup_update_doc},
- {"get", (PyCFunction)BPy_IDGroup_get, METH_VARARGS, BPy_IDGroup_get_doc},
- {"to_dict", (PyCFunction)BPy_IDGroup_to_dict, METH_NOARGS, BPy_IDGroup_to_dict_doc},
- {"clear", (PyCFunction)BPy_IDGroup_clear, METH_NOARGS, BPy_IDGroup_clear_doc},
- {NULL, NULL, 0, NULL},
+ {"pop", (PyCFunction)BPy_IDGroup_pop, METH_VARARGS, BPy_IDGroup_pop_doc},
+ {"iteritems", (PyCFunction)BPy_IDGroup_iter_items, METH_NOARGS, BPy_IDGroup_iter_items_doc},
+ {"keys", (PyCFunction)BPy_IDGroup_keys, METH_NOARGS, BPy_IDGroup_keys_doc},
+ {"values", (PyCFunction)BPy_IDGroup_values, METH_NOARGS, BPy_IDGroup_values_doc},
+ {"items", (PyCFunction)BPy_IDGroup_items, METH_NOARGS, BPy_IDGroup_items_doc},
+ {"update", (PyCFunction)BPy_IDGroup_update, METH_O, BPy_IDGroup_update_doc},
+ {"get", (PyCFunction)BPy_IDGroup_get, METH_VARARGS, BPy_IDGroup_get_doc},
+ {"to_dict", (PyCFunction)BPy_IDGroup_to_dict, METH_NOARGS, BPy_IDGroup_to_dict_doc},
+ {"clear", (PyCFunction)BPy_IDGroup_clear, METH_NOARGS, BPy_IDGroup_clear_doc},
+ {NULL, NULL, 0, NULL},
};
static PySequenceMethods BPy_IDGroup_Seq = {
- (lenfunc) BPy_IDGroup_Map_Len, /* lenfunc sq_length */
- NULL, /* binaryfunc sq_concat */
- NULL, /* ssizeargfunc sq_repeat */
- NULL, /* ssizeargfunc sq_item */ /* TODO - setting this will allow PySequence_Check to return True */
- NULL, /* intintargfunc ***was_sq_slice*** */
- NULL, /* intobjargproc sq_ass_item */
- NULL, /* ssizeobjargproc ***was_sq_ass_slice*** */
- (objobjproc) BPy_IDGroup_Contains, /* objobjproc sq_contains */
- NULL, /* binaryfunc sq_inplace_concat */
- NULL, /* ssizeargfunc sq_inplace_repeat */
+ (lenfunc)BPy_IDGroup_Map_Len, /* lenfunc sq_length */
+ NULL, /* binaryfunc sq_concat */
+ NULL, /* ssizeargfunc sq_repeat */
+ NULL,
+ /* ssizeargfunc sq_item */ /* TODO - setting this will allow PySequence_Check to return True */
+ NULL, /* intintargfunc ***was_sq_slice*** */
+ NULL, /* intobjargproc sq_ass_item */
+ NULL, /* ssizeobjargproc ***was_sq_ass_slice*** */
+ (objobjproc)BPy_IDGroup_Contains, /* objobjproc sq_contains */
+ NULL, /* binaryfunc sq_inplace_concat */
+ NULL, /* ssizeargfunc sq_inplace_repeat */
};
static PyMappingMethods BPy_IDGroup_Mapping = {
- (lenfunc)BPy_IDGroup_Map_Len, /*inquiry mp_length */
- (binaryfunc)BPy_IDGroup_Map_GetItem, /*binaryfunc mp_subscript */
- (objobjargproc)BPy_IDGroup_Map_SetItem, /*objobjargproc mp_ass_subscript */
+ (lenfunc)BPy_IDGroup_Map_Len, /*inquiry mp_length */
+ (binaryfunc)BPy_IDGroup_Map_GetItem, /*binaryfunc mp_subscript */
+ (objobjargproc)BPy_IDGroup_Map_SetItem, /*objobjargproc mp_ass_subscript */
};
PyTypeObject BPy_IDGroup_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* For printing, in format "<module>.<name>" */
- "IDPropertyGroup", /* char *tp_name; */
- sizeof(BPy_IDProperty), /* int tp_basicsize; */
- 0, /* tp_itemsize; For allocation */
-
- /* Methods to implement standard operations */
-
- NULL, /* destructor tp_dealloc; */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* cmpfunc tp_compare; */
- (reprfunc)BPy_IDGroup_repr, /* reprfunc tp_repr; */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- &BPy_IDGroup_Seq, /* PySequenceMethods *tp_as_sequence; */
- &BPy_IDGroup_Mapping, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- (hashfunc)BPy_IDGroup_hash, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- (getiterfunc)BPy_IDGroup_iter, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
- /*** Attribute descriptor and subclassing stuff ***/
- BPy_IDGroup_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- BPy_IDGroup_getseters, /* struct PyGetSetDef *tp_getset; */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* For printing, in format "<module>.<name>" */
+ "IDPropertyGroup", /* char *tp_name; */
+ sizeof(BPy_IDProperty), /* int tp_basicsize; */
+ 0, /* tp_itemsize; For allocation */
+
+ /* Methods to implement standard operations */
+
+ NULL, /* destructor tp_dealloc; */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL, /* cmpfunc tp_compare; */
+ (reprfunc)BPy_IDGroup_repr, /* reprfunc tp_repr; */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ &BPy_IDGroup_Seq, /* PySequenceMethods *tp_as_sequence; */
+ &BPy_IDGroup_Mapping, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ (hashfunc)BPy_IDGroup_hash, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ (getiterfunc)BPy_IDGroup_iter, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+ /*** Attribute descriptor and subclassing stuff ***/
+ BPy_IDGroup_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ BPy_IDGroup_getseters, /* struct PyGetSetDef *tp_getset; */
};
/********Array Wrapper********/
static PyTypeObject *idp_array_py_type(BPy_IDArray *self, bool *r_is_double)
{
- switch (self->prop->subtype) {
- case IDP_FLOAT:
- *r_is_double = false;
- return &PyFloat_Type;
- case IDP_DOUBLE:
- *r_is_double = true;
- return &PyFloat_Type;
- case IDP_INT:
- *r_is_double = false;
- return &PyLong_Type;
- default:
- *r_is_double = false;
- return NULL;
- }
+ switch (self->prop->subtype) {
+ case IDP_FLOAT:
+ *r_is_double = false;
+ return &PyFloat_Type;
+ case IDP_DOUBLE:
+ *r_is_double = true;
+ return &PyFloat_Type;
+ case IDP_INT:
+ *r_is_double = false;
+ return &PyLong_Type;
+ default:
+ *r_is_double = false;
+ return NULL;
+ }
}
static PyObject *BPy_IDArray_repr(BPy_IDArray *self)
{
- return PyUnicode_FromFormat("<bpy id property array [%d]>", self->prop->len);
+ return PyUnicode_FromFormat("<bpy id property array [%d]>", self->prop->len);
}
PyDoc_STRVAR(BPy_IDArray_get_typecode_doc,
-"The type of the data in the array {'f': float, 'd': double, 'i': int}."
-);
+ "The type of the data in the array {'f': float, 'd': double, 'i': int}.");
static PyObject *BPy_IDArray_get_typecode(BPy_IDArray *self)
{
- switch (self->prop->subtype) {
- case IDP_FLOAT: return PyUnicode_FromString("f");
- case IDP_DOUBLE: return PyUnicode_FromString("d");
- case IDP_INT: return PyUnicode_FromString("i");
- }
+ switch (self->prop->subtype) {
+ case IDP_FLOAT:
+ return PyUnicode_FromString("f");
+ case IDP_DOUBLE:
+ return PyUnicode_FromString("d");
+ case IDP_INT:
+ return PyUnicode_FromString("i");
+ }
- PyErr_Format(PyExc_RuntimeError,
- "%s: invalid/corrupt array type '%d'!",
- __func__, self->prop->subtype);
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: invalid/corrupt array type '%d'!", __func__, self->prop->subtype);
- return NULL;
+ return NULL;
}
static PyGetSetDef BPy_IDArray_getseters[] = {
- /* matches pythons array.typecode */
- {(char *)"typecode", (getter)BPy_IDArray_get_typecode, (setter)NULL, BPy_IDArray_get_typecode_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL},
+ /* matches pythons array.typecode */
+ {(char *)"typecode",
+ (getter)BPy_IDArray_get_typecode,
+ (setter)NULL,
+ BPy_IDArray_get_typecode_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL},
};
PyDoc_STRVAR(BPy_IDArray_to_list_doc,
-".. method:: to_list()\n"
-"\n"
-" Return the array as a list.\n"
-);
+ ".. method:: to_list()\n"
+ "\n"
+ " Return the array as a list.\n");
static PyObject *BPy_IDArray_to_list(BPy_IDArray *self)
{
- return BPy_IDGroup_MapDataToPy(self->prop);
+ return BPy_IDGroup_MapDataToPy(self->prop);
}
static PyMethodDef BPy_IDArray_methods[] = {
- {"to_list", (PyCFunction)BPy_IDArray_to_list, METH_NOARGS, BPy_IDArray_to_list_doc},
- {NULL, NULL, 0, NULL},
+ {"to_list", (PyCFunction)BPy_IDArray_to_list, METH_NOARGS, BPy_IDArray_to_list_doc},
+ {NULL, NULL, 0, NULL},
};
static int BPy_IDArray_Len(BPy_IDArray *self)
{
- return self->prop->len;
+ return self->prop->len;
}
static PyObject *BPy_IDArray_GetItem(BPy_IDArray *self, int index)
{
- if (index < 0 || index >= self->prop->len) {
- PyErr_SetString(PyExc_IndexError, "index out of range!");
- return NULL;
- }
+ if (index < 0 || index >= self->prop->len) {
+ PyErr_SetString(PyExc_IndexError, "index out of range!");
+ return NULL;
+ }
- switch (self->prop->subtype) {
- case IDP_FLOAT:
- return PyFloat_FromDouble(((float *)IDP_Array(self->prop))[index]);
- case IDP_DOUBLE:
- return PyFloat_FromDouble(((double *)IDP_Array(self->prop))[index]);
- case IDP_INT:
- return PyLong_FromLong((long)((int *)IDP_Array(self->prop))[index]);
- }
+ switch (self->prop->subtype) {
+ case IDP_FLOAT:
+ return PyFloat_FromDouble(((float *)IDP_Array(self->prop))[index]);
+ case IDP_DOUBLE:
+ return PyFloat_FromDouble(((double *)IDP_Array(self->prop))[index]);
+ case IDP_INT:
+ return PyLong_FromLong((long)((int *)IDP_Array(self->prop))[index]);
+ }
- PyErr_Format(PyExc_RuntimeError,
- "%s: invalid/corrupt array type '%d'!",
- __func__, self->prop->subtype);
+ PyErr_Format(
+ PyExc_RuntimeError, "%s: invalid/corrupt array type '%d'!", __func__, self->prop->subtype);
- return NULL;
+ return NULL;
}
static int BPy_IDArray_SetItem(BPy_IDArray *self, int index, PyObject *value)
{
- if (index < 0 || index >= self->prop->len) {
- PyErr_SetString(PyExc_RuntimeError, "index out of range!");
- return -1;
- }
-
- switch (self->prop->subtype) {
- case IDP_FLOAT:
- {
- const float f = (float)PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) {
- return -1;
- }
- ((float *)IDP_Array(self->prop))[index] = f;
- break;
- }
- case IDP_DOUBLE:
- {
- const double d = PyFloat_AsDouble(value);
- if (d == -1 && PyErr_Occurred()) {
- return -1;
- }
- ((double *)IDP_Array(self->prop))[index] = d;
- break;
- }
- case IDP_INT:
- {
- const int i = PyC_Long_AsI32(value);
- if (i == -1 && PyErr_Occurred()) {
- return -1;
- }
-
- ((int *)IDP_Array(self->prop))[index] = i;
- break;
- }
- }
- return 0;
+ if (index < 0 || index >= self->prop->len) {
+ PyErr_SetString(PyExc_RuntimeError, "index out of range!");
+ return -1;
+ }
+
+ switch (self->prop->subtype) {
+ case IDP_FLOAT: {
+ const float f = (float)PyFloat_AsDouble(value);
+ if (f == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+ ((float *)IDP_Array(self->prop))[index] = f;
+ break;
+ }
+ case IDP_DOUBLE: {
+ const double d = PyFloat_AsDouble(value);
+ if (d == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+ ((double *)IDP_Array(self->prop))[index] = d;
+ break;
+ }
+ case IDP_INT: {
+ const int i = PyC_Long_AsI32(value);
+ if (i == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+
+ ((int *)IDP_Array(self->prop))[index] = i;
+ break;
+ }
+ }
+ return 0;
}
static PySequenceMethods BPy_IDArray_Seq = {
- (lenfunc) BPy_IDArray_Len, /* inquiry sq_length */
- NULL, /* binaryfunc sq_concat */
- NULL, /* intargfunc sq_repeat */
- (ssizeargfunc)BPy_IDArray_GetItem, /* intargfunc sq_item */
- NULL, /* intintargfunc sq_slice */
- (ssizeobjargproc)BPy_IDArray_SetItem, /* intobjargproc sq_ass_item */
- NULL, /* intintobjargproc sq_ass_slice */
- NULL, /* objobjproc sq_contains */
- /* Added in release 2.0 */
- NULL, /* binaryfunc sq_inplace_concat */
- NULL, /* intargfunc sq_inplace_repeat */
+ (lenfunc)BPy_IDArray_Len, /* inquiry sq_length */
+ NULL, /* binaryfunc sq_concat */
+ NULL, /* intargfunc sq_repeat */
+ (ssizeargfunc)BPy_IDArray_GetItem, /* intargfunc sq_item */
+ NULL, /* intintargfunc sq_slice */
+ (ssizeobjargproc)BPy_IDArray_SetItem, /* intobjargproc sq_ass_item */
+ NULL, /* intintobjargproc sq_ass_slice */
+ NULL, /* objobjproc sq_contains */
+ /* Added in release 2.0 */
+ NULL, /* binaryfunc sq_inplace_concat */
+ NULL, /* intargfunc sq_inplace_repeat */
};
-
-
/* sequence slice (get): idparr[a:b] */
static PyObject *BPy_IDArray_slice(BPy_IDArray *self, int begin, int end)
{
- IDProperty *prop = self->prop;
- PyObject *tuple;
- int count;
-
- CLAMP(begin, 0, prop->len);
- if (end < 0) {
- end = prop->len + end + 1;
- }
- CLAMP(end, 0, prop->len);
- begin = MIN2(begin, end);
-
- tuple = PyTuple_New(end - begin);
-
- switch (prop->subtype) {
- case IDP_FLOAT:
- {
- const float *array = (float *)IDP_Array(prop);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
- }
- break;
- }
- case IDP_DOUBLE:
- {
- const double *array = (double *)IDP_Array(prop);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
- }
- break;
- }
- case IDP_INT:
- {
- const int *array = (int *)IDP_Array(prop);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyLong_FromLong(array[count]));
- }
- break;
- }
- }
-
- return tuple;
+ IDProperty *prop = self->prop;
+ PyObject *tuple;
+ int count;
+
+ CLAMP(begin, 0, prop->len);
+ if (end < 0) {
+ end = prop->len + end + 1;
+ }
+ CLAMP(end, 0, prop->len);
+ begin = MIN2(begin, end);
+
+ tuple = PyTuple_New(end - begin);
+
+ switch (prop->subtype) {
+ case IDP_FLOAT: {
+ const float *array = (float *)IDP_Array(prop);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
+ }
+ break;
+ }
+ case IDP_DOUBLE: {
+ const double *array = (double *)IDP_Array(prop);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
+ }
+ break;
+ }
+ case IDP_INT: {
+ const int *array = (int *)IDP_Array(prop);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyLong_FromLong(array[count]));
+ }
+ break;
+ }
+ }
+
+ return tuple;
}
/* sequence slice (set): idparr[a:b] = value */
static int BPy_IDArray_ass_slice(BPy_IDArray *self, int begin, int end, PyObject *seq)
{
- IDProperty *prop = self->prop;
- bool is_double;
- const PyTypeObject *py_type = idp_array_py_type(self, &is_double);
- const size_t elem_size = is_double ? sizeof(double) : sizeof(float);
- size_t alloc_len;
- size_t size;
- void *vec;
+ IDProperty *prop = self->prop;
+ bool is_double;
+ const PyTypeObject *py_type = idp_array_py_type(self, &is_double);
+ const size_t elem_size = is_double ? sizeof(double) : sizeof(float);
+ size_t alloc_len;
+ size_t size;
+ void *vec;
- CLAMP(begin, 0, prop->len);
- CLAMP(end, 0, prop->len);
- begin = MIN2(begin, end);
+ CLAMP(begin, 0, prop->len);
+ CLAMP(end, 0, prop->len);
+ begin = MIN2(begin, end);
- size = (end - begin);
- alloc_len = size * elem_size;
+ size = (end - begin);
+ alloc_len = size * elem_size;
- vec = MEM_mallocN(alloc_len, "array assignment"); /* NOTE: we count on int/float being the same size here */
- if (PyC_AsArray(vec, seq, size, py_type, is_double, "slice assignment: ") == -1) {
- MEM_freeN(vec);
- return -1;
- }
+ vec = MEM_mallocN(alloc_len,
+ "array assignment"); /* NOTE: we count on int/float being the same size here */
+ if (PyC_AsArray(vec, seq, size, py_type, is_double, "slice assignment: ") == -1) {
+ MEM_freeN(vec);
+ return -1;
+ }
- memcpy((void *)(((char *)IDP_Array(prop)) + (begin * elem_size)), vec, alloc_len);
+ memcpy((void *)(((char *)IDP_Array(prop)) + (begin * elem_size)), vec, alloc_len);
- MEM_freeN(vec);
- return 0;
+ MEM_freeN(vec);
+ return 0;
}
static PyObject *BPy_IDArray_subscript(BPy_IDArray *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 += self->prop->len;
- }
- return BPy_IDArray_GetItem(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return BPy_IDArray_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "vector indices must be integers, not %.200s",
- __func__, Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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 += self->prop->len;
+ }
+ return BPy_IDArray_GetItem(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return BPy_IDArray_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "vector indices must be integers, not %.200s",
+ __func__,
+ Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static int BPy_IDArray_ass_subscript(BPy_IDArray *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 += self->prop->len;
- }
- return BPy_IDArray_SetItem(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0) {
- return -1;
- }
-
- if (step == 1) {
- return BPy_IDArray_ass_slice(self, start, stop, value);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "vector indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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 += self->prop->len;
+ }
+ return BPy_IDArray_SetItem(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0) {
+ return -1;
+ }
+
+ if (step == 1) {
+ return BPy_IDArray_ass_slice(self, start, stop, value);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
static PyMappingMethods BPy_IDArray_AsMapping = {
- (lenfunc)BPy_IDArray_Len,
- (binaryfunc)BPy_IDArray_subscript,
- (objobjargproc)BPy_IDArray_ass_subscript,
+ (lenfunc)BPy_IDArray_Len,
+ (binaryfunc)BPy_IDArray_subscript,
+ (objobjargproc)BPy_IDArray_ass_subscript,
};
static int itemsize_by_idarray_type(int array_type)
{
- if (array_type == IDP_INT) { return sizeof(int); }
- if (array_type == IDP_FLOAT) { return sizeof(float); }
- if (array_type == IDP_DOUBLE) { return sizeof(double); }
- return -1; /* should never happen */
+ if (array_type == IDP_INT) {
+ return sizeof(int);
+ }
+ if (array_type == IDP_FLOAT) {
+ return sizeof(float);
+ }
+ if (array_type == IDP_DOUBLE) {
+ return sizeof(double);
+ }
+ return -1; /* should never happen */
}
static int BPy_IDArray_getbuffer(BPy_IDArray *self, Py_buffer *view, int flags)
{
- IDProperty *prop = self->prop;
- int itemsize = itemsize_by_idarray_type(prop->subtype);
- int length = itemsize * prop->len;
+ IDProperty *prop = self->prop;
+ int itemsize = itemsize_by_idarray_type(prop->subtype);
+ int length = itemsize * prop->len;
- if (PyBuffer_FillInfo(view, (PyObject *)self, IDP_Array(prop), length, false, flags) == -1) {
- return -1;
- }
+ if (PyBuffer_FillInfo(view, (PyObject *)self, IDP_Array(prop), length, false, flags) == -1) {
+ return -1;
+ }
- view->itemsize = itemsize;
- view->format = (char *)idp_format_from_array_type(prop->subtype);
+ view->itemsize = itemsize;
+ view->format = (char *)idp_format_from_array_type(prop->subtype);
- Py_ssize_t *shape = MEM_mallocN(sizeof(Py_ssize_t), __func__);
- shape[0] = prop->len;
- view->shape = shape;
+ Py_ssize_t *shape = MEM_mallocN(sizeof(Py_ssize_t), __func__);
+ shape[0] = prop->len;
+ view->shape = shape;
- return 0;
+ return 0;
}
static void BPy_IDArray_releasebuffer(BPy_IDArray *UNUSED(self), Py_buffer *view)
{
- MEM_freeN(view->shape);
+ MEM_freeN(view->shape);
}
static PyBufferProcs BPy_IDArray_Buffer = {
- (getbufferproc)BPy_IDArray_getbuffer,
- (releasebufferproc)BPy_IDArray_releasebuffer,
+ (getbufferproc)BPy_IDArray_getbuffer,
+ (releasebufferproc)BPy_IDArray_releasebuffer,
};
-
PyTypeObject BPy_IDArray_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* For printing, in format "<module>.<name>" */
- "IDPropertyArray", /* char *tp_name; */
- sizeof(BPy_IDArray), /* int tp_basicsize; */
- 0, /* tp_itemsize; For allocation */
-
- /* Methods to implement standard operations */
-
- NULL, /* destructor tp_dealloc; */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* cmpfunc tp_compare; */
- (reprfunc)BPy_IDArray_repr, /* reprfunc tp_repr; */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- &BPy_IDArray_Seq, /* PySequenceMethods *tp_as_sequence; */
- &BPy_IDArray_AsMapping, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- &BPy_IDArray_Buffer, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- BPy_IDArray_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- BPy_IDArray_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* For printing, in format "<module>.<name>" */
+ "IDPropertyArray", /* char *tp_name; */
+ sizeof(BPy_IDArray), /* int tp_basicsize; */
+ 0, /* tp_itemsize; For allocation */
+
+ /* Methods to implement standard operations */
+
+ NULL, /* destructor tp_dealloc; */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL, /* cmpfunc tp_compare; */
+ (reprfunc)BPy_IDArray_repr, /* reprfunc tp_repr; */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ &BPy_IDArray_Seq, /* PySequenceMethods *tp_as_sequence; */
+ &BPy_IDArray_AsMapping, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ &BPy_IDArray_Buffer, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ BPy_IDArray_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ BPy_IDArray_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
/*********** ID Property Group iterator ********/
static PyObject *IDGroup_Iter_repr(BPy_IDGroup_Iter *self)
{
- return PyUnicode_FromFormat("(ID Property Group Iter \"%s\")", self->group->prop->name);
+ return PyUnicode_FromFormat("(ID Property Group Iter \"%s\")", self->group->prop->name);
}
static PyObject *BPy_Group_Iter_Next(BPy_IDGroup_Iter *self)
{
- if (self->cur) {
- PyObject *ret;
- IDProperty *cur;
+ if (self->cur) {
+ PyObject *ret;
+ IDProperty *cur;
- cur = self->cur;
- self->cur = self->cur->next;
+ cur = self->cur;
+ self->cur = self->cur->next;
- if (self->mode == IDPROP_ITER_ITEMS) {
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- PyUnicode_FromString(cur->name),
- BPy_IDGroup_WrapData(self->group->id, cur, self->group->prop));
- return ret;
- }
- else {
- return PyUnicode_FromString(cur->name);
- }
- }
- else {
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
+ if (self->mode == IDPROP_ITER_ITEMS) {
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret,
+ PyUnicode_FromString(cur->name),
+ BPy_IDGroup_WrapData(self->group->id, cur, self->group->prop));
+ return ret;
+ }
+ else {
+ return PyUnicode_FromString(cur->name);
+ }
+ }
+ else {
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
}
PyTypeObject BPy_IDGroup_Iter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* For printing, in format "<module>.<name>" */
- "IDPropertyGroupIter", /* char *tp_name; */
- sizeof(BPy_IDGroup_Iter), /* int tp_basicsize; */
- 0, /* tp_itemsize; For allocation */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* For printing, in format "<module>.<name>" */
+ "IDPropertyGroupIter", /* char *tp_name; */
+ sizeof(BPy_IDGroup_Iter), /* int tp_basicsize; */
+ 0, /* tp_itemsize; For allocation */
- /* Methods to implement standard operations */
+ /* Methods to implement standard operations */
- NULL, /* destructor tp_dealloc; */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* cmpfunc tp_compare; */
- (reprfunc) IDGroup_Iter_repr, /* reprfunc tp_repr; */
+ NULL, /* destructor tp_dealloc; */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL, /* cmpfunc tp_compare; */
+ (reprfunc)IDGroup_Iter_repr, /* reprfunc tp_repr; */
- /* Method suites for standard classes */
+ /* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
- /* More standard operations (here for binary compatibility) */
+ /* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
- /*** Added in release 2.2 ***/
- /* Iterators */
- PyObject_SelfIter, /* getiterfunc tp_iter; */
- (iternextfunc) BPy_Group_Iter_Next, /* iternextfunc tp_iternext; */
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ PyObject_SelfIter, /* getiterfunc tp_iter; */
+ (iternextfunc)BPy_Group_Iter_Next, /* iternextfunc tp_iternext; */
};
void IDProp_Init_Types(void)
{
- PyType_Ready(&BPy_IDGroup_Type);
- PyType_Ready(&BPy_IDGroup_Iter_Type);
- PyType_Ready(&BPy_IDArray_Type);
+ PyType_Ready(&BPy_IDGroup_Type);
+ PyType_Ready(&BPy_IDGroup_Iter_Type);
+ PyType_Ready(&BPy_IDArray_Type);
}
/*----------------------------MODULE INIT-------------------------*/
@@ -1763,71 +1753,70 @@ void IDProp_Init_Types(void)
/* --- */
static struct PyModuleDef IDProp_types_module_def = {
- PyModuleDef_HEAD_INIT,
- "idprop.types", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "idprop.types", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
static PyObject *BPyInit_idprop_types(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&IDProp_types_module_def);
+ submodule = PyModule_Create(&IDProp_types_module_def);
- IDProp_Init_Types();
+ IDProp_Init_Types();
#define MODULE_TYPE_ADD(s, t) \
- PyModule_AddObject(s, t.tp_name, (PyObject *)&t); Py_INCREF((PyObject *)&t)
+ PyModule_AddObject(s, t.tp_name, (PyObject *)&t); \
+ Py_INCREF((PyObject *)&t)
- /* bmesh_py_types.c */
- MODULE_TYPE_ADD(submodule, BPy_IDGroup_Type);
- MODULE_TYPE_ADD(submodule, BPy_IDGroup_Iter_Type);
- MODULE_TYPE_ADD(submodule, BPy_IDArray_Type);
+ /* bmesh_py_types.c */
+ MODULE_TYPE_ADD(submodule, BPy_IDGroup_Type);
+ MODULE_TYPE_ADD(submodule, BPy_IDGroup_Iter_Type);
+ MODULE_TYPE_ADD(submodule, BPy_IDArray_Type);
#undef MODULE_TYPE_ADD
- return submodule;
+ return submodule;
}
/* --- */
static PyMethodDef IDProp_methods[] = {
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
-
PyDoc_STRVAR(IDProp_module_doc,
-"This module provides access id property types (currently mainly for docs)."
-);
+ "This module provides access id property types (currently mainly for docs).");
static struct PyModuleDef IDProp_module_def = {
- PyModuleDef_HEAD_INIT,
- "idprop", /* m_name */
- IDProp_module_doc, /* m_doc */
- 0, /* m_size */
- IDProp_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "idprop", /* m_name */
+ IDProp_module_doc, /* m_doc */
+ 0, /* m_size */
+ IDProp_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit_idprop(void)
{
- PyObject *mod;
- PyObject *submodule;
- PyObject *sys_modules = PyImport_GetModuleDict();
+ PyObject *mod;
+ PyObject *submodule;
+ PyObject *sys_modules = PyImport_GetModuleDict();
- mod = PyModule_Create(&IDProp_module_def);
+ mod = PyModule_Create(&IDProp_module_def);
- /* idprop.types */
- PyModule_AddObject(mod, "types", (submodule = BPyInit_idprop_types()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ /* idprop.types */
+ PyModule_AddObject(mod, "types", (submodule = BPyInit_idprop_types()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- return mod;
+ return mod;
}
diff --git a/source/blender/python/generic/idprop_py_api.h b/source/blender/python/generic/idprop_py_api.h
index 369b8359c55..49094f95ecb 100644
--- a/source/blender/python/generic/idprop_py_api.h
+++ b/source/blender/python/generic/idprop_py_api.h
@@ -18,7 +18,6 @@
* \ingroup pygen
*/
-
#ifndef __IDPROP_PY_API_H__
#define __IDPROP_PY_API_H__
@@ -30,32 +29,29 @@ extern PyTypeObject BPy_IDArray_Type;
extern PyTypeObject BPy_IDGroup_Iter_Type;
extern PyTypeObject BPy_IDGroup_Type;
-#define BPy_IDArray_Check(v) (PyObject_TypeCheck(v, &BPy_IDArray_Type))
-#define BPy_IDArray_CheckExact(v) (Py_TYPE(v) == &BPy_IDArray_Type)
-#define BPy_IDGroup_Iter_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Iter_Type))
-#define BPy_IDGroup_Iter_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Iter_Type)
-#define BPy_IDGroup_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Type))
-#define BPy_IDGroup_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Type)
+#define BPy_IDArray_Check(v) (PyObject_TypeCheck(v, &BPy_IDArray_Type))
+#define BPy_IDArray_CheckExact(v) (Py_TYPE(v) == &BPy_IDArray_Type)
+#define BPy_IDGroup_Iter_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Iter_Type))
+#define BPy_IDGroup_Iter_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Iter_Type)
+#define BPy_IDGroup_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Type))
+#define BPy_IDGroup_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Type)
typedef struct BPy_IDProperty {
- PyObject_VAR_HEAD
- struct ID *id; /* can be NULL */
- struct IDProperty *prop; /* must be second member */
- struct IDProperty *parent;
- PyObject *data_wrap;
+ PyObject_VAR_HEAD struct ID *id; /* can be NULL */
+ struct IDProperty *prop; /* must be second member */
+ struct IDProperty *parent;
+ PyObject *data_wrap;
} BPy_IDProperty;
typedef struct BPy_IDArray {
- PyObject_VAR_HEAD
- struct ID *id; /* can be NULL */
- struct IDProperty *prop; /* must be second member */
+ PyObject_VAR_HEAD struct ID *id; /* can be NULL */
+ struct IDProperty *prop; /* must be second member */
} BPy_IDArray;
typedef struct BPy_IDGroup_Iter {
- PyObject_VAR_HEAD
- BPy_IDProperty *group;
- struct IDProperty *cur;
- int mode;
+ PyObject_VAR_HEAD BPy_IDProperty *group;
+ struct IDProperty *cur;
+ int mode;
} BPy_IDGroup_Iter;
PyObject *BPy_Wrap_GetKeys(struct IDProperty *prop);
@@ -63,7 +59,6 @@ PyObject *BPy_Wrap_GetValues(struct ID *id, struct IDProperty *prop);
PyObject *BPy_Wrap_GetItems(struct ID *id, struct IDProperty *prop);
int BPy_Wrap_SetMapItem(struct IDProperty *prop, PyObject *key, PyObject *val);
-
PyObject *BPy_IDGroup_WrapData(struct ID *id, struct IDProperty *prop, struct IDProperty *parent);
bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *key, struct IDProperty *group, PyObject *ob);
@@ -71,7 +66,7 @@ void IDProp_Init_Types(void);
PyObject *BPyInit_idprop(void);
-#define IDPROP_ITER_KEYS 0
-#define IDPROP_ITER_ITEMS 1
+#define IDPROP_ITER_KEYS 0
+#define IDPROP_ITER_ITEMS 1
#endif /* __IDPROP_PY_API_H__ */
diff --git a/source/blender/python/generic/imbuf_py_api.c b/source/blender/python/generic/imbuf_py_api.c
index ed9994276c5..26e4e5bcf32 100644
--- a/source/blender/python/generic/imbuf_py_api.c
+++ b/source/blender/python/generic/imbuf_py_api.c
@@ -29,7 +29,7 @@
#include "python_utildefines.h"
-#include "imbuf_py_api.h" /* own include */
+#include "imbuf_py_api.h" /* own include */
#include "../../imbuf/IMB_imbuf.h"
#include "../../imbuf/IMB_imbuf_types.h"
@@ -46,28 +46,33 @@ static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf);
* \{ */
typedef struct Py_ImBuf {
- PyObject_VAR_HEAD
- /* can be NULL */
- ImBuf *ibuf;
+ PyObject_VAR_HEAD
+ /* can be NULL */
+ ImBuf *ibuf;
} Py_ImBuf;
static int py_imbuf_valid_check(Py_ImBuf *self)
{
- if (LIKELY(self->ibuf)) {
- return 0;
- }
- else {
- PyErr_Format(PyExc_ReferenceError,
- "ImBuf data of type %.200s has been freed",
- Py_TYPE(self)->tp_name);
- return -1;
- }
+ if (LIKELY(self->ibuf)) {
+ return 0;
+ }
+ else {
+ PyErr_Format(
+ PyExc_ReferenceError, "ImBuf data of type %.200s has been freed", Py_TYPE(self)->tp_name);
+ return -1;
+ }
}
#define PY_IMBUF_CHECK_OBJ(obj) \
- if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { return NULL; } ((void)0)
+ if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { \
+ return NULL; \
+ } \
+ ((void)0)
#define PY_IMBUF_CHECK_INT(obj) \
- if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { return -1; } ((void)0)
+ if (UNLIKELY(py_imbuf_valid_check(obj) == -1)) { \
+ return -1; \
+ } \
+ ((void)0)
/** \} */
@@ -76,77 +81,72 @@ static int py_imbuf_valid_check(Py_ImBuf *self)
* \{ */
PyDoc_STRVAR(py_imbuf_resize_doc,
-".. method:: resize(size, method='FAST')\n"
-"\n"
-" Resize the image.\n"
-"\n"
-" :arg size: New size.\n"
-" :type size: pair of ints\n"
-" :arg method: Method of resizing (TODO)\n"
-" :type method: str\n"
-);
+ ".. method:: resize(size, method='FAST')\n"
+ "\n"
+ " Resize the image.\n"
+ "\n"
+ " :arg size: New size.\n"
+ " :type size: pair of ints\n"
+ " :arg method: Method of resizing (TODO)\n"
+ " :type method: str\n");
static PyObject *py_imbuf_resize(Py_ImBuf *self, PyObject *args, PyObject *kw)
{
- PY_IMBUF_CHECK_OBJ(self);
-
- uint size[2];
- char *method = NULL;
-
- static const char *_keywords[] = {"size", "method", NULL};
- static _PyArg_Parser _parser = {"(II)|s:resize", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &size[0], &size[1],
- &method))
- {
- return NULL;
- }
- IMB_scaleImBuf(self->ibuf, UNPACK2(size));
- Py_RETURN_NONE;
+ PY_IMBUF_CHECK_OBJ(self);
+
+ uint size[2];
+ char *method = NULL;
+
+ static const char *_keywords[] = {"size", "method", NULL};
+ static _PyArg_Parser _parser = {"(II)|s:resize", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &size[0], &size[1], &method)) {
+ return NULL;
+ }
+ IMB_scaleImBuf(self->ibuf, UNPACK2(size));
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(py_imbuf_copy_doc,
-".. method:: copy()\n"
-"\n"
-" :return: A copy of the image.\n"
-" :rtype: :class:`ImBuf`\n"
-);
+ ".. method:: copy()\n"
+ "\n"
+ " :return: A copy of the image.\n"
+ " :rtype: :class:`ImBuf`\n");
static PyObject *py_imbuf_copy(Py_ImBuf *self)
{
- PY_IMBUF_CHECK_OBJ(self);
- return Py_ImBuf_CreatePyObject(self->ibuf);
+ PY_IMBUF_CHECK_OBJ(self);
+ return Py_ImBuf_CreatePyObject(self->ibuf);
}
static PyObject *py_imbuf_deepcopy(Py_ImBuf *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return py_imbuf_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return py_imbuf_copy(self);
}
-
PyDoc_STRVAR(py_imbuf_free_doc,
-".. method:: free()\n"
-"\n"
-" Clear image data immediately (causing an error on re-use).\n"
-);
+ ".. method:: free()\n"
+ "\n"
+ " Clear image data immediately (causing an error on re-use).\n");
static PyObject *py_imbuf_free(Py_ImBuf *self)
{
- if (self->ibuf) {
- IMB_freeImBuf(self->ibuf);
- self->ibuf = NULL;
- }
- Py_RETURN_NONE;
+ if (self->ibuf) {
+ IMB_freeImBuf(self->ibuf);
+ self->ibuf = NULL;
+ }
+ Py_RETURN_NONE;
}
static struct PyMethodDef Py_ImBuf_methods[] = {
- {"resize", (PyCFunction)py_imbuf_resize, METH_VARARGS | METH_KEYWORDS, (char *)py_imbuf_resize_doc},
- {"free", (PyCFunction)py_imbuf_free, METH_NOARGS, (char *)py_imbuf_free_doc},
- {"copy", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc},
- {"__copy__", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc},
- {"__deepcopy__", (PyCFunction)py_imbuf_deepcopy, METH_VARARGS, (char *)py_imbuf_copy_doc},
- {NULL, NULL, 0, NULL},
+ {"resize",
+ (PyCFunction)py_imbuf_resize,
+ METH_VARARGS | METH_KEYWORDS,
+ (char *)py_imbuf_resize_doc},
+ {"free", (PyCFunction)py_imbuf_free, METH_NOARGS, (char *)py_imbuf_free_doc},
+ {"copy", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc},
+ {"__copy__", (PyCFunction)py_imbuf_copy, METH_NOARGS, (char *)py_imbuf_copy_doc},
+ {"__deepcopy__", (PyCFunction)py_imbuf_deepcopy, METH_VARARGS, (char *)py_imbuf_copy_doc},
+ {NULL, NULL, 0, NULL},
};
/** \} */
@@ -155,50 +155,50 @@ static struct PyMethodDef Py_ImBuf_methods[] = {
/** \name Attributes
* \{ */
-PyDoc_STRVAR(py_imbuf_size_doc,
-"size of the image in pixels.\n\n:type: pair of ints"
-);
+PyDoc_STRVAR(py_imbuf_size_doc, "size of the image in pixels.\n\n:type: pair of ints");
static PyObject *py_imbuf_size_get(Py_ImBuf *self, void *UNUSED(closure))
{
- PY_IMBUF_CHECK_OBJ(self);
- ImBuf *ibuf = self->ibuf;
- return PyC_Tuple_Pack_I32(ibuf->x, ibuf->y);
+ PY_IMBUF_CHECK_OBJ(self);
+ ImBuf *ibuf = self->ibuf;
+ return PyC_Tuple_Pack_I32(ibuf->x, ibuf->y);
}
-PyDoc_STRVAR(py_imbuf_ppm_doc,
-"pixels per meter.\n\n:type: pair of floats"
-);
+PyDoc_STRVAR(py_imbuf_ppm_doc, "pixels per meter.\n\n:type: pair of floats");
static PyObject *py_imbuf_ppm_get(Py_ImBuf *self, void *UNUSED(closure))
{
- PY_IMBUF_CHECK_OBJ(self);
- ImBuf *ibuf = self->ibuf;
- return PyC_Tuple_Pack_F64(ibuf->ppm[0], ibuf->ppm[1]);
+ PY_IMBUF_CHECK_OBJ(self);
+ ImBuf *ibuf = self->ibuf;
+ return PyC_Tuple_Pack_F64(ibuf->ppm[0], ibuf->ppm[1]);
}
static int py_imbuf_ppm_set(Py_ImBuf *self, PyObject *value, void *UNUSED(closure))
{
- PY_IMBUF_CHECK_INT(self);
- double ppm[2];
-
- if (PyC_AsArray(ppm, value, 2, &PyFloat_Type, true, "ppm") == -1) {
- return -1;
- }
-
- if (ppm[0] <= 0.0 || ppm[1] <= 0.0) {
- PyErr_SetString(PyExc_ValueError, "invalid ppm value");
- return -1;
- }
-
- ImBuf *ibuf = self->ibuf;
- ibuf->ppm[0] = ppm[0];
- ibuf->ppm[1] = ppm[1];
- return 0;
+ PY_IMBUF_CHECK_INT(self);
+ double ppm[2];
+
+ if (PyC_AsArray(ppm, value, 2, &PyFloat_Type, true, "ppm") == -1) {
+ return -1;
+ }
+
+ if (ppm[0] <= 0.0 || ppm[1] <= 0.0) {
+ PyErr_SetString(PyExc_ValueError, "invalid ppm value");
+ return -1;
+ }
+
+ ImBuf *ibuf = self->ibuf;
+ ibuf->ppm[0] = ppm[0];
+ ibuf->ppm[1] = ppm[1];
+ return 0;
}
static PyGetSetDef Py_ImBuf_getseters[] = {
- {(char *)"size", (getter)py_imbuf_size_get, (setter)NULL, (char *)py_imbuf_size_doc, NULL},
- {(char *)"ppm", (getter)py_imbuf_ppm_get, (setter)py_imbuf_ppm_set, (char *)py_imbuf_ppm_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"size", (getter)py_imbuf_size_get, (setter)NULL, (char *)py_imbuf_size_doc, NULL},
+ {(char *)"ppm",
+ (getter)py_imbuf_ppm_get,
+ (setter)py_imbuf_ppm_set,
+ (char *)py_imbuf_ppm_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/** \} */
@@ -209,99 +209,97 @@ static PyGetSetDef Py_ImBuf_getseters[] = {
static void py_imbuf_dealloc(Py_ImBuf *self)
{
- ImBuf *ibuf = self->ibuf;
- if (ibuf != NULL) {
- IMB_freeImBuf(self->ibuf);
- self->ibuf = NULL;
- }
- PyObject_DEL(self);
+ ImBuf *ibuf = self->ibuf;
+ if (ibuf != NULL) {
+ IMB_freeImBuf(self->ibuf);
+ self->ibuf = NULL;
+ }
+ PyObject_DEL(self);
}
static PyObject *py_imbuf_repr(Py_ImBuf *self)
{
- const ImBuf *ibuf = self->ibuf;
- if (ibuf != NULL) {
- return PyUnicode_FromFormat(
- "<imbuf: address=%p, filename='%s', size=(%d, %d)>",
- ibuf, ibuf->name, ibuf->x, ibuf->y);
- }
- else {
- return PyUnicode_FromString(
- "<imbuf: address=0x0>");
- }
+ const ImBuf *ibuf = self->ibuf;
+ if (ibuf != NULL) {
+ return PyUnicode_FromFormat(
+ "<imbuf: address=%p, filename='%s', size=(%d, %d)>", ibuf, ibuf->name, ibuf->x, ibuf->y);
+ }
+ else {
+ return PyUnicode_FromString("<imbuf: address=0x0>");
+ }
}
static Py_hash_t py_imbuf_hash(Py_ImBuf *self)
{
- return _Py_HashPointer(self->ibuf);
+ return _Py_HashPointer(self->ibuf);
}
PyTypeObject Py_ImBuf_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* For printing, in format "<module>.<name>" */
- "ImBuf", /* tp_name */
- sizeof(Py_ImBuf), /* int tp_basicsize; */
- 0, /* tp_itemsize; For allocation */
-
- /* Methods to implement standard operations */
-
- (destructor)py_imbuf_dealloc, /* destructor tp_dealloc; */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* cmpfunc tp_compare; */
- (reprfunc)py_imbuf_repr, /* reprfunc tp_repr; */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- (hashfunc)py_imbuf_hash, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
- /*** Attribute descriptor and subclassing stuff ***/
- Py_ImBuf_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- Py_ImBuf_getseters, /* struct PyGetSetDef *tp_getset; */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* For printing, in format "<module>.<name>" */
+ "ImBuf", /* tp_name */
+ sizeof(Py_ImBuf), /* int tp_basicsize; */
+ 0, /* tp_itemsize; For allocation */
+
+ /* Methods to implement standard operations */
+
+ (destructor)py_imbuf_dealloc, /* destructor tp_dealloc; */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL, /* cmpfunc tp_compare; */
+ (reprfunc)py_imbuf_repr, /* reprfunc tp_repr; */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ (hashfunc)py_imbuf_hash, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+ /*** Attribute descriptor and subclassing stuff ***/
+ Py_ImBuf_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ Py_ImBuf_getseters, /* struct PyGetSetDef *tp_getset; */
};
static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf)
{
- Py_ImBuf *self = PyObject_New(Py_ImBuf, &Py_ImBuf_Type);
- self->ibuf = ibuf;
- return (PyObject *)self;
+ Py_ImBuf *self = PyObject_New(Py_ImBuf, &Py_ImBuf_Type);
+ self->ibuf = ibuf;
+ return (PyObject *)self;
}
/** \} */
@@ -311,118 +309,107 @@ static PyObject *Py_ImBuf_CreatePyObject(ImBuf *ibuf)
* \{ */
PyDoc_STRVAR(M_imbuf_new_doc,
-".. function:: new(size)\n"
-"\n"
-" Load a new image.\n"
-"\n"
-" :arg size: The size of the image in pixels.\n"
-" :type size: pair of ints\n"
-" :return: the newly loaded image.\n"
-" :rtype: :class:`ImBuf`\n"
-);
+ ".. function:: new(size)\n"
+ "\n"
+ " Load a new image.\n"
+ "\n"
+ " :arg size: The size of the image in pixels.\n"
+ " :type size: pair of ints\n"
+ " :return: the newly loaded image.\n"
+ " :rtype: :class:`ImBuf`\n");
static PyObject *M_imbuf_new(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- int size[2];
- static const char *_keywords[] = {"size", NULL};
- static _PyArg_Parser _parser = {"(ii)|i:new", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &size[0], &size[1]))
- {
- return NULL;
- }
-
- /* TODO, make options */
- uchar planes = 4;
- uint flags = IB_rect;
-
- ImBuf *ibuf = IMB_allocImBuf(UNPACK2(size), planes, flags);
- if (ibuf == NULL) {
- PyErr_Format(PyExc_ValueError, "new: Unable to create image (%d, %d)", UNPACK2(size));
- return NULL;
- }
- return Py_ImBuf_CreatePyObject(ibuf);
+ int size[2];
+ static const char *_keywords[] = {"size", NULL};
+ static _PyArg_Parser _parser = {"(ii)|i:new", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &size[0], &size[1])) {
+ return NULL;
+ }
+
+ /* TODO, make options */
+ uchar planes = 4;
+ uint flags = IB_rect;
+
+ ImBuf *ibuf = IMB_allocImBuf(UNPACK2(size), planes, flags);
+ if (ibuf == NULL) {
+ PyErr_Format(PyExc_ValueError, "new: Unable to create image (%d, %d)", UNPACK2(size));
+ return NULL;
+ }
+ return Py_ImBuf_CreatePyObject(ibuf);
}
PyDoc_STRVAR(M_imbuf_load_doc,
-".. function:: load(filename)\n"
-"\n"
-" Load an image from a file.\n"
-"\n"
-" :arg filename: the filename of the image.\n"
-" :type filename: string\n"
-" :return: the newly loaded image.\n"
-" :rtype: :class:`ImBuf`\n"
-);
+ ".. function:: load(filename)\n"
+ "\n"
+ " Load an image from a file.\n"
+ "\n"
+ " :arg filename: the filename of the image.\n"
+ " :type filename: string\n"
+ " :return: the newly loaded image.\n"
+ " :rtype: :class:`ImBuf`\n");
static PyObject *M_imbuf_load(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- const char *filename;
+ const char *filename;
- static const char *_keywords[] = {"filename", NULL};
- static _PyArg_Parser _parser = {"s:load", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &filename))
- {
- return NULL;
- }
+ static const char *_keywords[] = {"filename", NULL};
+ static _PyArg_Parser _parser = {"s:load", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &filename)) {
+ return NULL;
+ }
- const int file = BLI_open(filename, O_BINARY | O_RDONLY, 0);
- if (file == -1) {
- PyErr_Format(PyExc_IOError, "load: %s, failed to open file '%s'", strerror(errno));
- return NULL;
- }
+ const int file = BLI_open(filename, O_BINARY | O_RDONLY, 0);
+ if (file == -1) {
+ PyErr_Format(PyExc_IOError, "load: %s, failed to open file '%s'", strerror(errno));
+ return NULL;
+ }
- ImBuf *ibuf = IMB_loadifffile(file, filename, IB_rect, NULL, filename);
+ ImBuf *ibuf = IMB_loadifffile(file, filename, IB_rect, NULL, filename);
- close(file);
+ close(file);
- if (ibuf == NULL) {
- PyErr_Format(PyExc_ValueError, "load: Unable to recognize image format for file '%s'", filename);
- return NULL;
- }
+ if (ibuf == NULL) {
+ PyErr_Format(
+ PyExc_ValueError, "load: Unable to recognize image format for file '%s'", filename);
+ return NULL;
+ }
- BLI_strncpy(ibuf->name, filename, sizeof(ibuf->name));
+ BLI_strncpy(ibuf->name, filename, sizeof(ibuf->name));
- return Py_ImBuf_CreatePyObject(ibuf);
+ return Py_ImBuf_CreatePyObject(ibuf);
}
PyDoc_STRVAR(M_imbuf_write_doc,
-".. function:: write(image, filename)\n"
-"\n"
-" Write an image.\n"
-"\n"
-" :arg image: the image to write.\n"
-" :type image: :class:`ImBuf`\n"
-" :arg filename: the filename of the image.\n"
-" :type filename: string\n"
-);
+ ".. function:: write(image, filename)\n"
+ "\n"
+ " Write an image.\n"
+ "\n"
+ " :arg image: the image to write.\n"
+ " :type image: :class:`ImBuf`\n"
+ " :arg filename: the filename of the image.\n"
+ " :type filename: string\n");
static PyObject *M_imbuf_write(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- Py_ImBuf *py_imb;
- const char *filename = NULL;
-
- static const char *_keywords[] = {"image", "filename", NULL};
- static _PyArg_Parser _parser = {"O!|s:write", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &Py_ImBuf_Type, &py_imb,
- &filename))
- {
- return NULL;
- }
-
- if (filename == NULL) {
- filename = py_imb->ibuf->name;
- }
-
- bool ok = IMB_saveiff(py_imb->ibuf, filename, IB_rect);
- if (ok == false) {
- PyErr_Format(PyExc_IOError, "write: Unable to write image file (%s) '%s'", strerror(errno), filename);
- return NULL;
- }
-
- Py_RETURN_NONE;
+ Py_ImBuf *py_imb;
+ const char *filename = NULL;
+
+ static const char *_keywords[] = {"image", "filename", NULL};
+ static _PyArg_Parser _parser = {"O!|s:write", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &Py_ImBuf_Type, &py_imb, &filename)) {
+ return NULL;
+ }
+
+ if (filename == NULL) {
+ filename = py_imb->ibuf->name;
+ }
+
+ bool ok = IMB_saveiff(py_imb->ibuf, filename, IB_rect);
+ if (ok == false) {
+ PyErr_Format(
+ PyExc_IOError, "write: Unable to write image file (%s) '%s'", strerror(errno), filename);
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
/** \} */
@@ -432,36 +419,34 @@ static PyObject *M_imbuf_write(PyObject *UNUSED(self), PyObject *args, PyObject
* \{ */
static PyMethodDef IMB_methods[] = {
- {"new", (PyCFunction) M_imbuf_new, METH_VARARGS | METH_KEYWORDS, M_imbuf_new_doc},
- {"load", (PyCFunction) M_imbuf_load, METH_VARARGS | METH_KEYWORDS, M_imbuf_load_doc},
- {"write", (PyCFunction) M_imbuf_write, METH_VARARGS | METH_KEYWORDS, M_imbuf_write_doc},
- {NULL, NULL, 0, NULL},
+ {"new", (PyCFunction)M_imbuf_new, METH_VARARGS | METH_KEYWORDS, M_imbuf_new_doc},
+ {"load", (PyCFunction)M_imbuf_load, METH_VARARGS | METH_KEYWORDS, M_imbuf_load_doc},
+ {"write", (PyCFunction)M_imbuf_write, METH_VARARGS | METH_KEYWORDS, M_imbuf_write_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(IMB_doc,
-"This module provides access to Blender's image manipulation API."
-);
+PyDoc_STRVAR(IMB_doc, "This module provides access to Blender's image manipulation API.");
static struct PyModuleDef IMB_module_def = {
- PyModuleDef_HEAD_INIT,
- "imbuf", /* m_name */
- IMB_doc, /* m_doc */
- 0, /* m_size */
- IMB_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "imbuf", /* m_name */
+ IMB_doc, /* m_doc */
+ 0, /* m_size */
+ IMB_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit_imbuf(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&IMB_module_def);
+ submodule = PyModule_Create(&IMB_module_def);
- PyType_Ready(&Py_ImBuf_Type);
+ PyType_Ready(&Py_ImBuf_Type);
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/generic/imbuf_py_api.h b/source/blender/python/generic/imbuf_py_api.h
index c36c4ba11f6..2dea925a9f2 100644
--- a/source/blender/python/generic/imbuf_py_api.h
+++ b/source/blender/python/generic/imbuf_py_api.h
@@ -25,4 +25,4 @@ PyObject *BPyInit_imbuf(void);
extern PyTypeObject Py_ImBuf_Type;
-#endif /* __IMBUF_PY_API_H__ */
+#endif /* __IMBUF_PY_API_H__ */
diff --git a/source/blender/python/generic/py_capi_utils.c b/source/blender/python/generic/py_capi_utils.c
index 0c10737609c..191863a862d 100644
--- a/source/blender/python/generic/py_capi_utils.c
+++ b/source/blender/python/generic/py_capi_utils.c
@@ -28,7 +28,7 @@
#include <Python.h>
#include <frameobject.h>
-#include "BLI_utildefines.h" /* for bool */
+#include "BLI_utildefines.h" /* for bool */
#include "py_capi_utils.h"
@@ -38,90 +38,97 @@
#ifndef MATH_STANDALONE
/* only for BLI_strncpy_wchar_from_utf8, should replace with py funcs but too late in release now */
-#include "BLI_string_utf8.h"
+# include "BLI_string_utf8.h"
#endif
#ifdef _WIN32
-#include "BLI_math_base.h" /* isfinite() */
+# include "BLI_math_base.h" /* isfinite() */
#endif
/* array utility function */
-int PyC_AsArray_FAST(
- void *array, PyObject *value_fast, const Py_ssize_t length,
- const PyTypeObject *type, const bool is_double, const char *error_prefix)
+int PyC_AsArray_FAST(void *array,
+ PyObject *value_fast,
+ const Py_ssize_t length,
+ const PyTypeObject *type,
+ const bool is_double,
+ const char *error_prefix)
{
- const Py_ssize_t value_len = PySequence_Fast_GET_SIZE(value_fast);
- PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
- Py_ssize_t i;
-
- BLI_assert(PyList_Check(value_fast) || PyTuple_Check(value_fast));
-
- if (value_len != length) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: invalid sequence length. expected %d, got %d",
- error_prefix, length, value_len);
- return -1;
- }
-
- /* for each type */
- if (type == &PyFloat_Type) {
- if (is_double) {
- double *array_double = array;
- for (i = 0; i < length; i++) {
- array_double[i] = PyFloat_AsDouble(value_fast_items[i]);
- }
- }
- else {
- float *array_float = array;
- for (i = 0; i < length; i++) {
- array_float[i] = PyFloat_AsDouble(value_fast_items[i]);
- }
- }
- }
- else if (type == &PyLong_Type) {
- /* could use is_double for 'long int' but no use now */
- int *array_int = array;
- for (i = 0; i < length; i++) {
- array_int[i] = PyC_Long_AsI32(value_fast_items[i]);
- }
- }
- else if (type == &PyBool_Type) {
- bool *array_bool = array;
- for (i = 0; i < length; i++) {
- array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%s: internal error %s is invalid",
- error_prefix, type->tp_name);
- return -1;
- }
-
- if (PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%s: one or more items could not be used as a %s",
- error_prefix, type->tp_name);
- return -1;
- }
-
- return 0;
+ const Py_ssize_t value_len = PySequence_Fast_GET_SIZE(value_fast);
+ PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
+ Py_ssize_t i;
+
+ BLI_assert(PyList_Check(value_fast) || PyTuple_Check(value_fast));
+
+ if (value_len != length) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: invalid sequence length. expected %d, got %d",
+ error_prefix,
+ length,
+ value_len);
+ return -1;
+ }
+
+ /* for each type */
+ if (type == &PyFloat_Type) {
+ if (is_double) {
+ double *array_double = array;
+ for (i = 0; i < length; i++) {
+ array_double[i] = PyFloat_AsDouble(value_fast_items[i]);
+ }
+ }
+ else {
+ float *array_float = array;
+ for (i = 0; i < length; i++) {
+ array_float[i] = PyFloat_AsDouble(value_fast_items[i]);
+ }
+ }
+ }
+ else if (type == &PyLong_Type) {
+ /* could use is_double for 'long int' but no use now */
+ int *array_int = array;
+ for (i = 0; i < length; i++) {
+ array_int[i] = PyC_Long_AsI32(value_fast_items[i]);
+ }
+ }
+ else if (type == &PyBool_Type) {
+ bool *array_bool = array;
+ for (i = 0; i < length; i++) {
+ array_bool[i] = (PyLong_AsLong(value_fast_items[i]) != 0);
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "%s: internal error %s is invalid", error_prefix, type->tp_name);
+ return -1;
+ }
+
+ if (PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: one or more items could not be used as a %s",
+ error_prefix,
+ type->tp_name);
+ return -1;
+ }
+
+ return 0;
}
-int PyC_AsArray(
- void *array, PyObject *value, const Py_ssize_t length,
- const PyTypeObject *type, const bool is_double, const char *error_prefix)
+int PyC_AsArray(void *array,
+ PyObject *value,
+ const Py_ssize_t length,
+ const PyTypeObject *type,
+ const bool is_double,
+ const char *error_prefix)
{
- PyObject *value_fast;
- int ret;
+ PyObject *value_fast;
+ int ret;
- if (!(value_fast = PySequence_Fast(value, error_prefix))) {
- return -1;
- }
+ if (!(value_fast = PySequence_Fast(value, error_prefix))) {
+ return -1;
+ }
- ret = PyC_AsArray_FAST(array, value_fast, length, type, is_double, error_prefix);
- Py_DECREF(value_fast);
- return ret;
+ ret = PyC_AsArray_FAST(array, value_fast, length, type, is_double, error_prefix);
+ Py_DECREF(value_fast);
+ return ret;
}
/* -------------------------------------------------------------------- */
@@ -134,47 +141,47 @@ int PyC_AsArray(
/* array utility function */
PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len)
{
- PyObject *tuple = PyTuple_New(len);
- for (uint i = 0; i < len; i++) {
- PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
- }
- return tuple;
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
+ }
+ return tuple;
}
PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len)
{
- PyObject *tuple = PyTuple_New(len);
- for (uint i = 0; i < len; i++) {
- PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
- }
- return tuple;
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
+ }
+ return tuple;
}
PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len)
{
- PyObject *tuple = PyTuple_New(len);
- for (uint i = 0; i < len; i++) {
- PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array[i]));
- }
- return tuple;
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array[i]));
+ }
+ return tuple;
}
PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len)
{
- PyObject *tuple = PyTuple_New(len);
- for (uint i = 0; i < len; i++) {
- PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
- }
- return tuple;
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
+ }
+ return tuple;
}
PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len)
{
- PyObject *tuple = PyTuple_New(len);
- for (uint i = 0; i < len; i++) {
- PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
- }
- return tuple;
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
+ }
+ return tuple;
}
/** \} */
@@ -185,24 +192,24 @@ PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len)
*/
void PyC_Tuple_Fill(PyObject *tuple, PyObject *value)
{
- unsigned int tot = PyTuple_GET_SIZE(tuple);
- unsigned int i;
+ unsigned int tot = PyTuple_GET_SIZE(tuple);
+ unsigned int i;
- for (i = 0; i < tot; i++) {
- PyTuple_SET_ITEM(tuple, i, value);
- Py_INCREF(value);
- }
+ for (i = 0; i < tot; i++) {
+ PyTuple_SET_ITEM(tuple, i, value);
+ Py_INCREF(value);
+ }
}
void PyC_List_Fill(PyObject *list, PyObject *value)
{
- unsigned int tot = PyList_GET_SIZE(list);
- unsigned int i;
+ unsigned int tot = PyList_GET_SIZE(list);
+ unsigned int i;
- for (i = 0; i < tot; i++) {
- PyList_SET_ITEM(list, i, value);
- Py_INCREF(value);
- }
+ for (i = 0; i < tot; i++) {
+ PyList_SET_ITEM(list, i, value);
+ Py_INCREF(value);
+ }
}
/**
@@ -212,24 +219,22 @@ void PyC_List_Fill(PyObject *list, PyObject *value)
*/
int PyC_ParseBool(PyObject *o, void *p)
{
- bool *bool_p = p;
- long value;
- if (((value = PyLong_AsLong(o)) == -1) || !ELEM(value, 0, 1)) {
- PyErr_Format(PyExc_ValueError,
- "expected a bool or int (0/1), got %s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
-
- *bool_p = value ? true : false;
- return 1;
+ bool *bool_p = p;
+ long value;
+ if (((value = PyLong_AsLong(o)) == -1) || !ELEM(value, 0, 1)) {
+ PyErr_Format(PyExc_ValueError, "expected a bool or int (0/1), got %s", Py_TYPE(o)->tp_name);
+ return 0;
+ }
+
+ *bool_p = value ? true : false;
+ return 1;
}
/* silly function, we dont use arg. just check its compatible with __deepcopy__ */
int PyC_CheckArgs_DeepCopy(PyObject *args)
{
- PyObject *dummy_pydict;
- return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0;
+ PyObject *dummy_pydict;
+ return PyArg_ParseTuple(args, "|O!:__deepcopy__", &PyDict_Type, &dummy_pydict) != 0;
}
#ifndef MATH_STANDALONE
@@ -237,18 +242,20 @@ int PyC_CheckArgs_DeepCopy(PyObject *args)
/* for debugging */
void PyC_ObSpit(const char *name, PyObject *var)
{
- const char *null_str = "<null>";
- fprintf(stderr, "<%s> : ", name);
- if (var == NULL) {
- fprintf(stderr, "%s\n", null_str);
- }
- else {
- PyObject_Print(var, stderr, 0);
- const PyTypeObject *type = Py_TYPE(var);
- fprintf(stderr,
- " ref:%d, ptr:%p, type: %s\n",
- (int)var->ob_refcnt, (void *)var, type ? type->tp_name : null_str);
- }
+ const char *null_str = "<null>";
+ fprintf(stderr, "<%s> : ", name);
+ if (var == NULL) {
+ fprintf(stderr, "%s\n", null_str);
+ }
+ else {
+ PyObject_Print(var, stderr, 0);
+ const PyTypeObject *type = Py_TYPE(var);
+ fprintf(stderr,
+ " ref:%d, ptr:%p, type: %s\n",
+ (int)var->ob_refcnt,
+ (void *)var,
+ type ? type->tp_name : null_str);
+ }
}
/**
@@ -257,169 +264,167 @@ void PyC_ObSpit(const char *name, PyObject *var)
*/
void PyC_ObSpitStr(char *result, size_t result_len, PyObject *var)
{
- /* No name, creator of string can manage that. */
- const char *null_str = "<null>";
- if (var == NULL) {
- BLI_snprintf(result, result_len, "%s", null_str);
- }
- else {
- const PyTypeObject *type = Py_TYPE(var);
- PyObject *var_str = PyObject_Repr(var);
- if (var_str == NULL) {
- /* We could print error here, but this may be used for generating errors - so don't for now. */
- PyErr_Clear();
- }
- BLI_snprintf(
- result, result_len,
- " ref=%d, ptr=%p, type=%s, value=%.200s",
- (int)var->ob_refcnt,
- (void *)var,
- type ? type->tp_name : null_str,
- var_str ? _PyUnicode_AsString(var_str) : "<error>");
- if (var_str != NULL) {
- Py_DECREF(var_str);
- }
- }
+ /* No name, creator of string can manage that. */
+ const char *null_str = "<null>";
+ if (var == NULL) {
+ BLI_snprintf(result, result_len, "%s", null_str);
+ }
+ else {
+ const PyTypeObject *type = Py_TYPE(var);
+ PyObject *var_str = PyObject_Repr(var);
+ if (var_str == NULL) {
+ /* We could print error here, but this may be used for generating errors - so don't for now. */
+ PyErr_Clear();
+ }
+ BLI_snprintf(result,
+ result_len,
+ " ref=%d, ptr=%p, type=%s, value=%.200s",
+ (int)var->ob_refcnt,
+ (void *)var,
+ type ? type->tp_name : null_str,
+ var_str ? _PyUnicode_AsString(var_str) : "<error>");
+ if (var_str != NULL) {
+ Py_DECREF(var_str);
+ }
+ }
}
void PyC_LineSpit(void)
{
- const char *filename;
- int lineno;
+ const char *filename;
+ int lineno;
- /* Note, allow calling from outside python (RNA) */
- if (!PyC_IsInterpreterActive()) {
- fprintf(stderr, "python line lookup failed, interpreter inactive\n");
- return;
- }
+ /* Note, allow calling from outside python (RNA) */
+ if (!PyC_IsInterpreterActive()) {
+ fprintf(stderr, "python line lookup failed, interpreter inactive\n");
+ return;
+ }
- PyErr_Clear();
- PyC_FileAndNum(&filename, &lineno);
+ PyErr_Clear();
+ PyC_FileAndNum(&filename, &lineno);
- fprintf(stderr, "%s:%d\n", filename, lineno);
+ fprintf(stderr, "%s:%d\n", filename, lineno);
}
void PyC_StackSpit(void)
{
- /* Note, allow calling from outside python (RNA) */
- if (!PyC_IsInterpreterActive()) {
- fprintf(stderr, "python line lookup failed, interpreter inactive\n");
- return;
- }
- else {
- /* lame but handy */
- PyGILState_STATE gilstate = PyGILState_Ensure();
- PyRun_SimpleString("__import__('traceback').print_stack()");
- PyGILState_Release(gilstate);
- }
+ /* Note, allow calling from outside python (RNA) */
+ if (!PyC_IsInterpreterActive()) {
+ fprintf(stderr, "python line lookup failed, interpreter inactive\n");
+ return;
+ }
+ else {
+ /* lame but handy */
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyRun_SimpleString("__import__('traceback').print_stack()");
+ PyGILState_Release(gilstate);
+ }
}
void PyC_FileAndNum(const char **filename, int *lineno)
{
- PyFrameObject *frame;
-
- if (filename) {
- *filename = NULL;
- }
- if (lineno) {
- *lineno = -1;
- }
-
- if (!(frame = PyThreadState_GET()->frame)) {
- return;
- }
-
- /* when executing a script */
- if (filename) {
- *filename = _PyUnicode_AsString(frame->f_code->co_filename);
- }
-
- /* when executing a module */
- if (filename && *filename == NULL) {
- /* try an alternative method to get the filename - module based
- * references below are all borrowed (double checked) */
- PyObject *mod_name = PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
- if (mod_name) {
- PyObject *mod = PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
- if (mod) {
- PyObject *mod_file = PyModule_GetFilenameObject(mod);
- if (mod_file) {
- *filename = _PyUnicode_AsString(mod_name);
- Py_DECREF(mod_file);
- }
- else {
- PyErr_Clear();
- }
- }
-
- /* unlikely, fallback */
- if (*filename == NULL) {
- *filename = _PyUnicode_AsString(mod_name);
- }
- }
- }
-
- if (lineno) {
- *lineno = PyFrame_GetLineNumber(frame);
- }
+ PyFrameObject *frame;
+
+ if (filename) {
+ *filename = NULL;
+ }
+ if (lineno) {
+ *lineno = -1;
+ }
+
+ if (!(frame = PyThreadState_GET()->frame)) {
+ return;
+ }
+
+ /* when executing a script */
+ if (filename) {
+ *filename = _PyUnicode_AsString(frame->f_code->co_filename);
+ }
+
+ /* when executing a module */
+ if (filename && *filename == NULL) {
+ /* try an alternative method to get the filename - module based
+ * references below are all borrowed (double checked) */
+ PyObject *mod_name = PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
+ if (mod_name) {
+ PyObject *mod = PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
+ if (mod) {
+ PyObject *mod_file = PyModule_GetFilenameObject(mod);
+ if (mod_file) {
+ *filename = _PyUnicode_AsString(mod_name);
+ Py_DECREF(mod_file);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
+
+ /* unlikely, fallback */
+ if (*filename == NULL) {
+ *filename = _PyUnicode_AsString(mod_name);
+ }
+ }
+ }
+
+ if (lineno) {
+ *lineno = PyFrame_GetLineNumber(frame);
+ }
}
void PyC_FileAndNum_Safe(const char **filename, int *lineno)
{
- if (!PyC_IsInterpreterActive()) {
- return;
- }
+ if (!PyC_IsInterpreterActive()) {
+ return;
+ }
- PyC_FileAndNum(filename, lineno);
+ PyC_FileAndNum(filename, lineno);
}
/* Would be nice if python had this built in */
PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
{
- Py_ssize_t i;
- PyObject *item = o;
- const char *attr;
-
- va_list vargs;
-
- va_start(vargs, n);
- for (i = 0; i < n; i++) {
- attr = va_arg(vargs, char *);
- item = PyObject_GetAttrString(item, attr);
-
- if (item) {
- Py_DECREF(item);
- }
- else {
- /* python will set the error value here */
- break;
- }
-
- }
- va_end(vargs);
-
- Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
- return item;
+ Py_ssize_t i;
+ PyObject *item = o;
+ const char *attr;
+
+ va_list vargs;
+
+ va_start(vargs, n);
+ for (i = 0; i < n; i++) {
+ attr = va_arg(vargs, char *);
+ item = PyObject_GetAttrString(item, attr);
+
+ if (item) {
+ Py_DECREF(item);
+ }
+ else {
+ /* python will set the error value here */
+ break;
+ }
+ }
+ va_end(vargs);
+
+ Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
+ return item;
}
PyObject *PyC_FrozenSetFromStrings(const char **strings)
{
- const char **str;
- PyObject *ret;
+ const char **str;
+ PyObject *ret;
- ret = PyFrozenSet_New(NULL);
+ ret = PyFrozenSet_New(NULL);
- for (str = strings; *str; str++) {
- PyObject *py_str = PyUnicode_FromString(*str);
- PySet_Add(ret, py_str);
- Py_DECREF(py_str);
- }
+ for (str = strings; *str; str++) {
+ PyObject *py_str = PyUnicode_FromString(*str);
+ PySet_Add(ret, py_str);
+ Py_DECREF(py_str);
+ }
- return ret;
+ return ret;
}
-
/**
* Similar to #PyErr_Format(),
*
@@ -429,45 +434,41 @@ PyObject *PyC_FrozenSetFromStrings(const char **strings)
*/
PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...)
{
- PyObject *error_value_prefix;
- va_list args;
-
- va_start(args, format);
- error_value_prefix = PyUnicode_FromFormatV(format, args); /* can fail and be NULL */
- va_end(args);
-
- if (PyErr_Occurred()) {
- PyObject *error_type, *error_value, *error_traceback;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
-
- if (PyUnicode_Check(error_value)) {
- PyErr_Format(exception_type_prefix,
- "%S, %S",
- error_value_prefix,
- error_value);
- }
- else {
- PyErr_Format(exception_type_prefix,
- "%S, %.200s(%S)",
- error_value_prefix,
- Py_TYPE(error_value)->tp_name,
- error_value);
- }
- }
- else {
- PyErr_SetObject(exception_type_prefix,
- error_value_prefix);
- }
-
- Py_XDECREF(error_value_prefix);
-
- /* dumb to always return NULL but matches PyErr_Format */
- return NULL;
+ PyObject *error_value_prefix;
+ va_list args;
+
+ va_start(args, format);
+ error_value_prefix = PyUnicode_FromFormatV(format, args); /* can fail and be NULL */
+ va_end(args);
+
+ if (PyErr_Occurred()) {
+ PyObject *error_type, *error_value, *error_traceback;
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+
+ if (PyUnicode_Check(error_value)) {
+ PyErr_Format(exception_type_prefix, "%S, %S", error_value_prefix, error_value);
+ }
+ else {
+ PyErr_Format(exception_type_prefix,
+ "%S, %.200s(%S)",
+ error_value_prefix,
+ Py_TYPE(error_value)->tp_name,
+ error_value);
+ }
+ }
+ else {
+ PyErr_SetObject(exception_type_prefix, error_value_prefix);
+ }
+
+ Py_XDECREF(error_value_prefix);
+
+ /* dumb to always return NULL but matches PyErr_Format */
+ return NULL;
}
PyObject *PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *str)
{
- return PyC_Err_Format_Prefix(exception_type_prefix, "%s", str);
+ return PyC_Err_Format_Prefix(exception_type_prefix, "%s", str);
}
/**
@@ -476,231 +477,228 @@ PyObject *PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *
*/
void PyC_Err_PrintWithFunc(PyObject *py_func)
{
- /* since we return to C code we can't leave the error */
- PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
- PyErr_Print();
- PyErr_Clear();
-
- /* use py style error */
- fprintf(stderr, "File \"%s\", line %d, in %s\n",
- _PyUnicode_AsString(f_code->co_filename),
- f_code->co_firstlineno,
- _PyUnicode_AsString(((PyFunctionObject *)py_func)->func_name)
- );
+ /* since we return to C code we can't leave the error */
+ PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
+ PyErr_Print();
+ PyErr_Clear();
+
+ /* use py style error */
+ fprintf(stderr,
+ "File \"%s\", line %d, in %s\n",
+ _PyUnicode_AsString(f_code->co_filename),
+ f_code->co_firstlineno,
+ _PyUnicode_AsString(((PyFunctionObject *)py_func)->func_name));
}
-
/* returns the exception string as a new PyUnicode object, depends on external traceback module */
-#if 0
+# if 0
/* this version uses traceback module but somehow fails on UI errors */
PyObject *PyC_ExceptionBuffer(void)
{
- PyObject *traceback_mod = NULL;
- PyObject *format_tb_func = NULL;
- PyObject *ret = NULL;
+ PyObject *traceback_mod = NULL;
+ PyObject *format_tb_func = NULL;
+ PyObject *ret = NULL;
- if (!(traceback_mod = PyImport_ImportModule("traceback"))) {
- goto error_cleanup;
- }
- else if (!(format_tb_func = PyObject_GetAttrString(traceback_mod, "format_exc"))) {
- goto error_cleanup;
- }
+ if (!(traceback_mod = PyImport_ImportModule("traceback"))) {
+ goto error_cleanup;
+ }
+ else if (!(format_tb_func = PyObject_GetAttrString(traceback_mod, "format_exc"))) {
+ goto error_cleanup;
+ }
- ret = PyObject_CallObject(format_tb_func, NULL);
+ ret = PyObject_CallObject(format_tb_func, NULL);
- if (ret == Py_None) {
- Py_DECREF(ret);
- ret = NULL;
- }
+ if (ret == Py_None) {
+ Py_DECREF(ret);
+ ret = NULL;
+ }
error_cleanup:
- /* could not import the module so print the error and close */
- Py_XDECREF(traceback_mod);
- Py_XDECREF(format_tb_func);
+ /* could not import the module so print the error and close */
+ Py_XDECREF(traceback_mod);
+ Py_XDECREF(format_tb_func);
- return ret;
+ return ret;
}
-#else /* verbose, non-threadsafe version */
+# else /* verbose, non-threadsafe version */
PyObject *PyC_ExceptionBuffer(void)
{
- PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
- PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
- PyObject *string_io = NULL;
- PyObject *string_io_buf = NULL;
- PyObject *string_io_mod = NULL;
- PyObject *string_io_getvalue = NULL;
-
- PyObject *error_type, *error_value, *error_traceback;
+ PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
+ PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
+ PyObject *string_io = NULL;
+ PyObject *string_io_buf = NULL;
+ PyObject *string_io_mod = NULL;
+ PyObject *string_io_getvalue = NULL;
- if (!PyErr_Occurred()) {
- return NULL;
- }
+ PyObject *error_type, *error_value, *error_traceback;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ if (!PyErr_Occurred()) {
+ return NULL;
+ }
- PyErr_Clear();
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
- /* import io
- * string_io = io.StringIO()
- */
+ PyErr_Clear();
- if (!(string_io_mod = PyImport_ImportModule("io"))) {
- goto error_cleanup;
- }
- else if (!(string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
- goto error_cleanup;
- }
- else if (!(string_io_getvalue = PyObject_GetAttrString(string_io, "getvalue"))) {
- goto error_cleanup;
- }
+ /* import io
+ * string_io = io.StringIO()
+ */
- Py_INCREF(stdout_backup); // since these were borrowed we don't want them freed when replaced.
- Py_INCREF(stderr_backup);
+ if (!(string_io_mod = PyImport_ImportModule("io"))) {
+ goto error_cleanup;
+ }
+ else if (!(string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
+ goto error_cleanup;
+ }
+ else if (!(string_io_getvalue = PyObject_GetAttrString(string_io, "getvalue"))) {
+ goto error_cleanup;
+ }
- PySys_SetObject("stdout", string_io); // both of these are freed when restoring
- PySys_SetObject("stderr", string_io);
+ Py_INCREF(stdout_backup); // since these were borrowed we don't want them freed when replaced.
+ Py_INCREF(stderr_backup);
- PyErr_Restore(error_type, error_value, error_traceback);
- PyErr_Print(); /* print the error */
- PyErr_Clear();
+ PySys_SetObject("stdout", string_io); // both of these are freed when restoring
+ PySys_SetObject("stderr", string_io);
- string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
+ PyErr_Restore(error_type, error_value, error_traceback);
+ PyErr_Print(); /* print the error */
+ PyErr_Clear();
- PySys_SetObject("stdout", stdout_backup);
- PySys_SetObject("stderr", stderr_backup);
+ string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
- Py_DECREF(stdout_backup); /* now sys owns the ref again */
- Py_DECREF(stderr_backup);
+ PySys_SetObject("stdout", stdout_backup);
+ PySys_SetObject("stderr", stderr_backup);
- Py_DECREF(string_io_mod);
- Py_DECREF(string_io_getvalue);
- Py_DECREF(string_io); /* free the original reference */
+ Py_DECREF(stdout_backup); /* now sys owns the ref again */
+ Py_DECREF(stderr_backup);
- PyErr_Clear();
- return string_io_buf;
+ Py_DECREF(string_io_mod);
+ Py_DECREF(string_io_getvalue);
+ Py_DECREF(string_io); /* free the original reference */
+ PyErr_Clear();
+ return string_io_buf;
error_cleanup:
- /* could not import the module so print the error and close */
- Py_XDECREF(string_io_mod);
- Py_XDECREF(string_io);
+ /* could not import the module so print the error and close */
+ Py_XDECREF(string_io_mod);
+ Py_XDECREF(string_io);
- PyErr_Restore(error_type, error_value, error_traceback);
- PyErr_Print(); /* print the error */
- PyErr_Clear();
+ PyErr_Restore(error_type, error_value, error_traceback);
+ PyErr_Print(); /* print the error */
+ PyErr_Clear();
- return NULL;
+ return NULL;
}
-#endif
+# endif
PyObject *PyC_ExceptionBuffer_Simple(void)
{
- PyObject *string_io_buf;
+ PyObject *string_io_buf;
- PyObject *error_type, *error_value, *error_traceback;
+ PyObject *error_type, *error_value, *error_traceback;
- if (!PyErr_Occurred()) {
- return NULL;
- }
+ if (!PyErr_Occurred()) {
+ return NULL;
+ }
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
- if (error_value == NULL) {
- return NULL;
- }
+ if (error_value == NULL) {
+ return NULL;
+ }
- string_io_buf = PyObject_Str(error_value);
- /* Python does this too */
- if (UNLIKELY(string_io_buf == NULL)) {
- string_io_buf = PyUnicode_FromFormat(
- "<unprintable %s object>", Py_TYPE(error_value)->tp_name);
- }
+ string_io_buf = PyObject_Str(error_value);
+ /* Python does this too */
+ if (UNLIKELY(string_io_buf == NULL)) {
+ string_io_buf = PyUnicode_FromFormat("<unprintable %s object>", Py_TYPE(error_value)->tp_name);
+ }
- PyErr_Restore(error_type, error_value, error_traceback);
+ PyErr_Restore(error_type, error_value, error_traceback);
- PyErr_Print();
- PyErr_Clear();
- return string_io_buf;
+ PyErr_Print();
+ PyErr_Clear();
+ return string_io_buf;
}
/* string conversion, escape non-unicode chars, coerce must be set to NULL */
const char *PyC_UnicodeAsByteAndSize(PyObject *py_str, Py_ssize_t *size, PyObject **coerce)
{
- const char *result;
-
- result = _PyUnicode_AsStringAndSize(py_str, size);
-
- if (result) {
- /* 99% of the time this is enough but we better support non unicode
- * chars since blender doesn't limit this */
- return result;
- }
- else {
- PyErr_Clear();
-
- if (PyBytes_Check(py_str)) {
- *size = PyBytes_GET_SIZE(py_str);
- return PyBytes_AS_STRING(py_str);
- }
- else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
- *size = PyBytes_GET_SIZE(*coerce);
- return PyBytes_AS_STRING(*coerce);
- }
- else {
- /* leave error raised from EncodeFS */
- return NULL;
- }
- }
+ const char *result;
+
+ result = _PyUnicode_AsStringAndSize(py_str, size);
+
+ if (result) {
+ /* 99% of the time this is enough but we better support non unicode
+ * chars since blender doesn't limit this */
+ return result;
+ }
+ else {
+ PyErr_Clear();
+
+ if (PyBytes_Check(py_str)) {
+ *size = PyBytes_GET_SIZE(py_str);
+ return PyBytes_AS_STRING(py_str);
+ }
+ else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
+ *size = PyBytes_GET_SIZE(*coerce);
+ return PyBytes_AS_STRING(*coerce);
+ }
+ else {
+ /* leave error raised from EncodeFS */
+ return NULL;
+ }
+ }
}
const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
{
- const char *result;
-
- result = _PyUnicode_AsString(py_str);
-
- if (result) {
- /* 99% of the time this is enough but we better support non unicode
- * chars since blender doesnt limit this */
- return result;
- }
- else {
- PyErr_Clear();
-
- if (PyBytes_Check(py_str)) {
- return PyBytes_AS_STRING(py_str);
- }
- else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
- return PyBytes_AS_STRING(*coerce);
- }
- else {
- /* leave error raised from EncodeFS */
- return NULL;
- }
- }
+ const char *result;
+
+ result = _PyUnicode_AsString(py_str);
+
+ if (result) {
+ /* 99% of the time this is enough but we better support non unicode
+ * chars since blender doesnt limit this */
+ return result;
+ }
+ else {
+ PyErr_Clear();
+
+ if (PyBytes_Check(py_str)) {
+ return PyBytes_AS_STRING(py_str);
+ }
+ else if ((*coerce = PyUnicode_EncodeFSDefault(py_str))) {
+ return PyBytes_AS_STRING(*coerce);
+ }
+ else {
+ /* leave error raised from EncodeFS */
+ return NULL;
+ }
+ }
}
PyObject *PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size)
{
- PyObject *result = PyUnicode_FromStringAndSize(str, size);
- if (result) {
- /* 99% of the time this is enough but we better support non unicode
- * chars since blender doesn't limit this */
- return result;
- }
- else {
- PyErr_Clear();
- /* this means paths will always be accessible once converted, on all OS's */
- result = PyUnicode_DecodeFSDefaultAndSize(str, size);
- return result;
- }
+ PyObject *result = PyUnicode_FromStringAndSize(str, size);
+ if (result) {
+ /* 99% of the time this is enough but we better support non unicode
+ * chars since blender doesn't limit this */
+ return result;
+ }
+ else {
+ PyErr_Clear();
+ /* this means paths will always be accessible once converted, on all OS's */
+ result = PyUnicode_DecodeFSDefaultAndSize(str, size);
+ return result;
+ }
}
PyObject *PyC_UnicodeFromByte(const char *str)
{
- return PyC_UnicodeFromByteAndSize(str, strlen(str));
+ return PyC_UnicodeFromByteAndSize(str, strlen(str));
}
/*****************************************************************************
@@ -717,107 +715,109 @@ PyObject *PyC_UnicodeFromByte(const char *str)
****************************************************************************/
PyObject *PyC_DefaultNameSpace(const char *filename)
{
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- PyObject *mod_main = PyModule_New("__main__");
- PyDict_SetItemString(interp->modules, "__main__", mod_main);
- Py_DECREF(mod_main); /* sys.modules owns now */
- PyModule_AddStringConstant(mod_main, "__name__", "__main__");
- if (filename) {
- /* __file__ mainly for nice UI'ness
- * note: this wont map to a real file when executing text-blocks and buttons. */
- PyModule_AddObject(mod_main, "__file__", PyC_UnicodeFromByte(filename));
- }
- PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
- Py_INCREF(interp->builtins); /* AddObject steals a reference */
- return PyModule_GetDict(mod_main);
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ PyObject *mod_main = PyModule_New("__main__");
+ PyDict_SetItemString(interp->modules, "__main__", mod_main);
+ Py_DECREF(mod_main); /* sys.modules owns now */
+ PyModule_AddStringConstant(mod_main, "__name__", "__main__");
+ if (filename) {
+ /* __file__ mainly for nice UI'ness
+ * note: this wont map to a real file when executing text-blocks and buttons. */
+ PyModule_AddObject(mod_main, "__file__", PyC_UnicodeFromByte(filename));
+ }
+ PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
+ Py_INCREF(interp->builtins); /* AddObject steals a reference */
+ return PyModule_GetDict(mod_main);
}
bool PyC_NameSpace_ImportArray(PyObject *py_dict, const char *imports[])
{
- for (int i = 0; imports[i]; i++) {
- PyObject *name = PyUnicode_FromString(imports[i]);
- PyObject *mod = PyImport_ImportModuleLevelObject(name, NULL, NULL, 0, 0);
- bool ok = false;
- if (mod) {
- PyDict_SetItem(py_dict, name, mod);
- ok = true;
- Py_DECREF(mod);
- }
- Py_DECREF(name);
-
- if (!ok) {
- return false;
- }
- }
- return true;
+ for (int i = 0; imports[i]; i++) {
+ PyObject *name = PyUnicode_FromString(imports[i]);
+ PyObject *mod = PyImport_ImportModuleLevelObject(name, NULL, NULL, 0, 0);
+ bool ok = false;
+ if (mod) {
+ PyDict_SetItem(py_dict, name, mod);
+ ok = true;
+ Py_DECREF(mod);
+ }
+ Py_DECREF(name);
+
+ if (!ok) {
+ return false;
+ }
+ }
+ return true;
}
/* restore MUST be called after this */
void PyC_MainModule_Backup(PyObject **main_mod)
{
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- *main_mod = PyDict_GetItemString(interp->modules, "__main__");
- Py_XINCREF(*main_mod); /* don't free */
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ *main_mod = PyDict_GetItemString(interp->modules, "__main__");
+ Py_XINCREF(*main_mod); /* don't free */
}
void PyC_MainModule_Restore(PyObject *main_mod)
{
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- PyDict_SetItemString(interp->modules, "__main__", main_mod);
- Py_XDECREF(main_mod);
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ PyDict_SetItemString(interp->modules, "__main__", main_mod);
+ Py_XDECREF(main_mod);
}
/* must be called before Py_Initialize, expects output of BKE_appdir_folder_id(BLENDER_PYTHON, NULL) */
void PyC_SetHomePath(const char *py_path_bundle)
{
- if (py_path_bundle == NULL) {
- /* Common enough to have bundled *nix python but complain on OSX/Win */
-#if defined(__APPLE__) || defined(_WIN32)
- fprintf(stderr, "Warning! bundled python not found and is expected on this platform. "
- "(if you built with CMake: 'install' target may have not been built)\n");
-#endif
- return;
- }
- /* set the environment path */
- printf("found bundled python: %s\n", py_path_bundle);
-
-#ifdef __APPLE__
- /* OSX allow file/directory names to contain : character (represented as / in the Finder)
- * but current Python lib (release 3.1.1) doesn't handle these correctly */
- if (strchr(py_path_bundle, ':')) {
- printf("Warning : Blender application is located in a path containing : or / chars\
- \nThis may make python import function fail\n");
- }
-#endif
-
-
-#if 0 /* disable for now [#31506] - campbell */
-#ifdef _WIN32
- /* cmake/MSVC debug build crashes without this, why only
- * in this case is unknown.. */
- {
- /*BLI_setenv("PYTHONPATH", py_path_bundle)*/;
- }
-#endif
-#endif
-
- {
- static wchar_t py_path_bundle_wchar[1024];
-
- /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
- /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
-
- BLI_strncpy_wchar_from_utf8(py_path_bundle_wchar, py_path_bundle, ARRAY_SIZE(py_path_bundle_wchar));
-
- Py_SetPythonHome(py_path_bundle_wchar);
- // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
- }
+ if (py_path_bundle == NULL) {
+ /* Common enough to have bundled *nix python but complain on OSX/Win */
+# if defined(__APPLE__) || defined(_WIN32)
+ fprintf(stderr,
+ "Warning! bundled python not found and is expected on this platform. "
+ "(if you built with CMake: 'install' target may have not been built)\n");
+# endif
+ return;
+ }
+ /* set the environment path */
+ printf("found bundled python: %s\n", py_path_bundle);
+
+# ifdef __APPLE__
+ /* OSX allow file/directory names to contain : character (represented as / in the Finder)
+ * but current Python lib (release 3.1.1) doesn't handle these correctly */
+ if (strchr(py_path_bundle, ':')) {
+ printf(
+ "Warning : Blender application is located in a path containing : or / chars\
+ \nThis may make python import function fail\n");
+ }
+# endif
+
+# if 0 /* disable for now [#31506] - campbell */
+# ifdef _WIN32
+ /* cmake/MSVC debug build crashes without this, why only
+ * in this case is unknown.. */
+ {
+ /*BLI_setenv("PYTHONPATH", py_path_bundle)*/;
+ }
+# endif
+# endif
+
+ {
+ static wchar_t py_path_bundle_wchar[1024];
+
+ /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
+ /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
+
+ BLI_strncpy_wchar_from_utf8(
+ py_path_bundle_wchar, py_path_bundle, ARRAY_SIZE(py_path_bundle_wchar));
+
+ Py_SetPythonHome(py_path_bundle_wchar);
+ // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
+ }
}
bool PyC_IsInterpreterActive(void)
{
- /* instead of PyThreadState_Get, which calls Py_FatalError */
- return (PyThreadState_GetDict() != NULL);
+ /* instead of PyThreadState_Get, which calls Py_FatalError */
+ return (PyThreadState_GetDict() != NULL);
}
/* Would be nice if python had this built in
@@ -825,433 +825,447 @@ bool PyC_IsInterpreterActive(void)
*/
void PyC_RunQuicky(const char *filepath, int n, ...)
{
- FILE *fp = fopen(filepath, "r");
-
- if (fp) {
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ FILE *fp = fopen(filepath, "r");
+
+ if (fp) {
+ PyGILState_STATE gilstate = PyGILState_Ensure();
- va_list vargs;
+ va_list vargs;
- int *sizes = PyMem_MALLOC(sizeof(int) * (n / 2));
- int i;
-
- PyObject *py_dict = PyC_DefaultNameSpace(filepath);
- PyObject *values = PyList_New(n / 2); /* namespace owns this, don't free */
-
- PyObject *py_result, *ret;
-
- PyObject *struct_mod = PyImport_ImportModule("struct");
- PyObject *calcsize = PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
- PyObject *pack = PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
- PyObject *unpack = PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
-
- Py_DECREF(struct_mod);
-
- va_start(vargs, n);
- for (i = 0; i * 2 < n; i++) {
- const char *format = va_arg(vargs, char *);
- void *ptr = va_arg(vargs, void *);
-
- ret = PyObject_CallFunction(calcsize, "s", format);
-
- if (ret) {
- sizes[i] = PyLong_AsLong(ret);
- Py_DECREF(ret);
- ret = PyObject_CallFunction(unpack, "sy#", format, (char *)ptr, sizes[i]);
- }
-
- if (ret == NULL) {
- printf("%s error, line:%d\n", __func__, __LINE__);
- PyErr_Print();
- PyErr_Clear();
-
- PyList_SET_ITEM(values, i, Py_INCREF_RET(Py_None)); /* hold user */
-
- sizes[i] = 0;
- }
- else {
- if (PyTuple_GET_SIZE(ret) == 1) {
- /* convenience, convert single tuples into single values */
- PyObject *tmp = PyTuple_GET_ITEM(ret, 0);
- Py_INCREF(tmp);
- Py_DECREF(ret);
- ret = tmp;
- }
-
- PyList_SET_ITEM(values, i, ret); /* hold user */
- }
- }
- va_end(vargs);
-
- /* set the value so we can access it */
- PyDict_SetItemString(py_dict, "values", values);
- Py_DECREF(values);
-
- py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
-
- fclose(fp);
-
- if (py_result) {
-
- /* we could skip this but then only slice assignment would work
- * better not be so strict */
- values = PyDict_GetItemString(py_dict, "values");
-
- if (values && PyList_Check(values)) {
-
- /* don't use the result */
- Py_DECREF(py_result);
- py_result = NULL;
-
- /* now get the values back */
- va_start(vargs, n);
- for (i = 0; i * 2 < n; i++) {
- const char *format = va_arg(vargs, char *);
- void *ptr = va_arg(vargs, void *);
-
- PyObject *item;
- PyObject *item_new;
- /* prepend the string formatting and remake the tuple */
- item = PyList_GET_ITEM(values, i);
- if (PyTuple_CheckExact(item)) {
- int ofs = PyTuple_GET_SIZE(item);
- item_new = PyTuple_New(ofs + 1);
- while (ofs--) {
- PyObject *member = PyTuple_GET_ITEM(item, ofs);
- PyTuple_SET_ITEM(item_new, ofs + 1, member);
- Py_INCREF(member);
- }
-
- PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
- }
- else {
- item_new = Py_BuildValue("sO", format, item);
- }
-
- ret = PyObject_Call(pack, item_new, NULL);
-
- if (ret) {
- /* copy the bytes back into memory */
- memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
- Py_DECREF(ret);
- }
- else {
- printf("%s error on arg '%d', line:%d\n", __func__, i, __LINE__);
- PyC_ObSpit("failed converting:", item_new);
- PyErr_Print();
- PyErr_Clear();
- }
-
- Py_DECREF(item_new);
- }
- va_end(vargs);
- }
- else {
- printf("%s error, 'values' not a list, line:%d\n", __func__, __LINE__);
- }
- }
- else {
- printf("%s error line:%d\n", __func__, __LINE__);
- PyErr_Print();
- PyErr_Clear();
- }
-
- Py_DECREF(calcsize);
- Py_DECREF(pack);
- Py_DECREF(unpack);
-
- PyMem_FREE(sizes);
-
- PyGILState_Release(gilstate);
- }
- else {
- fprintf(stderr, "%s: '%s' missing\n", __func__, filepath);
- }
+ int *sizes = PyMem_MALLOC(sizeof(int) * (n / 2));
+ int i;
+
+ PyObject *py_dict = PyC_DefaultNameSpace(filepath);
+ PyObject *values = PyList_New(n / 2); /* namespace owns this, don't free */
+
+ PyObject *py_result, *ret;
+
+ PyObject *struct_mod = PyImport_ImportModule("struct");
+ PyObject *calcsize = PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
+ PyObject *pack = PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
+ PyObject *unpack = PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */
+
+ Py_DECREF(struct_mod);
+
+ va_start(vargs, n);
+ for (i = 0; i * 2 < n; i++) {
+ const char *format = va_arg(vargs, char *);
+ void *ptr = va_arg(vargs, void *);
+
+ ret = PyObject_CallFunction(calcsize, "s", format);
+
+ if (ret) {
+ sizes[i] = PyLong_AsLong(ret);
+ Py_DECREF(ret);
+ ret = PyObject_CallFunction(unpack, "sy#", format, (char *)ptr, sizes[i]);
+ }
+
+ if (ret == NULL) {
+ printf("%s error, line:%d\n", __func__, __LINE__);
+ PyErr_Print();
+ PyErr_Clear();
+
+ PyList_SET_ITEM(values, i, Py_INCREF_RET(Py_None)); /* hold user */
+
+ sizes[i] = 0;
+ }
+ else {
+ if (PyTuple_GET_SIZE(ret) == 1) {
+ /* convenience, convert single tuples into single values */
+ PyObject *tmp = PyTuple_GET_ITEM(ret, 0);
+ Py_INCREF(tmp);
+ Py_DECREF(ret);
+ ret = tmp;
+ }
+
+ PyList_SET_ITEM(values, i, ret); /* hold user */
+ }
+ }
+ va_end(vargs);
+
+ /* set the value so we can access it */
+ PyDict_SetItemString(py_dict, "values", values);
+ Py_DECREF(values);
+
+ py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);
+
+ fclose(fp);
+
+ if (py_result) {
+
+ /* we could skip this but then only slice assignment would work
+ * better not be so strict */
+ values = PyDict_GetItemString(py_dict, "values");
+
+ if (values && PyList_Check(values)) {
+
+ /* don't use the result */
+ Py_DECREF(py_result);
+ py_result = NULL;
+
+ /* now get the values back */
+ va_start(vargs, n);
+ for (i = 0; i * 2 < n; i++) {
+ const char *format = va_arg(vargs, char *);
+ void *ptr = va_arg(vargs, void *);
+
+ PyObject *item;
+ PyObject *item_new;
+ /* prepend the string formatting and remake the tuple */
+ item = PyList_GET_ITEM(values, i);
+ if (PyTuple_CheckExact(item)) {
+ int ofs = PyTuple_GET_SIZE(item);
+ item_new = PyTuple_New(ofs + 1);
+ while (ofs--) {
+ PyObject *member = PyTuple_GET_ITEM(item, ofs);
+ PyTuple_SET_ITEM(item_new, ofs + 1, member);
+ Py_INCREF(member);
+ }
+
+ PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
+ }
+ else {
+ item_new = Py_BuildValue("sO", format, item);
+ }
+
+ ret = PyObject_Call(pack, item_new, NULL);
+
+ if (ret) {
+ /* copy the bytes back into memory */
+ memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
+ Py_DECREF(ret);
+ }
+ else {
+ printf("%s error on arg '%d', line:%d\n", __func__, i, __LINE__);
+ PyC_ObSpit("failed converting:", item_new);
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ Py_DECREF(item_new);
+ }
+ va_end(vargs);
+ }
+ else {
+ printf("%s error, 'values' not a list, line:%d\n", __func__, __LINE__);
+ }
+ }
+ else {
+ printf("%s error line:%d\n", __func__, __LINE__);
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ Py_DECREF(calcsize);
+ Py_DECREF(pack);
+ Py_DECREF(unpack);
+
+ PyMem_FREE(sizes);
+
+ PyGILState_Release(gilstate);
+ }
+ else {
+ fprintf(stderr, "%s: '%s' missing\n", __func__, filepath);
+ }
}
/* generic function to avoid depending on RNA */
void *PyC_RNA_AsPointer(PyObject *value, const char *type_name)
{
- PyObject *as_pointer;
- PyObject *pointer;
-
- if (STREQ(Py_TYPE(value)->tp_name, type_name) &&
- (as_pointer = PyObject_GetAttrString(value, "as_pointer")) != NULL &&
- PyCallable_Check(as_pointer))
- {
- void *result = NULL;
-
- /* must be a 'type_name' object */
- pointer = PyObject_CallObject(as_pointer, NULL);
- Py_DECREF(as_pointer);
-
- if (!pointer) {
- PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
- return NULL;
- }
- result = PyLong_AsVoidPtr(pointer);
- Py_DECREF(pointer);
- if (!result) {
- PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
- }
-
- return result;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "expected '%.200s' type found '%.200s' instead",
- type_name, Py_TYPE(value)->tp_name);
- return NULL;
- }
+ PyObject *as_pointer;
+ PyObject *pointer;
+
+ if (STREQ(Py_TYPE(value)->tp_name, type_name) &&
+ (as_pointer = PyObject_GetAttrString(value, "as_pointer")) != NULL &&
+ PyCallable_Check(as_pointer)) {
+ void *result = NULL;
+
+ /* must be a 'type_name' object */
+ pointer = PyObject_CallObject(as_pointer, NULL);
+ Py_DECREF(as_pointer);
+
+ if (!pointer) {
+ PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
+ return NULL;
+ }
+ result = PyLong_AsVoidPtr(pointer);
+ Py_DECREF(pointer);
+ if (!result) {
+ PyErr_SetString(PyExc_SystemError, "value.as_pointer() failed");
+ }
+
+ return result;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "expected '%.200s' type found '%.200s' instead",
+ type_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
}
-
/* PyC_FlagSet_* functions - so flags/sets can be interchanged in a generic way */
-#include "BLI_dynstr.h"
-#include "MEM_guardedalloc.h"
+# include "BLI_dynstr.h"
+# include "MEM_guardedalloc.h"
char *PyC_FlagSet_AsString(PyC_FlagSet *item)
{
- DynStr *dynstr = BLI_dynstr_new();
- PyC_FlagSet *e;
- char *cstring;
+ DynStr *dynstr = BLI_dynstr_new();
+ PyC_FlagSet *e;
+ char *cstring;
- for (e = item; item->identifier; item++) {
- BLI_dynstr_appendf(dynstr, (e == item) ? "'%s'" : ", '%s'", item->identifier);
- }
+ for (e = item; item->identifier; item++) {
+ BLI_dynstr_appendf(dynstr, (e == item) ? "'%s'" : ", '%s'", item->identifier);
+ }
- cstring = BLI_dynstr_get_cstring(dynstr);
- BLI_dynstr_free(dynstr);
- return cstring;
+ cstring = BLI_dynstr_get_cstring(dynstr);
+ BLI_dynstr_free(dynstr);
+ return cstring;
}
int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *r_value)
{
- for ( ; item->identifier; item++) {
- if (STREQ(item->identifier, identifier)) {
- *r_value = item->value;
- return 1;
- }
- }
-
- return 0;
+ for (; item->identifier; item++) {
+ if (STREQ(item->identifier, identifier)) {
+ *r_value = item->value;
+ return 1;
+ }
+ }
+
+ return 0;
}
-int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *r_value, const char *error_prefix)
+int PyC_FlagSet_ValueFromID(PyC_FlagSet *item,
+ const char *identifier,
+ int *r_value,
+ const char *error_prefix)
{
- if (PyC_FlagSet_ValueFromID_int(item, identifier, r_value) == 0) {
- const char *enum_str = PyC_FlagSet_AsString(item);
- PyErr_Format(PyExc_ValueError,
- "%s: '%.200s' not found in (%s)",
- error_prefix, identifier, enum_str);
- MEM_freeN((void *)enum_str);
- return -1;
- }
-
- return 0;
+ if (PyC_FlagSet_ValueFromID_int(item, identifier, r_value) == 0) {
+ const char *enum_str = PyC_FlagSet_AsString(item);
+ PyErr_Format(
+ PyExc_ValueError, "%s: '%.200s' not found in (%s)", error_prefix, identifier, enum_str);
+ MEM_freeN((void *)enum_str);
+ return -1;
+ }
+
+ return 0;
}
-int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix)
+int PyC_FlagSet_ToBitfield(PyC_FlagSet *items,
+ PyObject *value,
+ int *r_value,
+ const char *error_prefix)
{
- /* set of enum items, concatenate all values with OR */
- int ret, flag = 0;
-
- /* set looping */
- Py_ssize_t pos = 0;
- Py_ssize_t hash = 0;
- PyObject *key;
-
- if (!PySet_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected a set, not %.200s",
- error_prefix, Py_TYPE(value)->tp_name);
- return -1;
- }
-
- *r_value = 0;
-
- while (_PySet_NextEntry(value, &pos, &key, &hash)) {
- const char *param = _PyUnicode_AsString(key);
-
- if (param == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s set must contain strings, not %.200s",
- error_prefix, Py_TYPE(key)->tp_name);
- return -1;
- }
-
- if (PyC_FlagSet_ValueFromID(items, param, &ret, error_prefix) < 0) {
- return -1;
- }
-
- flag |= ret;
- }
-
- *r_value = flag;
- return 0;
+ /* set of enum items, concatenate all values with OR */
+ int ret, flag = 0;
+
+ /* set looping */
+ Py_ssize_t pos = 0;
+ Py_ssize_t hash = 0;
+ PyObject *key;
+
+ if (!PySet_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected a set, not %.200s",
+ error_prefix,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ *r_value = 0;
+
+ while (_PySet_NextEntry(value, &pos, &key, &hash)) {
+ const char *param = _PyUnicode_AsString(key);
+
+ if (param == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s set must contain strings, not %.200s",
+ error_prefix,
+ Py_TYPE(key)->tp_name);
+ return -1;
+ }
+
+ if (PyC_FlagSet_ValueFromID(items, param, &ret, error_prefix) < 0) {
+ return -1;
+ }
+
+ flag |= ret;
+ }
+
+ *r_value = flag;
+ return 0;
}
PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag)
{
- PyObject *ret = PySet_New(NULL);
- PyObject *pystr;
-
- for ( ; items->identifier; items++) {
- if (items->value & flag) {
- pystr = PyUnicode_FromString(items->identifier);
- PySet_Add(ret, pystr);
- Py_DECREF(pystr);
- }
- }
-
- return ret;
+ PyObject *ret = PySet_New(NULL);
+ PyObject *pystr;
+
+ for (; items->identifier; items++) {
+ if (items->value & flag) {
+ pystr = PyUnicode_FromString(items->identifier);
+ PySet_Add(ret, pystr);
+ Py_DECREF(pystr);
+ }
+ }
+
+ return ret;
}
-
/**
* \return success
*
* \note it is caller's responsibility to acquire & release GIL!
*/
-bool PyC_RunString_AsNumber(const char *imports[], const char *expr, const char *filename, double *r_value)
+bool PyC_RunString_AsNumber(const char *imports[],
+ const char *expr,
+ const char *filename,
+ double *r_value)
{
- PyObject *py_dict, *mod, *retval;
- bool ok = true;
- PyObject *main_mod = NULL;
-
- PyC_MainModule_Backup(&main_mod);
-
- py_dict = PyC_DefaultNameSpace(filename);
-
- mod = PyImport_ImportModule("math");
- if (mod) {
- PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
- Py_DECREF(mod);
- }
- else { /* highly unlikely but possibly */
- PyErr_Print();
- PyErr_Clear();
- }
-
- if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
- ok = false;
- }
- else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
- ok = false;
- }
- else {
- double val;
-
- if (PyTuple_Check(retval)) {
- /* Users my have typed in 10km, 2m
- * add up all values */
- int i;
- val = 0.0;
-
- for (i = 0; i < PyTuple_GET_SIZE(retval); i++) {
- const double val_item = PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
- if (val_item == -1 && PyErr_Occurred()) {
- val = -1;
- break;
- }
- val += val_item;
- }
- }
- else {
- val = PyFloat_AsDouble(retval);
- }
- Py_DECREF(retval);
-
- if (val == -1 && PyErr_Occurred()) {
- ok = false;
- }
- else if (!isfinite(val)) {
- *r_value = 0.0;
- }
- else {
- *r_value = val;
- }
- }
-
- PyC_MainModule_Restore(main_mod);
-
- return ok;
+ PyObject *py_dict, *mod, *retval;
+ bool ok = true;
+ PyObject *main_mod = NULL;
+
+ PyC_MainModule_Backup(&main_mod);
+
+ py_dict = PyC_DefaultNameSpace(filename);
+
+ mod = PyImport_ImportModule("math");
+ if (mod) {
+ PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
+ Py_DECREF(mod);
+ }
+ else { /* highly unlikely but possibly */
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
+ ok = false;
+ }
+ else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
+ ok = false;
+ }
+ else {
+ double val;
+
+ if (PyTuple_Check(retval)) {
+ /* Users my have typed in 10km, 2m
+ * add up all values */
+ int i;
+ val = 0.0;
+
+ for (i = 0; i < PyTuple_GET_SIZE(retval); i++) {
+ const double val_item = PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
+ if (val_item == -1 && PyErr_Occurred()) {
+ val = -1;
+ break;
+ }
+ val += val_item;
+ }
+ }
+ else {
+ val = PyFloat_AsDouble(retval);
+ }
+ Py_DECREF(retval);
+
+ if (val == -1 && PyErr_Occurred()) {
+ ok = false;
+ }
+ else if (!isfinite(val)) {
+ *r_value = 0.0;
+ }
+ else {
+ *r_value = val;
+ }
+ }
+
+ PyC_MainModule_Restore(main_mod);
+
+ return ok;
}
-bool PyC_RunString_AsIntPtr(const char *imports[], const char *expr, const char *filename, intptr_t *r_value)
+bool PyC_RunString_AsIntPtr(const char *imports[],
+ const char *expr,
+ const char *filename,
+ intptr_t *r_value)
{
- PyObject *py_dict, *retval;
- bool ok = true;
- PyObject *main_mod = NULL;
+ PyObject *py_dict, *retval;
+ bool ok = true;
+ PyObject *main_mod = NULL;
- PyC_MainModule_Backup(&main_mod);
+ PyC_MainModule_Backup(&main_mod);
- py_dict = PyC_DefaultNameSpace(filename);
+ py_dict = PyC_DefaultNameSpace(filename);
- if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
- ok = false;
- }
- else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
- ok = false;
- }
- else {
- intptr_t val;
+ if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
+ ok = false;
+ }
+ else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
+ ok = false;
+ }
+ else {
+ intptr_t val;
- val = (intptr_t)PyLong_AsVoidPtr(retval);
- if (val == 0 && PyErr_Occurred()) {
- ok = false;
- }
- else {
- *r_value = val;
- }
+ val = (intptr_t)PyLong_AsVoidPtr(retval);
+ if (val == 0 && PyErr_Occurred()) {
+ ok = false;
+ }
+ else {
+ *r_value = val;
+ }
- Py_DECREF(retval);
- }
+ Py_DECREF(retval);
+ }
- PyC_MainModule_Restore(main_mod);
+ PyC_MainModule_Restore(main_mod);
- return ok;
+ return ok;
}
-bool PyC_RunString_AsString(const char *imports[], const char *expr, const char *filename, char **r_value)
+bool PyC_RunString_AsString(const char *imports[],
+ const char *expr,
+ const char *filename,
+ char **r_value)
{
- PyObject *py_dict, *retval;
- bool ok = true;
- PyObject *main_mod = NULL;
-
- PyC_MainModule_Backup(&main_mod);
-
- py_dict = PyC_DefaultNameSpace(filename);
-
- if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
- ok = false;
- }
- else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
- ok = false;
- }
- else {
- const char *val;
- Py_ssize_t val_len;
-
- val = _PyUnicode_AsStringAndSize(retval, &val_len);
- if (val == NULL && PyErr_Occurred()) {
- ok = false;
- }
- else {
- char *val_alloc = MEM_mallocN(val_len + 1, __func__);
- memcpy(val_alloc, val, val_len + 1);
- *r_value = val_alloc;
- }
-
- Py_DECREF(retval);
- }
-
- PyC_MainModule_Restore(main_mod);
-
- return ok;
+ PyObject *py_dict, *retval;
+ bool ok = true;
+ PyObject *main_mod = NULL;
+
+ PyC_MainModule_Backup(&main_mod);
+
+ py_dict = PyC_DefaultNameSpace(filename);
+
+ if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
+ ok = false;
+ }
+ else if ((retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict)) == NULL) {
+ ok = false;
+ }
+ else {
+ const char *val;
+ Py_ssize_t val_len;
+
+ val = _PyUnicode_AsStringAndSize(retval, &val_len);
+ if (val == NULL && PyErr_Occurred()) {
+ ok = false;
+ }
+ else {
+ char *val_alloc = MEM_mallocN(val_len + 1, __func__);
+ memcpy(val_alloc, val, val_len + 1);
+ *r_value = val_alloc;
+ }
+
+ Py_DECREF(retval);
+ }
+
+ PyC_MainModule_Restore(main_mod);
+
+ return ok;
}
-#endif /* #ifndef MATH_STANDALONE */
+#endif /* #ifndef MATH_STANDALONE */
/* -------------------------------------------------------------------- */
/** \name Int Conversion
@@ -1271,35 +1285,32 @@ bool PyC_RunString_AsString(const char *imports[], const char *expr, const char
*/
int PyC_Long_AsBool(PyObject *value)
{
- int test = _PyLong_AsInt(value);
- if (UNLIKELY((uint)test > 1)) {
- PyErr_SetString(PyExc_TypeError,
- "Python number not a bool (0/1)");
- return -1;
- }
- return test;
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY((uint)test > 1)) {
+ PyErr_SetString(PyExc_TypeError, "Python number not a bool (0/1)");
+ return -1;
+ }
+ return test;
}
int8_t PyC_Long_AsI8(PyObject *value)
{
- int test = _PyLong_AsInt(value);
- if (UNLIKELY(test < INT8_MIN || test > INT8_MAX)) {
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C int8");
- return -1;
- }
- return (int8_t)test;
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY(test < INT8_MIN || test > INT8_MAX)) {
+ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int8");
+ return -1;
+ }
+ return (int8_t)test;
}
int16_t PyC_Long_AsI16(PyObject *value)
{
- int test = _PyLong_AsInt(value);
- if (UNLIKELY(test < INT16_MIN || test > INT16_MAX)) {
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C int16");
- return -1;
- }
- return (int16_t)test;
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY(test < INT16_MIN || test > INT16_MAX)) {
+ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int16");
+ return -1;
+ }
+ return (int16_t)test;
}
/* Inlined in header:
@@ -1309,35 +1320,32 @@ int16_t PyC_Long_AsI16(PyObject *value)
uint8_t PyC_Long_AsU8(PyObject *value)
{
- ulong test = PyLong_AsUnsignedLong(value);
- if (UNLIKELY(test > UINT8_MAX)) {
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C uint8");
- return (uint8_t)-1;
- }
- return (uint8_t)test;
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT8_MAX)) {
+ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint8");
+ return (uint8_t)-1;
+ }
+ return (uint8_t)test;
}
uint16_t PyC_Long_AsU16(PyObject *value)
{
- ulong test = PyLong_AsUnsignedLong(value);
- if (UNLIKELY(test > UINT16_MAX)) {
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C uint16");
- return (uint16_t)-1;
- }
- return (uint16_t)test;
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT16_MAX)) {
+ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint16");
+ return (uint16_t)-1;
+ }
+ return (uint16_t)test;
}
uint32_t PyC_Long_AsU32(PyObject *value)
{
- ulong test = PyLong_AsUnsignedLong(value);
- if (UNLIKELY(test > UINT32_MAX)) {
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C uint32");
- return (uint32_t)-1;
- }
- return (uint32_t)test;
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT32_MAX)) {
+ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C uint32");
+ return (uint32_t)-1;
+ }
+ return (uint32_t)test;
}
/* Inlined in header:
@@ -1351,72 +1359,72 @@ uint32_t PyC_Long_AsU32(PyObject *value)
char PyC_StructFmt_type_from_str(const char *typestr)
{
- switch (typestr[0]) {
- case '!':
- case '<':
- case '=':
- case '>':
- case '@':
- return typestr[1];
- default:
- return typestr[0];
- }
+ switch (typestr[0]) {
+ case '!':
+ case '<':
+ case '=':
+ case '>':
+ case '@':
+ return typestr[1];
+ default:
+ return typestr[0];
+ }
}
bool PyC_StructFmt_type_is_float_any(char format)
{
- switch (format) {
- case 'f':
- case 'd':
- case 'e':
- return true;
- default:
- return false;
- }
+ switch (format) {
+ case 'f':
+ case 'd':
+ case 'e':
+ return true;
+ default:
+ return false;
+ }
}
bool PyC_StructFmt_type_is_int_any(char format)
{
- switch (format) {
- case 'i':
- case 'I':
- case 'l':
- case 'L':
- case 'h':
- case 'H':
- case 'b':
- case 'B':
- case 'q':
- case 'Q':
- case 'n':
- case 'N':
- case 'P':
- return true;
- default:
- return false;
- }
+ switch (format) {
+ case 'i':
+ case 'I':
+ case 'l':
+ case 'L':
+ case 'h':
+ case 'H':
+ case 'b':
+ case 'B':
+ case 'q':
+ case 'Q':
+ case 'n':
+ case 'N':
+ case 'P':
+ return true;
+ default:
+ return false;
+ }
}
bool PyC_StructFmt_type_is_byte(char format)
{
- switch (format) {
- case 'c':
- case 's':
- case 'p':
- return true;
- default:
- return false;
- }
+ switch (format) {
+ case 'c':
+ case 's':
+ case 'p':
+ return true;
+ default:
+ return false;
+ }
}
bool PyC_StructFmt_type_is_bool(char format)
{
- switch (format) {
- case '?':
- return true;
- default:
- return false;
- }
+ switch (format) {
+ case '?':
+ return true;
+ default:
+ return false;
+ }
}
/** \} */
diff --git a/source/blender/python/generic/py_capi_utils.h b/source/blender/python/generic/py_capi_utils.h
index 76c28e4a6f5..4454aa11d77 100644
--- a/source/blender/python/generic/py_capi_utils.h
+++ b/source/blender/python/generic/py_capi_utils.h
@@ -24,10 +24,10 @@
#include "BLI_sys_types.h"
#include "BLI_utildefines_variadic.h"
-void PyC_ObSpit(const char *name, PyObject *var);
-void PyC_ObSpitStr(char *result, size_t result_len, PyObject *var);
-void PyC_LineSpit(void);
-void PyC_StackSpit(void);
+void PyC_ObSpit(const char *name, PyObject *var);
+void PyC_ObSpitStr(char *result, size_t result_len, PyObject *var);
+void PyC_LineSpit(void);
+void PyC_StackSpit(void);
PyObject *PyC_ExceptionBuffer(void);
PyObject *PyC_ExceptionBuffer_Simple(void);
PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...);
@@ -36,40 +36,46 @@ PyObject *PyC_FrozenSetFromStrings(const char **strings);
PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...);
PyObject *PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *str);
-void PyC_Err_PrintWithFunc(PyObject *py_func);
-
-void PyC_FileAndNum(const char **filename, int *lineno);
-void PyC_FileAndNum_Safe(const char **filename, int *lineno); /* checks python is running */
-int PyC_AsArray_FAST(
- void *array, PyObject *value_fast, const Py_ssize_t length,
- const PyTypeObject *type, const bool is_double, const char *error_prefix);
-int PyC_AsArray(
- void *array, PyObject *value, const Py_ssize_t length,
- const PyTypeObject *type, const bool is_double, const char *error_prefix);
-
-PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len);
-PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len);
-PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len);
-PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len);
-PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len);
+void PyC_Err_PrintWithFunc(PyObject *py_func);
+
+void PyC_FileAndNum(const char **filename, int *lineno);
+void PyC_FileAndNum_Safe(const char **filename, int *lineno); /* checks python is running */
+int PyC_AsArray_FAST(void *array,
+ PyObject *value_fast,
+ const Py_ssize_t length,
+ const PyTypeObject *type,
+ const bool is_double,
+ const char *error_prefix);
+int PyC_AsArray(void *array,
+ PyObject *value,
+ const Py_ssize_t length,
+ const PyTypeObject *type,
+ const bool is_double,
+ const char *error_prefix);
+
+PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len);
+PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len);
+PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len);
+PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len);
+PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len);
#define PyC_Tuple_Pack_F32(...) \
- PyC_Tuple_PackArray_F32(((const float []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+ PyC_Tuple_PackArray_F32(((const float[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
#define PyC_Tuple_Pack_F64(...) \
- PyC_Tuple_PackArray_F64(((const double []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+ PyC_Tuple_PackArray_F64(((const double[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
#define PyC_Tuple_Pack_I32(...) \
- PyC_Tuple_PackArray_I32(((const int []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+ PyC_Tuple_PackArray_I32(((const int[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
#define PyC_Tuple_Pack_I32FromBool(...) \
- PyC_Tuple_PackArray_I32FromBool(((const int []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+ PyC_Tuple_PackArray_I32FromBool(((const int[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
#define PyC_Tuple_Pack_Bool(...) \
- PyC_Tuple_PackArray_Bool(((const bool []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+ PyC_Tuple_PackArray_Bool(((const bool[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
-void PyC_Tuple_Fill(PyObject *tuple, PyObject *value);
-void PyC_List_Fill(PyObject *list, PyObject *value);
+void PyC_Tuple_Fill(PyObject *tuple, PyObject *value);
+void PyC_List_Fill(PyObject *list, PyObject *value);
/* follow http://www.python.org/dev/peps/pep-0383/ */
-PyObject *PyC_UnicodeFromByte(const char *str);
-PyObject *PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size);
+PyObject *PyC_UnicodeFromByte(const char *str);
+PyObject *PyC_UnicodeFromByteAndSize(const char *str, Py_ssize_t size);
const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce); /* coerce must be NULL */
const char *PyC_UnicodeAsByteAndSize(PyObject *py_str, Py_ssize_t *size, PyObject **coerce);
@@ -89,34 +95,49 @@ void *PyC_RNA_AsPointer(PyObject *value, const char *type_name);
/* flag / set --- interchange */
typedef struct PyC_FlagSet {
- int value;
- const char *identifier;
+ int value;
+ const char *identifier;
} PyC_FlagSet;
-char *PyC_FlagSet_AsString(PyC_FlagSet *item);
-int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *r_value);
-int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *r_value, const char *error_prefix);
-int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix);
+char *PyC_FlagSet_AsString(PyC_FlagSet *item);
+int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *r_value);
+int PyC_FlagSet_ValueFromID(PyC_FlagSet *item,
+ const char *identifier,
+ int *r_value,
+ const char *error_prefix);
+int PyC_FlagSet_ToBitfield(PyC_FlagSet *items,
+ PyObject *value,
+ int *r_value,
+ const char *error_prefix);
PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag);
-bool PyC_RunString_AsNumber(const char **imports, const char *expr, const char *filename, double *r_value);
-bool PyC_RunString_AsIntPtr(const char **imports, const char *expr, const char *filename, intptr_t *r_value);
-bool PyC_RunString_AsString(const char **imports, const char *expr, const char *filename, char **r_value);
+bool PyC_RunString_AsNumber(const char **imports,
+ const char *expr,
+ const char *filename,
+ double *r_value);
+bool PyC_RunString_AsIntPtr(const char **imports,
+ const char *expr,
+ const char *filename,
+ intptr_t *r_value);
+bool PyC_RunString_AsString(const char **imports,
+ const char *expr,
+ const char *filename,
+ char **r_value);
int PyC_ParseBool(PyObject *o, void *p);
int PyC_CheckArgs_DeepCopy(PyObject *args);
/* Integer parsing (with overflow checks), -1 on error. */
-int PyC_Long_AsBool(PyObject *value);
-int8_t PyC_Long_AsI8(PyObject *value);
+int PyC_Long_AsBool(PyObject *value);
+int8_t PyC_Long_AsI8(PyObject *value);
int16_t PyC_Long_AsI16(PyObject *value);
#if 0 /* inline */
int32_t PyC_Long_AsI32(PyObject *value);
int64_t PyC_Long_AsI64(PyObject *value);
#endif
-uint8_t PyC_Long_AsU8(PyObject *value);
+uint8_t PyC_Long_AsU8(PyObject *value);
uint16_t PyC_Long_AsU16(PyObject *value);
uint32_t PyC_Long_AsU32(PyObject *value);
#if 0 /* inline */
@@ -124,9 +145,18 @@ uint64_t PyC_Long_AsU64(PyObject *value);
#endif
/* inline so type signatures match as expected */
-Py_LOCAL_INLINE(int32_t) PyC_Long_AsI32(PyObject *value) { return (int32_t)_PyLong_AsInt(value); }
-Py_LOCAL_INLINE(int64_t) PyC_Long_AsI64(PyObject *value) { return (int64_t)PyLong_AsLongLong(value); }
-Py_LOCAL_INLINE(uint64_t) PyC_Long_AsU64(PyObject *value) { return (uint64_t)PyLong_AsUnsignedLongLong(value); }
+Py_LOCAL_INLINE(int32_t) PyC_Long_AsI32(PyObject *value)
+{
+ return (int32_t)_PyLong_AsInt(value);
+}
+Py_LOCAL_INLINE(int64_t) PyC_Long_AsI64(PyObject *value)
+{
+ return (int64_t)PyLong_AsLongLong(value);
+}
+Py_LOCAL_INLINE(uint64_t) PyC_Long_AsU64(PyObject *value)
+{
+ return (uint64_t)PyLong_AsUnsignedLongLong(value);
+}
/* utils for format string in `struct` module style syntax */
char PyC_StructFmt_type_from_str(const char *typestr);
@@ -135,4 +165,4 @@ bool PyC_StructFmt_type_is_int_any(char format);
bool PyC_StructFmt_type_is_byte(char format);
bool PyC_StructFmt_type_is_bool(char format);
-#endif /* __PY_CAPI_UTILS_H__ */
+#endif /* __PY_CAPI_UTILS_H__ */
diff --git a/source/blender/python/generic/python_utildefines.h b/source/blender/python/generic/python_utildefines.h
index 70840e5ce34..40cec436dea 100644
--- a/source/blender/python/generic/python_utildefines.h
+++ b/source/blender/python/generic/python_utildefines.h
@@ -28,28 +28,33 @@ extern "C" {
#endif
#define PyTuple_SET_ITEMS(op_arg, ...) \
-{ \
- PyTupleObject *op = (PyTupleObject *)op_arg; \
- PyObject **ob_items = op->ob_item; \
- CHECK_TYPE_ANY(op_arg, PyObject *, PyTupleObject *); \
- BLI_assert(VA_NARGS_COUNT(__VA_ARGS__) == PyTuple_GET_SIZE(op)); \
- ARRAY_SET_ITEMS(ob_items, __VA_ARGS__); \
-} (void)0
+ { \
+ PyTupleObject *op = (PyTupleObject *)op_arg; \
+ PyObject **ob_items = op->ob_item; \
+ CHECK_TYPE_ANY(op_arg, PyObject *, PyTupleObject *); \
+ BLI_assert(VA_NARGS_COUNT(__VA_ARGS__) == PyTuple_GET_SIZE(op)); \
+ ARRAY_SET_ITEMS(ob_items, __VA_ARGS__); \
+ } \
+ (void)0
/* wrap Py_INCREF & return the result,
* use sparingly to avoid comma operator or temp var assignment */
-Py_LOCAL_INLINE(PyObject *)Py_INCREF_RET(PyObject *op) { Py_INCREF(op); return op; }
+Py_LOCAL_INLINE(PyObject *) Py_INCREF_RET(PyObject *op)
+{
+ Py_INCREF(op);
+ return op;
+}
/* append & transfer ownership to the list, avoids inline Py_DECREF all over (which is quite a large macro) */
Py_LOCAL_INLINE(int) PyList_APPEND(PyObject *op, PyObject *v)
{
- int ret = PyList_Append(op, v);
- Py_DecRef(v);
- return ret;
+ int ret = PyList_Append(op, v);
+ Py_DecRef(v);
+ return ret;
}
#ifdef __cplusplus
}
#endif
-#endif /* __PYTHON_UTILDEFINES_H__ */
+#endif /* __PYTHON_UTILDEFINES_H__ */
diff --git a/source/blender/python/gpu/CMakeLists.txt b/source/blender/python/gpu/CMakeLists.txt
index aeef81c5fd7..cda866510e3 100644
--- a/source/blender/python/gpu/CMakeLists.txt
+++ b/source/blender/python/gpu/CMakeLists.txt
@@ -16,42 +16,42 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- .
- ../../blenkernel
- ../../blenlib
- ../../gpu
- ../../makesdna
- ../../../../intern/guardedalloc
- ../../../../intern/glew-mx
+ .
+ ../../blenkernel
+ ../../blenlib
+ ../../gpu
+ ../../makesdna
+ ../../../../intern/guardedalloc
+ ../../../../intern/glew-mx
)
set(INC_SYS
- ${GLEW_INCLUDE_PATH}
- ${PYTHON_INCLUDE_DIRS}
+ ${GLEW_INCLUDE_PATH}
+ ${PYTHON_INCLUDE_DIRS}
)
set(SRC
- gpu_py_api.c
- gpu_py_batch.c
- gpu_py_element.c
- gpu_py_matrix.c
- gpu_py_offscreen.c
- gpu_py_select.c
- gpu_py_shader.c
- gpu_py_types.c
- gpu_py_vertex_buffer.c
- gpu_py_vertex_format.c
+ gpu_py_api.c
+ gpu_py_batch.c
+ gpu_py_element.c
+ gpu_py_matrix.c
+ gpu_py_offscreen.c
+ gpu_py_select.c
+ gpu_py_shader.c
+ gpu_py_types.c
+ gpu_py_vertex_buffer.c
+ gpu_py_vertex_format.c
- gpu_py_api.h
- gpu_py_batch.h
- gpu_py_element.h
- gpu_py_matrix.h
- gpu_py_offscreen.h
- gpu_py_select.h
- gpu_py_shader.h
- gpu_py_types.h
- gpu_py_vertex_buffer.h
- gpu_py_vertex_format.h
+ gpu_py_api.h
+ gpu_py_batch.h
+ gpu_py_element.h
+ gpu_py_matrix.h
+ gpu_py_offscreen.h
+ gpu_py_select.h
+ gpu_py_shader.h
+ gpu_py_types.h
+ gpu_py_vertex_buffer.h
+ gpu_py_vertex_format.h
)
set(LIB
diff --git a/source/blender/python/gpu/gpu_py_api.c b/source/blender/python/gpu/gpu_py_api.c
index e2baf548064..bce9563a293 100644
--- a/source/blender/python/gpu/gpu_py_api.c
+++ b/source/blender/python/gpu/gpu_py_api.c
@@ -39,120 +39,111 @@
#include "gpu_py_api.h" /* own include */
-
/* -------------------------------------------------------------------- */
/** \name Utils to invalidate functions
* \{ */
bool bpygpu_is_initialized_or_error(void)
{
- if (!GPU_is_initialized()) {
- PyErr_SetString(
- PyExc_SystemError,
- "GPU functions for drawing are not available in background mode");
+ if (!GPU_is_initialized()) {
+ PyErr_SetString(PyExc_SystemError,
+ "GPU functions for drawing are not available in background mode");
- return false;
- }
+ return false;
+ }
- return true;
+ return true;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Primitive Type Utils
* \{ */
int bpygpu_ParsePrimType(PyObject *o, void *p)
{
- Py_ssize_t mode_id_len;
- const char *mode_id = _PyUnicode_AsStringAndSize(o, &mode_id_len);
- if (mode_id == NULL) {
- PyErr_Format(PyExc_ValueError,
- "expected a string, got %s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
+ Py_ssize_t mode_id_len;
+ const char *mode_id = _PyUnicode_AsStringAndSize(o, &mode_id_len);
+ if (mode_id == NULL) {
+ PyErr_Format(PyExc_ValueError, "expected a string, got %s", Py_TYPE(o)->tp_name);
+ return 0;
+ }
#define MATCH_ID(id) \
- if (mode_id_len == strlen(STRINGIFY(id))) { \
- if (STREQ(mode_id, STRINGIFY(id))) { \
- mode = GPU_PRIM_##id; \
- goto success; \
- } \
- } ((void)0)
-
- GPUPrimType mode;
- MATCH_ID(POINTS);
- MATCH_ID(LINES);
- MATCH_ID(TRIS);
- MATCH_ID(LINE_STRIP);
- MATCH_ID(LINE_LOOP);
- MATCH_ID(TRI_STRIP);
- MATCH_ID(TRI_FAN);
- MATCH_ID(LINE_STRIP_ADJ);
+ if (mode_id_len == strlen(STRINGIFY(id))) { \
+ if (STREQ(mode_id, STRINGIFY(id))) { \
+ mode = GPU_PRIM_##id; \
+ goto success; \
+ } \
+ } \
+ ((void)0)
+
+ GPUPrimType mode;
+ MATCH_ID(POINTS);
+ MATCH_ID(LINES);
+ MATCH_ID(TRIS);
+ MATCH_ID(LINE_STRIP);
+ MATCH_ID(LINE_LOOP);
+ MATCH_ID(TRI_STRIP);
+ MATCH_ID(TRI_FAN);
+ MATCH_ID(LINE_STRIP_ADJ);
#undef MATCH_ID
- PyErr_Format(PyExc_ValueError,
- "unknown type literal: '%s'",
- mode_id);
- return 0;
+ PyErr_Format(PyExc_ValueError, "unknown type literal: '%s'", mode_id);
+ return 0;
success:
- (*(GPUPrimType *)p) = mode;
- return 1;
+ (*(GPUPrimType *)p) = mode;
+ return 1;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name GPU Module
* \{ */
-
PyDoc_STRVAR(GPU_doc,
-"This module provides Python wrappers for the GPU implementation in Blender. "
-"Some higher level functions can be found in the `gpu_extras` module. "
-"\n\n"
-"Submodules:\n"
-"\n"
-".. toctree::\n"
-" :maxdepth: 1\n"
-"\n"
-" gpu.types.rst\n"
-" gpu.shader.rst\n"
-" gpu.matrix.rst\n"
-" gpu.select.rst\n"
-"\n"
-);
+ "This module provides Python wrappers for the GPU implementation in Blender. "
+ "Some higher level functions can be found in the `gpu_extras` module. "
+ "\n\n"
+ "Submodules:\n"
+ "\n"
+ ".. toctree::\n"
+ " :maxdepth: 1\n"
+ "\n"
+ " gpu.types.rst\n"
+ " gpu.shader.rst\n"
+ " gpu.matrix.rst\n"
+ " gpu.select.rst\n"
+ "\n");
static struct PyModuleDef GPU_module_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "gpu",
- .m_doc = GPU_doc,
+ PyModuleDef_HEAD_INIT,
+ .m_name = "gpu",
+ .m_doc = GPU_doc,
};
PyObject *BPyInit_gpu(void)
{
- PyObject *sys_modules = PyImport_GetModuleDict();
- PyObject *submodule;
- PyObject *mod;
+ PyObject *sys_modules = PyImport_GetModuleDict();
+ PyObject *submodule;
+ PyObject *mod;
- mod = PyModule_Create(&GPU_module_def);
+ mod = PyModule_Create(&GPU_module_def);
- PyModule_AddObject(mod, "types", (submodule = BPyInit_gpu_types()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "types", (submodule = BPyInit_gpu_types()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- PyModule_AddObject(mod, "matrix", (submodule = BPyInit_gpu_matrix()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "matrix", (submodule = BPyInit_gpu_matrix()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- PyModule_AddObject(mod, "select", (submodule = BPyInit_gpu_select()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "select", (submodule = BPyInit_gpu_select()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- PyModule_AddObject(mod, "shader", (submodule = BPyInit_gpu_shader()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyModule_AddObject(mod, "shader", (submodule = BPyInit_gpu_shader()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- return mod;
+ return mod;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_api.h b/source/blender/python/gpu/gpu_py_api.h
index d4cfcce24e9..e278bb63a49 100644
--- a/source/blender/python/gpu/gpu_py_api.h
+++ b/source/blender/python/gpu/gpu_py_api.h
@@ -21,13 +21,20 @@
#ifndef __GPU_PY_API_H__
#define __GPU_PY_API_H__
-
int bpygpu_ParsePrimType(PyObject *o, void *p);
PyObject *BPyInit_gpu(void);
bool bpygpu_is_initialized_or_error(void);
-#define BPYGPU_IS_INIT_OR_ERROR_OBJ if (UNLIKELY(!bpygpu_is_initialized_or_error())) { return NULL; } ((void)0)
-#define BPYGPU_IS_INIT_OR_ERROR_INT if (UNLIKELY(!bpygpu_is_initialized_or_error())) { return -1; } ((void)0)
+#define BPYGPU_IS_INIT_OR_ERROR_OBJ \
+ if (UNLIKELY(!bpygpu_is_initialized_or_error())) { \
+ return NULL; \
+ } \
+ ((void)0)
+#define BPYGPU_IS_INIT_OR_ERROR_INT \
+ if (UNLIKELY(!bpygpu_is_initialized_or_error())) { \
+ return -1; \
+ } \
+ ((void)0)
-#endif /* __GPU_PY_API_H__ */
+#endif /* __GPU_PY_API_H__ */
diff --git a/source/blender/python/gpu/gpu_py_batch.c b/source/blender/python/gpu/gpu_py_batch.c
index b5f9bb0f45a..094052b724f 100644
--- a/source/blender/python/gpu/gpu_py_batch.c
+++ b/source/blender/python/gpu/gpu_py_batch.c
@@ -32,7 +32,6 @@
#include "BLI_utildefines.h"
-
#include "GPU_batch.h"
#include "../mathutils/mathutils.h"
@@ -45,85 +44,81 @@
#include "gpu_py_element.h"
#include "gpu_py_batch.h" /* own include */
-
/* -------------------------------------------------------------------- */
/** \name Utility Functions
* \{ */
static bool bpygpu_batch_is_program_or_error(BPyGPUBatch *self)
{
- if (!glIsProgram(self->batch->program)) {
- PyErr_SetString(
- PyExc_RuntimeError,
- "batch does not have any program assigned to it");
- return false;
- }
- return true;
+ if (!glIsProgram(self->batch->program)) {
+ PyErr_SetString(PyExc_RuntimeError, "batch does not have any program assigned to it");
+ return false;
+ }
+ return true;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name GPUBatch Type
* \{ */
static PyObject *bpygpu_Batch_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- BPYGPU_IS_INIT_OR_ERROR_OBJ;
-
- const char *exc_str_missing_arg = "GPUBatch.__new__() missing required argument '%s' (pos %d)";
-
- struct {
- GPUPrimType type_id;
- BPyGPUVertBuf *py_vertbuf;
- BPyGPUIndexBuf *py_indexbuf;
- } params = {GPU_PRIM_NONE, NULL, NULL};
-
- static const char *_keywords[] = {"type", "buf", "elem", NULL};
- static _PyArg_Parser _parser = {"|$O&O!O!:GPUBatch.__new__", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- bpygpu_ParsePrimType, &params.type_id,
- &BPyGPUVertBuf_Type, &params.py_vertbuf,
- &BPyGPUIndexBuf_Type, &params.py_indexbuf))
- {
- return NULL;
- }
-
- if (params.type_id == GPU_PRIM_NONE) {
- PyErr_Format(PyExc_TypeError,
- exc_str_missing_arg, _keywords[0], 1);
- return NULL;
- }
-
- if (params.py_vertbuf == NULL) {
- PyErr_Format(PyExc_TypeError,
- exc_str_missing_arg, _keywords[1], 2);
- return NULL;
- }
-
- GPUBatch *batch = GPU_batch_create(
- params.type_id,
- params.py_vertbuf->buf,
- params.py_indexbuf ? params.py_indexbuf->elem : NULL);
-
- BPyGPUBatch *ret = (BPyGPUBatch *)BPyGPUBatch_CreatePyObject(batch);
+ BPYGPU_IS_INIT_OR_ERROR_OBJ;
+
+ const char *exc_str_missing_arg = "GPUBatch.__new__() missing required argument '%s' (pos %d)";
+
+ struct {
+ GPUPrimType type_id;
+ BPyGPUVertBuf *py_vertbuf;
+ BPyGPUIndexBuf *py_indexbuf;
+ } params = {GPU_PRIM_NONE, NULL, NULL};
+
+ static const char *_keywords[] = {"type", "buf", "elem", NULL};
+ static _PyArg_Parser _parser = {"|$O&O!O!:GPUBatch.__new__", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kwds,
+ &_parser,
+ bpygpu_ParsePrimType,
+ &params.type_id,
+ &BPyGPUVertBuf_Type,
+ &params.py_vertbuf,
+ &BPyGPUIndexBuf_Type,
+ &params.py_indexbuf)) {
+ return NULL;
+ }
+
+ if (params.type_id == GPU_PRIM_NONE) {
+ PyErr_Format(PyExc_TypeError, exc_str_missing_arg, _keywords[0], 1);
+ return NULL;
+ }
+
+ if (params.py_vertbuf == NULL) {
+ PyErr_Format(PyExc_TypeError, exc_str_missing_arg, _keywords[1], 2);
+ return NULL;
+ }
+
+ GPUBatch *batch = GPU_batch_create(params.type_id,
+ params.py_vertbuf->buf,
+ params.py_indexbuf ? params.py_indexbuf->elem : NULL);
+
+ BPyGPUBatch *ret = (BPyGPUBatch *)BPyGPUBatch_CreatePyObject(batch);
#ifdef USE_GPU_PY_REFERENCES
- ret->references = PyList_New(params.py_indexbuf ? 2 : 1);
- PyList_SET_ITEM(ret->references, 0, (PyObject *)params.py_vertbuf);
- Py_INCREF(params.py_vertbuf);
+ ret->references = PyList_New(params.py_indexbuf ? 2 : 1);
+ PyList_SET_ITEM(ret->references, 0, (PyObject *)params.py_vertbuf);
+ Py_INCREF(params.py_vertbuf);
- if (params.py_indexbuf != NULL) {
- PyList_SET_ITEM(ret->references, 1, (PyObject *)params.py_indexbuf);
- Py_INCREF(params.py_indexbuf);
- }
+ if (params.py_indexbuf != NULL) {
+ PyList_SET_ITEM(ret->references, 1, (PyObject *)params.py_indexbuf);
+ Py_INCREF(params.py_indexbuf);
+ }
- PyObject_GC_Track(ret);
+ PyObject_GC_Track(ret);
#endif
- return (PyObject *)ret;
+ return (PyObject *)ret;
}
PyDoc_STRVAR(bpygpu_Batch_vertbuf_add_doc,
@@ -140,240 +135,224 @@ PyDoc_STRVAR(bpygpu_Batch_vertbuf_add_doc,
);
static PyObject *bpygpu_Batch_vertbuf_add(BPyGPUBatch *self, BPyGPUVertBuf *py_buf)
{
- if (!BPyGPUVertBuf_Check(py_buf)) {
- PyErr_Format(PyExc_TypeError,
- "Expected a GPUVertBuf, got %s",
- Py_TYPE(py_buf)->tp_name);
- return NULL;
- }
-
- if (self->batch->verts[0]->vertex_len != py_buf->buf->vertex_len) {
- PyErr_Format(PyExc_TypeError,
- "Expected %d length, got %d",
- self->batch->verts[0]->vertex_len, py_buf->buf->vertex_len);
- return NULL;
- }
-
- if (self->batch->verts[GPU_BATCH_VBO_MAX_LEN - 1] != NULL) {
- PyErr_SetString(
- PyExc_RuntimeError,
- "Maximum number of vertex buffers exceeded: " STRINGIFY(GPU_BATCH_VBO_MAX_LEN));
- return NULL;
- }
+ if (!BPyGPUVertBuf_Check(py_buf)) {
+ PyErr_Format(PyExc_TypeError, "Expected a GPUVertBuf, got %s", Py_TYPE(py_buf)->tp_name);
+ return NULL;
+ }
+
+ if (self->batch->verts[0]->vertex_len != py_buf->buf->vertex_len) {
+ PyErr_Format(PyExc_TypeError,
+ "Expected %d length, got %d",
+ self->batch->verts[0]->vertex_len,
+ py_buf->buf->vertex_len);
+ return NULL;
+ }
+
+ if (self->batch->verts[GPU_BATCH_VBO_MAX_LEN - 1] != NULL) {
+ PyErr_SetString(
+ PyExc_RuntimeError,
+ "Maximum number of vertex buffers exceeded: " STRINGIFY(GPU_BATCH_VBO_MAX_LEN));
+ return NULL;
+ }
#ifdef USE_GPU_PY_REFERENCES
- /* Hold user */
- PyList_Append(self->references, (PyObject *)py_buf);
+ /* Hold user */
+ PyList_Append(self->references, (PyObject *)py_buf);
#endif
- GPU_batch_vertbuf_add(self->batch, py_buf->buf);
- Py_RETURN_NONE;
+ GPU_batch_vertbuf_add(self->batch, py_buf->buf);
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpygpu_Batch_program_set_doc,
-".. method:: program_set(program)\n"
-"\n"
-" Assign a shader to this batch that will be used for drawing when not overwritten later.\n"
-" Note: This method has to be called in the draw context that the batch will be drawn in.\n"
-" This function does not need to be called when you always set the shader when calling `batch.draw`.\n"
-"\n"
-" :param program: The program/shader the batch will use in future draw calls.\n"
-" :type program: :class:`gpu.types.GPUShader`\n"
-);
+PyDoc_STRVAR(
+ bpygpu_Batch_program_set_doc,
+ ".. method:: program_set(program)\n"
+ "\n"
+ " Assign a shader to this batch that will be used for drawing when not overwritten later.\n"
+ " Note: This method has to be called in the draw context that the batch will be drawn in.\n"
+ " This function does not need to be called when you always set the shader when calling "
+ "`batch.draw`.\n"
+ "\n"
+ " :param program: The program/shader the batch will use in future draw calls.\n"
+ " :type program: :class:`gpu.types.GPUShader`\n");
static PyObject *bpygpu_Batch_program_set(BPyGPUBatch *self, BPyGPUShader *py_shader)
{
- if (!BPyGPUShader_Check(py_shader)) {
- PyErr_Format(PyExc_TypeError,
- "Expected a GPUShader, got %s",
- Py_TYPE(py_shader)->tp_name);
- return NULL;
- }
-
- GPUShader *shader = py_shader->shader;
- GPU_batch_program_set(
- self->batch,
- GPU_shader_get_program(shader),
- GPU_shader_get_interface(shader));
+ if (!BPyGPUShader_Check(py_shader)) {
+ PyErr_Format(PyExc_TypeError, "Expected a GPUShader, got %s", Py_TYPE(py_shader)->tp_name);
+ return NULL;
+ }
+
+ GPUShader *shader = py_shader->shader;
+ GPU_batch_program_set(
+ self->batch, GPU_shader_get_program(shader), GPU_shader_get_interface(shader));
#ifdef USE_GPU_PY_REFERENCES
- /* Remove existing user (if any), hold new user. */
- int i = PyList_GET_SIZE(self->references);
- while (--i != -1) {
- PyObject *py_shader_test = PyList_GET_ITEM(self->references, i);
- if (BPyGPUShader_Check(py_shader_test)) {
- PyList_SET_ITEM(self->references, i, (PyObject *)py_shader);
- Py_INCREF(py_shader);
- Py_DECREF(py_shader_test);
- /* Only ever reference one shader. */
- break;
- }
- }
- if (i != -1) {
- PyList_Append(self->references, (PyObject *)py_shader);
- }
+ /* Remove existing user (if any), hold new user. */
+ int i = PyList_GET_SIZE(self->references);
+ while (--i != -1) {
+ PyObject *py_shader_test = PyList_GET_ITEM(self->references, i);
+ if (BPyGPUShader_Check(py_shader_test)) {
+ PyList_SET_ITEM(self->references, i, (PyObject *)py_shader);
+ Py_INCREF(py_shader);
+ Py_DECREF(py_shader_test);
+ /* Only ever reference one shader. */
+ break;
+ }
+ }
+ if (i != -1) {
+ PyList_Append(self->references, (PyObject *)py_shader);
+ }
#endif
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_Batch_draw_doc,
-".. method:: draw(program=None)\n"
-"\n"
-" Run the drawing program with the parameters assigned to the batch.\n"
-"\n"
-" :param program: Program that performs the drawing operations.\n"
-" If ``None`` is passed, the last program setted to this batch will run.\n"
-" :type program: :class:`gpu.types.GPUShader`\n"
-);
+ ".. method:: draw(program=None)\n"
+ "\n"
+ " Run the drawing program with the parameters assigned to the batch.\n"
+ "\n"
+ " :param program: Program that performs the drawing operations.\n"
+ " If ``None`` is passed, the last program setted to this batch will run.\n"
+ " :type program: :class:`gpu.types.GPUShader`\n");
static PyObject *bpygpu_Batch_draw(BPyGPUBatch *self, PyObject *args)
{
- BPyGPUShader *py_program = NULL;
-
- if (!PyArg_ParseTuple(
- args, "|O!:GPUBatch.draw",
- &BPyGPUShader_Type, &py_program))
- {
- return NULL;
- }
- else if (py_program == NULL) {
- if (!bpygpu_batch_is_program_or_error(self)) {
- return NULL;
- }
- }
- else if (self->batch->program != GPU_shader_get_program(py_program->shader)) {
- GPU_batch_program_set(
- self->batch,
- GPU_shader_get_program(py_program->shader),
- GPU_shader_get_interface(py_program->shader));
- }
-
- GPU_batch_draw(self->batch);
- Py_RETURN_NONE;
+ BPyGPUShader *py_program = NULL;
+
+ if (!PyArg_ParseTuple(args, "|O!:GPUBatch.draw", &BPyGPUShader_Type, &py_program)) {
+ return NULL;
+ }
+ else if (py_program == NULL) {
+ if (!bpygpu_batch_is_program_or_error(self)) {
+ return NULL;
+ }
+ }
+ else if (self->batch->program != GPU_shader_get_program(py_program->shader)) {
+ GPU_batch_program_set(self->batch,
+ GPU_shader_get_program(py_program->shader),
+ GPU_shader_get_interface(py_program->shader));
+ }
+
+ GPU_batch_draw(self->batch);
+ Py_RETURN_NONE;
}
static PyObject *bpygpu_Batch_program_use_begin(BPyGPUBatch *self)
{
- if (!bpygpu_batch_is_program_or_error(self)) {
- return NULL;
- }
- GPU_batch_program_use_begin(self->batch);
- Py_RETURN_NONE;
+ if (!bpygpu_batch_is_program_or_error(self)) {
+ return NULL;
+ }
+ GPU_batch_program_use_begin(self->batch);
+ Py_RETURN_NONE;
}
static PyObject *bpygpu_Batch_program_use_end(BPyGPUBatch *self)
{
- if (!bpygpu_batch_is_program_or_error(self)) {
- return NULL;
- }
- GPU_batch_program_use_end(self->batch);
- Py_RETURN_NONE;
+ if (!bpygpu_batch_is_program_or_error(self)) {
+ return NULL;
+ }
+ GPU_batch_program_use_end(self->batch);
+ Py_RETURN_NONE;
}
static struct PyMethodDef bpygpu_Batch_methods[] = {
- {"vertbuf_add", (PyCFunction)bpygpu_Batch_vertbuf_add,
- METH_O, bpygpu_Batch_vertbuf_add_doc},
- {"program_set", (PyCFunction)bpygpu_Batch_program_set,
- METH_O, bpygpu_Batch_program_set_doc},
- {"draw", (PyCFunction) bpygpu_Batch_draw,
- METH_VARARGS, bpygpu_Batch_draw_doc},
- {"_program_use_begin", (PyCFunction)bpygpu_Batch_program_use_begin,
- METH_NOARGS, ""},
- {"_program_use_end", (PyCFunction)bpygpu_Batch_program_use_end,
- METH_NOARGS, ""},
- {NULL, NULL, 0, NULL},
+ {"vertbuf_add", (PyCFunction)bpygpu_Batch_vertbuf_add, METH_O, bpygpu_Batch_vertbuf_add_doc},
+ {"program_set", (PyCFunction)bpygpu_Batch_program_set, METH_O, bpygpu_Batch_program_set_doc},
+ {"draw", (PyCFunction)bpygpu_Batch_draw, METH_VARARGS, bpygpu_Batch_draw_doc},
+ {"_program_use_begin", (PyCFunction)bpygpu_Batch_program_use_begin, METH_NOARGS, ""},
+ {"_program_use_end", (PyCFunction)bpygpu_Batch_program_use_end, METH_NOARGS, ""},
+ {NULL, NULL, 0, NULL},
};
#ifdef USE_GPU_PY_REFERENCES
static int bpygpu_Batch_traverse(BPyGPUBatch *self, visitproc visit, void *arg)
{
- Py_VISIT(self->references);
- return 0;
+ Py_VISIT(self->references);
+ return 0;
}
static int bpygpu_Batch_clear(BPyGPUBatch *self)
{
- Py_CLEAR(self->references);
- return 0;
+ Py_CLEAR(self->references);
+ return 0;
}
#endif
static void bpygpu_Batch_dealloc(BPyGPUBatch *self)
{
- GPU_batch_discard(self->batch);
+ GPU_batch_discard(self->batch);
#ifdef USE_GPU_PY_REFERENCES
- if (self->references) {
- PyObject_GC_UnTrack(self);
- bpygpu_Batch_clear(self);
- Py_XDECREF(self->references);
- }
+ if (self->references) {
+ PyObject_GC_UnTrack(self);
+ bpygpu_Batch_clear(self);
+ Py_XDECREF(self->references);
+ }
#endif
- Py_TYPE(self)->tp_free(self);
+ Py_TYPE(self)->tp_free(self);
}
-PyDoc_STRVAR(py_gpu_batch_doc,
-".. class:: GPUBatch(type, buf, elem=None)\n"
-"\n"
-" Reusable container for drawable geometry.\n"
-"\n"
-" :arg type: One of these primitive types: {\n"
-" `POINTS`,\n"
-" `LINES`,\n"
-" `TRIS`,\n"
-" `LINE_STRIP`,\n"
-" `LINE_LOOP`,\n"
-" `TRI_STRIP`,\n"
-" `TRI_FAN`,\n"
-" `LINES_ADJ`,\n"
-" `TRIS_ADJ`,\n"
-" `LINE_STRIP_ADJ` }\n"
-" :type type: `str`\n"
-" :arg buf: Vertex buffer containing all or some of the attributes required for drawing.\n"
-" :type buf: :class:`gpu.types.GPUVertBuf`\n"
-" :arg elem: An optional index buffer.\n"
-" :type elem: :class:`gpu.types.GPUIndexBuf`\n"
-);
+PyDoc_STRVAR(
+ py_gpu_batch_doc,
+ ".. class:: GPUBatch(type, buf, elem=None)\n"
+ "\n"
+ " Reusable container for drawable geometry.\n"
+ "\n"
+ " :arg type: One of these primitive types: {\n"
+ " `POINTS`,\n"
+ " `LINES`,\n"
+ " `TRIS`,\n"
+ " `LINE_STRIP`,\n"
+ " `LINE_LOOP`,\n"
+ " `TRI_STRIP`,\n"
+ " `TRI_FAN`,\n"
+ " `LINES_ADJ`,\n"
+ " `TRIS_ADJ`,\n"
+ " `LINE_STRIP_ADJ` }\n"
+ " :type type: `str`\n"
+ " :arg buf: Vertex buffer containing all or some of the attributes required for drawing.\n"
+ " :type buf: :class:`gpu.types.GPUVertBuf`\n"
+ " :arg elem: An optional index buffer.\n"
+ " :type elem: :class:`gpu.types.GPUIndexBuf`\n");
PyTypeObject BPyGPUBatch_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUBatch",
- .tp_basicsize = sizeof(BPyGPUBatch),
- .tp_dealloc = (destructor)bpygpu_Batch_dealloc,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUBatch",
+ .tp_basicsize = sizeof(BPyGPUBatch),
+ .tp_dealloc = (destructor)bpygpu_Batch_dealloc,
#ifdef USE_GPU_PY_REFERENCES
- .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
- .tp_doc = py_gpu_batch_doc,
- .tp_traverse = (traverseproc)bpygpu_Batch_traverse,
- .tp_clear = (inquiry)bpygpu_Batch_clear,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = py_gpu_batch_doc,
+ .tp_traverse = (traverseproc)bpygpu_Batch_traverse,
+ .tp_clear = (inquiry)bpygpu_Batch_clear,
#else
- .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
#endif
- .tp_methods = bpygpu_Batch_methods,
- .tp_new = bpygpu_Batch_new,
+ .tp_methods = bpygpu_Batch_methods,
+ .tp_new = bpygpu_Batch_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUBatch_CreatePyObject(GPUBatch *batch)
{
- BPyGPUBatch *self;
+ BPyGPUBatch *self;
#ifdef USE_GPU_PY_REFERENCES
- self = (BPyGPUBatch *)_PyObject_GC_New(&BPyGPUBatch_Type);
- self->references = NULL;
+ self = (BPyGPUBatch *)_PyObject_GC_New(&BPyGPUBatch_Type);
+ self->references = NULL;
#else
- self = PyObject_New(BPyGPUBatch, &BPyGPUBatch_Type);
+ self = PyObject_New(BPyGPUBatch, &BPyGPUBatch_Type);
#endif
- self->batch = batch;
+ self->batch = batch;
- return (PyObject *)self;
+ return (PyObject *)self;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_batch.h b/source/blender/python/gpu/gpu_py_batch.h
index a0de4663889..1e916afcc2e 100644
--- a/source/blender/python/gpu/gpu_py_batch.h
+++ b/source/blender/python/gpu/gpu_py_batch.h
@@ -27,15 +27,15 @@
extern PyTypeObject BPyGPUBatch_Type;
-#define BPyGPUBatch_Check(v) (Py_TYPE(v) == &BPyGPUBatch_Type)
+#define BPyGPUBatch_Check(v) (Py_TYPE(v) == &BPyGPUBatch_Type)
typedef struct BPyGPUBatch {
- PyObject_VAR_HEAD
- /* The batch is owned, we may support thin wrapped batches later. */
- struct GPUBatch *batch;
+ PyObject_VAR_HEAD
+ /* The batch is owned, we may support thin wrapped batches later. */
+ struct GPUBatch *batch;
#ifdef USE_GPU_PY_REFERENCES
- /* Just to keep a user to prevent freeing buf's we're using */
- PyObject *references;
+ /* Just to keep a user to prevent freeing buf's we're using */
+ PyObject *references;
#endif
} BPyGPUBatch;
diff --git a/source/blender/python/gpu/gpu_py_element.c b/source/blender/python/gpu/gpu_py_element.c
index b33ab9ec7cc..b9d87f57e9d 100644
--- a/source/blender/python/gpu/gpu_py_element.c
+++ b/source/blender/python/gpu/gpu_py_element.c
@@ -35,204 +35,190 @@
#include "gpu_py_api.h"
#include "gpu_py_element.h" /* own include */
-
/* -------------------------------------------------------------------- */
/** \name IndexBuf Type
* \{ */
static PyObject *bpygpu_IndexBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- BPYGPU_IS_INIT_OR_ERROR_OBJ;
-
- const char *error_prefix = "IndexBuf.__new__";
- bool ok = true;
-
- struct {
- GPUPrimType type_id;
- PyObject *seq;
- } params;
-
- uint verts_per_prim;
- uint index_len;
- GPUIndexBufBuilder builder;
-
- static const char *_keywords[] = {"type", "seq", NULL};
- static _PyArg_Parser _parser = {"$O&O:IndexBuf.__new__", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- bpygpu_ParsePrimType, &params.type_id,
- &params.seq))
- {
- return NULL;
- }
-
- verts_per_prim = GPU_indexbuf_primitive_len(params.type_id);
- if (verts_per_prim == -1) {
- PyErr_Format(PyExc_ValueError,
- "The argument 'type' must be "
- "'POINTS', 'LINES', 'TRIS' or 'LINES_ADJ'");
- return NULL;
- }
-
- if (PyObject_CheckBuffer(params.seq)) {
- Py_buffer pybuffer;
-
- if (PyObject_GetBuffer(params.seq, &pybuffer, PyBUF_FORMAT | PyBUF_ND) == -1) {
- /* PyObject_GetBuffer already handles error messages. */
- return NULL;
- }
-
- if (pybuffer.ndim != 1 && pybuffer.shape[1] != verts_per_prim) {
- PyErr_Format(PyExc_ValueError,
- "Each primitive must exactly %d indices",
- verts_per_prim);
- return NULL;
- }
-
- if (pybuffer.itemsize != 4 ||
- PyC_StructFmt_type_is_float_any(PyC_StructFmt_type_from_str(pybuffer.format)))
- {
- PyErr_Format(PyExc_ValueError,
- "Each index must be an 4-bytes integer value");
- return NULL;
- }
-
- index_len = pybuffer.shape[0];
- if (pybuffer.ndim != 1) {
- index_len *= pybuffer.shape[1];
- }
-
- /* The `vertex_len` parameter is only used for asserts in the Debug build. */
- /* Not very useful in python since scripts are often tested in Release build. */
- /* Use `INT_MAX` instead of the actual number of vertices. */
- GPU_indexbuf_init(
- &builder, params.type_id, index_len, INT_MAX);
+ BPYGPU_IS_INIT_OR_ERROR_OBJ;
+
+ const char *error_prefix = "IndexBuf.__new__";
+ bool ok = true;
+
+ struct {
+ GPUPrimType type_id;
+ PyObject *seq;
+ } params;
+
+ uint verts_per_prim;
+ uint index_len;
+ GPUIndexBufBuilder builder;
+
+ static const char *_keywords[] = {"type", "seq", NULL};
+ static _PyArg_Parser _parser = {"$O&O:IndexBuf.__new__", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kwds, &_parser, bpygpu_ParsePrimType, &params.type_id, &params.seq)) {
+ return NULL;
+ }
+
+ verts_per_prim = GPU_indexbuf_primitive_len(params.type_id);
+ if (verts_per_prim == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "The argument 'type' must be "
+ "'POINTS', 'LINES', 'TRIS' or 'LINES_ADJ'");
+ return NULL;
+ }
+
+ if (PyObject_CheckBuffer(params.seq)) {
+ Py_buffer pybuffer;
+
+ if (PyObject_GetBuffer(params.seq, &pybuffer, PyBUF_FORMAT | PyBUF_ND) == -1) {
+ /* PyObject_GetBuffer already handles error messages. */
+ return NULL;
+ }
+
+ if (pybuffer.ndim != 1 && pybuffer.shape[1] != verts_per_prim) {
+ PyErr_Format(PyExc_ValueError, "Each primitive must exactly %d indices", verts_per_prim);
+ return NULL;
+ }
+
+ if (pybuffer.itemsize != 4 ||
+ PyC_StructFmt_type_is_float_any(PyC_StructFmt_type_from_str(pybuffer.format))) {
+ PyErr_Format(PyExc_ValueError, "Each index must be an 4-bytes integer value");
+ return NULL;
+ }
+
+ index_len = pybuffer.shape[0];
+ if (pybuffer.ndim != 1) {
+ index_len *= pybuffer.shape[1];
+ }
+
+ /* The `vertex_len` parameter is only used for asserts in the Debug build. */
+ /* Not very useful in python since scripts are often tested in Release build. */
+ /* Use `INT_MAX` instead of the actual number of vertices. */
+ GPU_indexbuf_init(&builder, params.type_id, index_len, INT_MAX);
#if 0
- uint *buf = pybuffer.buf;
- for (uint i = index_len; i--; buf++) {
- GPU_indexbuf_add_generic_vert(&builder, *buf);
- }
+ uint *buf = pybuffer.buf;
+ for (uint i = index_len; i--; buf++) {
+ GPU_indexbuf_add_generic_vert(&builder, *buf);
+ }
#else
- memcpy(builder.data, pybuffer.buf, index_len * sizeof(*builder.data));
- builder.index_len = index_len;
+ memcpy(builder.data, pybuffer.buf, index_len * sizeof(*builder.data));
+ builder.index_len = index_len;
#endif
- PyBuffer_Release(&pybuffer);
- }
- else {
- PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
-
- if (seq_fast == NULL) {
- return false;
- }
-
- const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
-
- PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
-
- index_len = seq_len * verts_per_prim;
-
- /* The `vertex_len` parameter is only used for asserts in the Debug build. */
- /* Not very useful in python since scripts are often tested in Release build. */
- /* Use `INT_MAX` instead of the actual number of vertices. */
- GPU_indexbuf_init(
- &builder, params.type_id, index_len, INT_MAX);
-
- if (verts_per_prim == 1) {
- for (uint i = 0; i < seq_len; i++) {
- GPU_indexbuf_add_generic_vert(
- &builder, PyC_Long_AsU32(seq_items[i]));
- }
- }
- else {
- int values[4];
- for (uint i = 0; i < seq_len; i++) {
- PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
- if (seq_fast_item == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%s: expected a sequence, got %s",
- error_prefix, Py_TYPE(seq_items[i])->tp_name);
- ok = false;
- goto finally;
- }
-
- ok = PyC_AsArray_FAST(
- values, seq_fast_item, verts_per_prim,
- &PyLong_Type, false, error_prefix) == 0;
-
- if (ok) {
- for (uint j = 0; j < verts_per_prim; j++) {
- GPU_indexbuf_add_generic_vert(&builder, values[j]);
- }
- }
- Py_DECREF(seq_fast_item);
- }
- }
-
- if (PyErr_Occurred()) {
- ok = false;
- }
-
-finally:
-
- Py_DECREF(seq_fast);
- }
-
- if (ok == false) {
- MEM_freeN(builder.data);
- return NULL;
- }
-
- return BPyGPUIndexBuf_CreatePyObject(GPU_indexbuf_build(&builder));
+ PyBuffer_Release(&pybuffer);
+ }
+ else {
+ PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
+
+ if (seq_fast == NULL) {
+ return false;
+ }
+
+ const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
+
+ PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
+
+ index_len = seq_len * verts_per_prim;
+
+ /* The `vertex_len` parameter is only used for asserts in the Debug build. */
+ /* Not very useful in python since scripts are often tested in Release build. */
+ /* Use `INT_MAX` instead of the actual number of vertices. */
+ GPU_indexbuf_init(&builder, params.type_id, index_len, INT_MAX);
+
+ if (verts_per_prim == 1) {
+ for (uint i = 0; i < seq_len; i++) {
+ GPU_indexbuf_add_generic_vert(&builder, PyC_Long_AsU32(seq_items[i]));
+ }
+ }
+ else {
+ int values[4];
+ for (uint i = 0; i < seq_len; i++) {
+ PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
+ if (seq_fast_item == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: expected a sequence, got %s",
+ error_prefix,
+ Py_TYPE(seq_items[i])->tp_name);
+ ok = false;
+ goto finally;
+ }
+
+ ok = PyC_AsArray_FAST(
+ values, seq_fast_item, verts_per_prim, &PyLong_Type, false, error_prefix) == 0;
+
+ if (ok) {
+ for (uint j = 0; j < verts_per_prim; j++) {
+ GPU_indexbuf_add_generic_vert(&builder, values[j]);
+ }
+ }
+ Py_DECREF(seq_fast_item);
+ }
+ }
+
+ if (PyErr_Occurred()) {
+ ok = false;
+ }
+
+ finally:
+
+ Py_DECREF(seq_fast);
+ }
+
+ if (ok == false) {
+ MEM_freeN(builder.data);
+ return NULL;
+ }
+
+ return BPyGPUIndexBuf_CreatePyObject(GPU_indexbuf_build(&builder));
}
static void bpygpu_IndexBuf_dealloc(BPyGPUIndexBuf *self)
{
- GPU_indexbuf_discard(self->elem);
- Py_TYPE(self)->tp_free(self);
+ GPU_indexbuf_discard(self->elem);
+ Py_TYPE(self)->tp_free(self);
}
PyDoc_STRVAR(py_gpu_element_doc,
-".. class:: GPUIndexBuf(type, seq)\n"
-"\n"
-" Contains an index buffer.\n"
-"\n"
-" :param type: One of these primitive types: {\n"
-" `POINTS`,\n"
-" `LINES`,\n"
-" `TRIS`,\n"
-" `LINE_STRIP_ADJ` }\n"
-" :type type: `str`\n"
-" :param seq: Indices this index buffer will contain.\n"
-" Whether a 1D or 2D sequence is required depends on the type.\n"
-" Optionally the sequence can support the buffer protocol.\n"
-" :type seq: 1D or 2D sequence\n"
-);
+ ".. class:: GPUIndexBuf(type, seq)\n"
+ "\n"
+ " Contains an index buffer.\n"
+ "\n"
+ " :param type: One of these primitive types: {\n"
+ " `POINTS`,\n"
+ " `LINES`,\n"
+ " `TRIS`,\n"
+ " `LINE_STRIP_ADJ` }\n"
+ " :type type: `str`\n"
+ " :param seq: Indices this index buffer will contain.\n"
+ " Whether a 1D or 2D sequence is required depends on the type.\n"
+ " Optionally the sequence can support the buffer protocol.\n"
+ " :type seq: 1D or 2D sequence\n");
PyTypeObject BPyGPUIndexBuf_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUIndexBuf",
- .tp_basicsize = sizeof(BPyGPUIndexBuf),
- .tp_dealloc = (destructor)bpygpu_IndexBuf_dealloc,
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_doc = py_gpu_element_doc,
- .tp_new = bpygpu_IndexBuf_new,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUIndexBuf",
+ .tp_basicsize = sizeof(BPyGPUIndexBuf),
+ .tp_dealloc = (destructor)bpygpu_IndexBuf_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = py_gpu_element_doc,
+ .tp_new = bpygpu_IndexBuf_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUIndexBuf_CreatePyObject(GPUIndexBuf *elem)
{
- BPyGPUIndexBuf *self;
+ BPyGPUIndexBuf *self;
- self = PyObject_New(BPyGPUIndexBuf, &BPyGPUIndexBuf_Type);
- self->elem = elem;
+ self = PyObject_New(BPyGPUIndexBuf, &BPyGPUIndexBuf_Type);
+ self->elem = elem;
- return (PyObject *)self;
+ return (PyObject *)self;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_element.h b/source/blender/python/gpu/gpu_py_element.h
index 274149db565..055c9d54ecf 100644
--- a/source/blender/python/gpu/gpu_py_element.h
+++ b/source/blender/python/gpu/gpu_py_element.h
@@ -23,11 +23,10 @@
extern PyTypeObject BPyGPUIndexBuf_Type;
-#define BPyGPUIndexBuf_Check(v) (Py_TYPE(v) == &BPyGPUIndexBuf_Type)
+#define BPyGPUIndexBuf_Check(v) (Py_TYPE(v) == &BPyGPUIndexBuf_Type)
typedef struct BPyGPUIndexBuf {
- PyObject_VAR_HEAD
- struct GPUIndexBuf *elem;
+ PyObject_VAR_HEAD struct GPUIndexBuf *elem;
} BPyGPUIndexBuf;
PyObject *BPyGPUIndexBuf_CreatePyObject(struct GPUIndexBuf *elem);
diff --git a/source/blender/python/gpu/gpu_py_matrix.c b/source/blender/python/gpu/gpu_py_matrix.c
index 6f74fc41567..85d65ee4e2c 100644
--- a/source/blender/python/gpu/gpu_py_matrix.c
+++ b/source/blender/python/gpu/gpu_py_matrix.c
@@ -28,7 +28,6 @@
#include <Python.h>
-
#include "BLI_utildefines.h"
#include "../mathutils/mathutils.h"
@@ -47,42 +46,42 @@
static bool bpygpu_stack_is_push_model_view_ok_or_error(void)
{
- if (GPU_matrix_stack_level_get_model_view() >= GPU_PY_MATRIX_STACK_LEN) {
- PyErr_SetString(PyExc_RuntimeError,
- "Maximum model-view stack depth " STRINGIFY(GPU_PY_MATRIX_STACK_DEPTH) " reached");
- return false;
- }
- return true;
+ if (GPU_matrix_stack_level_get_model_view() >= GPU_PY_MATRIX_STACK_LEN) {
+ PyErr_SetString(
+ PyExc_RuntimeError,
+ "Maximum model-view stack depth " STRINGIFY(GPU_PY_MATRIX_STACK_DEPTH) " reached");
+ return false;
+ }
+ return true;
}
static bool bpygpu_stack_is_push_projection_ok_or_error(void)
{
- if (GPU_matrix_stack_level_get_projection() >= GPU_PY_MATRIX_STACK_LEN) {
- PyErr_SetString(PyExc_RuntimeError,
- "Maximum projection stack depth " STRINGIFY(GPU_PY_MATRIX_STACK_DEPTH) " reached");
- return false;
- }
- return true;
+ if (GPU_matrix_stack_level_get_projection() >= GPU_PY_MATRIX_STACK_LEN) {
+ PyErr_SetString(
+ PyExc_RuntimeError,
+ "Maximum projection stack depth " STRINGIFY(GPU_PY_MATRIX_STACK_DEPTH) " reached");
+ return false;
+ }
+ return true;
}
static bool bpygpu_stack_is_pop_model_view_ok_or_error(void)
{
- if (GPU_matrix_stack_level_get_model_view() == 0) {
- PyErr_SetString(PyExc_RuntimeError,
- "Minimum model-view stack depth reached");
- return false;
- }
- return true;
+ if (GPU_matrix_stack_level_get_model_view() == 0) {
+ PyErr_SetString(PyExc_RuntimeError, "Minimum model-view stack depth reached");
+ return false;
+ }
+ return true;
}
static bool bpygpu_stack_is_pop_projection_ok_or_error(void)
{
- if (GPU_matrix_stack_level_get_projection() == 0) {
- PyErr_SetString(PyExc_RuntimeError,
- "Minimum projection stack depth reached");
- return false;
- }
- return true;
+ if (GPU_matrix_stack_level_get_projection() == 0) {
+ PyErr_SetString(PyExc_RuntimeError, "Minimum projection stack depth reached");
+ return false;
+ }
+ return true;
}
/** \} */
@@ -92,59 +91,55 @@ static bool bpygpu_stack_is_pop_projection_ok_or_error(void)
* \{ */
PyDoc_STRVAR(bpygpu_matrix_push_doc,
-".. function:: push()\n"
-"\n"
-" Add to the model-view matrix stack.\n"
-);
+ ".. function:: push()\n"
+ "\n"
+ " Add to the model-view matrix stack.\n");
static PyObject *bpygpu_matrix_push(PyObject *UNUSED(self))
{
- if (!bpygpu_stack_is_push_model_view_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_push();
- Py_RETURN_NONE;
+ if (!bpygpu_stack_is_push_model_view_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_push();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_pop_doc,
-".. function:: pop()\n"
-"\n"
-" Remove the last model-view matrix from the stack.\n"
-);
+ ".. function:: pop()\n"
+ "\n"
+ " Remove the last model-view matrix from the stack.\n");
static PyObject *bpygpu_matrix_pop(PyObject *UNUSED(self))
{
- if (!bpygpu_stack_is_pop_model_view_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_pop();
- Py_RETURN_NONE;
+ if (!bpygpu_stack_is_pop_model_view_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_pop();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_push_projection_doc,
-".. function:: push_projection()\n"
-"\n"
-" Add to the projection matrix stack.\n"
-);
+ ".. function:: push_projection()\n"
+ "\n"
+ " Add to the projection matrix stack.\n");
static PyObject *bpygpu_matrix_push_projection(PyObject *UNUSED(self))
{
- if (!bpygpu_stack_is_push_projection_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_push_projection();
- Py_RETURN_NONE;
+ if (!bpygpu_stack_is_push_projection_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_push_projection();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_pop_projection_doc,
-".. function:: pop_projection()\n"
-"\n"
-" Remove the last projection matrix from the stack.\n"
-);
+ ".. function:: pop_projection()\n"
+ "\n"
+ " Remove the last projection matrix from the stack.\n");
static PyObject *bpygpu_matrix_pop_projection(PyObject *UNUSED(self))
{
- if (!bpygpu_stack_is_pop_projection_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_pop_projection();
- Py_RETURN_NONE;
+ if (!bpygpu_stack_is_pop_projection_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_pop_projection();
+ Py_RETURN_NONE;
}
/** \} */
@@ -157,120 +152,121 @@ static PyObject *bpygpu_matrix_pop_projection(PyObject *UNUSED(self))
* \{ */
typedef struct {
- PyObject_HEAD /* required python macro */
- int type;
- int level;
+ PyObject_HEAD /* required python macro */
+ int type;
+ int level;
} BPyGPU_MatrixStackContext;
enum {
- PYGPU_MATRIX_TYPE_MODEL_VIEW = 1,
- PYGPU_MATRIX_TYPE_PROJECTION = 2,
+ PYGPU_MATRIX_TYPE_MODEL_VIEW = 1,
+ PYGPU_MATRIX_TYPE_PROJECTION = 2,
};
static PyObject *bpygpu_matrix_stack_context_enter(BPyGPU_MatrixStackContext *self);
static PyObject *bpygpu_matrix_stack_context_exit(BPyGPU_MatrixStackContext *self, PyObject *args);
static PyMethodDef bpygpu_matrix_stack_context_methods[] = {
- {"__enter__", (PyCFunction)bpygpu_matrix_stack_context_enter, METH_NOARGS},
- {"__exit__", (PyCFunction)bpygpu_matrix_stack_context_exit, METH_VARARGS},
- {NULL},
+ {"__enter__", (PyCFunction)bpygpu_matrix_stack_context_enter, METH_NOARGS},
+ {"__exit__", (PyCFunction)bpygpu_matrix_stack_context_exit, METH_VARARGS},
+ {NULL},
};
static PyTypeObject BPyGPU_matrix_stack_context_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUMatrixStackContext",
- .tp_basicsize = sizeof(BPyGPU_MatrixStackContext),
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_methods = bpygpu_matrix_stack_context_methods,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUMatrixStackContext",
+ .tp_basicsize = sizeof(BPyGPU_MatrixStackContext),
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_methods = bpygpu_matrix_stack_context_methods,
};
static PyObject *bpygpu_matrix_stack_context_enter(BPyGPU_MatrixStackContext *self)
{
- /* sanity - should never happen */
- if (self->level != -1) {
- PyErr_SetString(PyExc_RuntimeError, "Already in use");
- return NULL;
- }
-
- if (self->type == PYGPU_MATRIX_TYPE_MODEL_VIEW) {
- if (!bpygpu_stack_is_push_model_view_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_push();
- self->level = GPU_matrix_stack_level_get_model_view();
- }
- else if (self->type == PYGPU_MATRIX_TYPE_PROJECTION) {
- if (!bpygpu_stack_is_push_projection_ok_or_error()) {
- return NULL;
- }
- GPU_matrix_push_projection();
- self->level = GPU_matrix_stack_level_get_projection();
- }
- else {
- BLI_assert(0);
- }
- Py_RETURN_NONE;
+ /* sanity - should never happen */
+ if (self->level != -1) {
+ PyErr_SetString(PyExc_RuntimeError, "Already in use");
+ return NULL;
+ }
+
+ if (self->type == PYGPU_MATRIX_TYPE_MODEL_VIEW) {
+ if (!bpygpu_stack_is_push_model_view_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_push();
+ self->level = GPU_matrix_stack_level_get_model_view();
+ }
+ else if (self->type == PYGPU_MATRIX_TYPE_PROJECTION) {
+ if (!bpygpu_stack_is_push_projection_ok_or_error()) {
+ return NULL;
+ }
+ GPU_matrix_push_projection();
+ self->level = GPU_matrix_stack_level_get_projection();
+ }
+ else {
+ BLI_assert(0);
+ }
+ Py_RETURN_NONE;
}
-static PyObject *bpygpu_matrix_stack_context_exit(BPyGPU_MatrixStackContext *self, PyObject *UNUSED(args))
+static PyObject *bpygpu_matrix_stack_context_exit(BPyGPU_MatrixStackContext *self,
+ PyObject *UNUSED(args))
{
- /* sanity - should never happen */
- if (self->level == -1) {
- fprintf(stderr, "Not yet in use\n");
- goto finally;
- }
-
- if (self->type == PYGPU_MATRIX_TYPE_MODEL_VIEW) {
- const int level = GPU_matrix_stack_level_get_model_view();
- if (level != self->level) {
- fprintf(stderr, "Level push/pop mismatch, expected %d, got %d\n", self->level, level);
- }
- if (level != 0) {
- GPU_matrix_pop();
- }
- }
- else if (self->type == PYGPU_MATRIX_TYPE_PROJECTION) {
- const int level = GPU_matrix_stack_level_get_projection();
- if (level != self->level) {
- fprintf(stderr, "Level push/pop mismatch, expected %d, got %d", self->level, level);
- }
- if (level != 0) {
- GPU_matrix_pop_projection();
- }
- }
- else {
- BLI_assert(0);
- }
+ /* sanity - should never happen */
+ if (self->level == -1) {
+ fprintf(stderr, "Not yet in use\n");
+ goto finally;
+ }
+
+ if (self->type == PYGPU_MATRIX_TYPE_MODEL_VIEW) {
+ const int level = GPU_matrix_stack_level_get_model_view();
+ if (level != self->level) {
+ fprintf(stderr, "Level push/pop mismatch, expected %d, got %d\n", self->level, level);
+ }
+ if (level != 0) {
+ GPU_matrix_pop();
+ }
+ }
+ else if (self->type == PYGPU_MATRIX_TYPE_PROJECTION) {
+ const int level = GPU_matrix_stack_level_get_projection();
+ if (level != self->level) {
+ fprintf(stderr, "Level push/pop mismatch, expected %d, got %d", self->level, level);
+ }
+ if (level != 0) {
+ GPU_matrix_pop_projection();
+ }
+ }
+ else {
+ BLI_assert(0);
+ }
finally:
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *bpygpu_matrix_push_pop_impl(int type)
{
- BPyGPU_MatrixStackContext *ret = PyObject_New(BPyGPU_MatrixStackContext, &BPyGPU_matrix_stack_context_Type);
- ret->type = type;
- ret->level = -1;
- return (PyObject *)ret;
+ BPyGPU_MatrixStackContext *ret = PyObject_New(BPyGPU_MatrixStackContext,
+ &BPyGPU_matrix_stack_context_Type);
+ ret->type = type;
+ ret->level = -1;
+ return (PyObject *)ret;
}
-PyDoc_STRVAR(bpygpu_matrix_push_pop_doc,
-".. function:: push_pop()\n"
-"\n"
-" Context manager to ensure balanced push/pop calls, even in the case of an error.\n"
-);
+PyDoc_STRVAR(
+ bpygpu_matrix_push_pop_doc,
+ ".. function:: push_pop()\n"
+ "\n"
+ " Context manager to ensure balanced push/pop calls, even in the case of an error.\n");
static PyObject *bpygpu_matrix_push_pop(PyObject *UNUSED(self))
{
- return bpygpu_matrix_push_pop_impl(PYGPU_MATRIX_TYPE_MODEL_VIEW);
+ return bpygpu_matrix_push_pop_impl(PYGPU_MATRIX_TYPE_MODEL_VIEW);
}
-PyDoc_STRVAR(bpygpu_matrix_push_pop_projection_doc,
-".. function:: push_pop_projection()\n"
-"\n"
-" Context manager to ensure balanced push/pop calls, even in the case of an error.\n"
-);
+PyDoc_STRVAR(
+ bpygpu_matrix_push_pop_projection_doc,
+ ".. function:: push_pop_projection()\n"
+ "\n"
+ " Context manager to ensure balanced push/pop calls, even in the case of an error.\n");
static PyObject *bpygpu_matrix_push_pop_projection(PyObject *UNUSED(self))
{
- return bpygpu_matrix_push_pop_impl(PYGPU_MATRIX_TYPE_PROJECTION);
+ return bpygpu_matrix_push_pop_impl(PYGPU_MATRIX_TYPE_PROJECTION);
}
/** \} */
@@ -280,88 +276,84 @@ static PyObject *bpygpu_matrix_push_pop_projection(PyObject *UNUSED(self))
* \{ */
PyDoc_STRVAR(bpygpu_matrix_multiply_matrix_doc,
-".. function:: multiply_matrix(matrix)\n"
-"\n"
-" Multiply the current stack matrix.\n"
-"\n"
-" :param matrix: A 4x4 matrix.\n"
-" :type matrix: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: multiply_matrix(matrix)\n"
+ "\n"
+ " Multiply the current stack matrix.\n"
+ "\n"
+ " :param matrix: A 4x4 matrix.\n"
+ " :type matrix: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_multiply_matrix(PyObject *UNUSED(self), PyObject *value)
{
- MatrixObject *pymat;
- if (!Matrix_Parse4x4(value, &pymat)) {
- return NULL;
- }
- GPU_matrix_mul(pymat->matrix);
- Py_RETURN_NONE;
+ MatrixObject *pymat;
+ if (!Matrix_Parse4x4(value, &pymat)) {
+ return NULL;
+ }
+ GPU_matrix_mul(pymat->matrix);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_scale_doc,
-".. function:: scale(scale)\n"
-"\n"
-" Scale the current stack matrix.\n"
-"\n"
-" :param scale: Scale the current stack matrix.\n"
-" :type scale: sequence of 2 or 3 floats\n"
-);
+ ".. function:: scale(scale)\n"
+ "\n"
+ " Scale the current stack matrix.\n"
+ "\n"
+ " :param scale: Scale the current stack matrix.\n"
+ " :type scale: sequence of 2 or 3 floats\n");
static PyObject *bpygpu_matrix_scale(PyObject *UNUSED(self), PyObject *value)
{
- float scale[3];
- int len;
- if ((len = mathutils_array_parse(scale, 2, 3, value, "gpu.matrix.scale(): invalid vector arg")) == -1) {
- return NULL;
- }
- if (len == 2) {
- GPU_matrix_scale_2fv(scale);
- }
- else {
- GPU_matrix_scale_3fv(scale);
- }
- Py_RETURN_NONE;
+ float scale[3];
+ int len;
+ if ((len = mathutils_array_parse(
+ scale, 2, 3, value, "gpu.matrix.scale(): invalid vector arg")) == -1) {
+ return NULL;
+ }
+ if (len == 2) {
+ GPU_matrix_scale_2fv(scale);
+ }
+ else {
+ GPU_matrix_scale_3fv(scale);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_scale_uniform_doc,
-".. function:: scale_uniform(scale)\n"
-"\n"
-" :param scale: Scale the current stack matrix.\n"
-" :type scale: float\n"
-);
+ ".. function:: scale_uniform(scale)\n"
+ "\n"
+ " :param scale: Scale the current stack matrix.\n"
+ " :type scale: float\n");
static PyObject *bpygpu_matrix_scale_uniform(PyObject *UNUSED(self), PyObject *value)
{
- float scalar;
- if ((scalar = PyFloat_AsDouble(value)) == -1.0f && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "expected a number, not %.200s",
- Py_TYPE(value)->tp_name);
- return NULL;
- }
- GPU_matrix_scale_1f(scalar);
- Py_RETURN_NONE;
+ float scalar;
+ if ((scalar = PyFloat_AsDouble(value)) == -1.0f && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError, "expected a number, not %.200s", Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+ GPU_matrix_scale_1f(scalar);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_translate_doc,
-".. function:: translate(offset)\n"
-"\n"
-" Scale the current stack matrix.\n"
-"\n"
-" :param offset: Translate the current stack matrix.\n"
-" :type offset: sequence of 2 or 3 floats\n"
-);
+ ".. function:: translate(offset)\n"
+ "\n"
+ " Scale the current stack matrix.\n"
+ "\n"
+ " :param offset: Translate the current stack matrix.\n"
+ " :type offset: sequence of 2 or 3 floats\n");
static PyObject *bpygpu_matrix_translate(PyObject *UNUSED(self), PyObject *value)
{
- float offset[3];
- int len;
- if ((len = mathutils_array_parse(offset, 2, 3, value, "gpu.matrix.translate(): invalid vector arg")) == -1) {
- return NULL;
- }
- if (len == 2) {
- GPU_matrix_translate_2fv(offset);
- }
- else {
- GPU_matrix_translate_3fv(offset);
- }
- Py_RETURN_NONE;
+ float offset[3];
+ int len;
+ if ((len = mathutils_array_parse(
+ offset, 2, 3, value, "gpu.matrix.translate(): invalid vector arg")) == -1) {
+ return NULL;
+ }
+ if (len == 2) {
+ GPU_matrix_translate_2fv(offset);
+ }
+ else {
+ GPU_matrix_translate_3fv(offset);
+ }
+ Py_RETURN_NONE;
}
/** \} */
@@ -371,61 +363,57 @@ static PyObject *bpygpu_matrix_translate(PyObject *UNUSED(self), PyObject *value
* \{ */
PyDoc_STRVAR(bpygpu_matrix_reset_doc,
-".. function:: reset()\n"
-"\n"
-" Empty stack and set to identity.\n"
-);
+ ".. function:: reset()\n"
+ "\n"
+ " Empty stack and set to identity.\n");
static PyObject *bpygpu_matrix_reset(PyObject *UNUSED(self))
{
- GPU_matrix_reset();
- Py_RETURN_NONE;
+ GPU_matrix_reset();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_load_identity_doc,
-".. function:: load_identity()\n"
-"\n"
-" Empty stack and set to identity.\n"
-);
+ ".. function:: load_identity()\n"
+ "\n"
+ " Empty stack and set to identity.\n");
static PyObject *bpygpu_matrix_load_identity(PyObject *UNUSED(self))
{
- GPU_matrix_identity_set();
- Py_RETURN_NONE;
+ GPU_matrix_identity_set();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_load_matrix_doc,
-".. function:: load_matrix(matrix)\n"
-"\n"
-" Load a matrix into the stack.\n"
-"\n"
-" :param matrix: A 4x4 matrix.\n"
-" :type matrix: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: load_matrix(matrix)\n"
+ "\n"
+ " Load a matrix into the stack.\n"
+ "\n"
+ " :param matrix: A 4x4 matrix.\n"
+ " :type matrix: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_load_matrix(PyObject *UNUSED(self), PyObject *value)
{
- MatrixObject *pymat;
- if (!Matrix_Parse4x4(value, &pymat)) {
- return NULL;
- }
- GPU_matrix_set(pymat->matrix);
- Py_RETURN_NONE;
+ MatrixObject *pymat;
+ if (!Matrix_Parse4x4(value, &pymat)) {
+ return NULL;
+ }
+ GPU_matrix_set(pymat->matrix);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_matrix_load_projection_matrix_doc,
-".. function:: load_projection_matrix(matrix)\n"
-"\n"
-" Load a projection matrix into the stack.\n"
-"\n"
-" :param matrix: A 4x4 matrix.\n"
-" :type matrix: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: load_projection_matrix(matrix)\n"
+ "\n"
+ " Load a projection matrix into the stack.\n"
+ "\n"
+ " :param matrix: A 4x4 matrix.\n"
+ " :type matrix: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_load_projection_matrix(PyObject *UNUSED(self), PyObject *value)
{
- MatrixObject *pymat;
- if (!Matrix_Parse4x4(value, &pymat)) {
- return NULL;
- }
- GPU_matrix_projection_set(pymat->matrix);
- Py_RETURN_NONE;
+ MatrixObject *pymat;
+ if (!Matrix_Parse4x4(value, &pymat)) {
+ return NULL;
+ }
+ GPU_matrix_projection_set(pymat->matrix);
+ Py_RETURN_NONE;
}
/** \} */
@@ -435,49 +423,45 @@ static PyObject *bpygpu_matrix_load_projection_matrix(PyObject *UNUSED(self), Py
* \{ */
PyDoc_STRVAR(bpygpu_matrix_get_projection_matrix_doc,
-".. function:: get_projection_matrix()\n"
-"\n"
-" Return a copy of the projection matrix.\n"
-"\n"
-" :return: A 4x4 projection matrix.\n"
-" :rtype: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: get_projection_matrix()\n"
+ "\n"
+ " Return a copy of the projection matrix.\n"
+ "\n"
+ " :return: A 4x4 projection matrix.\n"
+ " :rtype: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_get_projection_matrix(PyObject *UNUSED(self))
{
- float matrix[4][4];
- GPU_matrix_projection_get(matrix);
- return Matrix_CreatePyObject(&matrix[0][0], 4, 4, NULL);
+ float matrix[4][4];
+ GPU_matrix_projection_get(matrix);
+ return Matrix_CreatePyObject(&matrix[0][0], 4, 4, NULL);
}
-
PyDoc_STRVAR(bpygpu_matrix_get_model_view_matrix_doc,
-".. function:: get_model_view_matrix()\n"
-"\n"
-" Return a copy of the model-view matrix.\n"
-"\n"
-" :return: A 4x4 view matrix.\n"
-" :rtype: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: get_model_view_matrix()\n"
+ "\n"
+ " Return a copy of the model-view matrix.\n"
+ "\n"
+ " :return: A 4x4 view matrix.\n"
+ " :rtype: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_get_model_view_matrix(PyObject *UNUSED(self))
{
- float matrix[4][4];
- GPU_matrix_model_view_get(matrix);
- return Matrix_CreatePyObject(&matrix[0][0], 4, 4, NULL);
+ float matrix[4][4];
+ GPU_matrix_model_view_get(matrix);
+ return Matrix_CreatePyObject(&matrix[0][0], 4, 4, NULL);
}
PyDoc_STRVAR(bpygpu_matrix_get_normal_matrix_doc,
-".. function:: get_normal_matrix()\n"
-"\n"
-" Return a copy of the normal matrix.\n"
-"\n"
-" :return: A 3x3 normal matrix.\n"
-" :rtype: :class:`mathutils.Matrix`\n"
-);
+ ".. function:: get_normal_matrix()\n"
+ "\n"
+ " Return a copy of the normal matrix.\n"
+ "\n"
+ " :return: A 3x3 normal matrix.\n"
+ " :rtype: :class:`mathutils.Matrix`\n");
static PyObject *bpygpu_matrix_get_normal_matrix(PyObject *UNUSED(self))
{
- float matrix[3][3];
- GPU_matrix_normal_get(matrix);
- return Matrix_CreatePyObject(&matrix[0][0], 3, 3, NULL);
+ float matrix[3][3];
+ GPU_matrix_normal_get(matrix);
+ return Matrix_CreatePyObject(&matrix[0][0], 3, 3, NULL);
}
/** \} */
@@ -487,85 +471,96 @@ static PyObject *bpygpu_matrix_get_normal_matrix(PyObject *UNUSED(self))
* \{ */
static struct PyMethodDef bpygpu_matrix_methods[] = {
- /* Manage Stack */
- {"push", (PyCFunction)bpygpu_matrix_push,
- METH_NOARGS, bpygpu_matrix_push_doc},
- {"pop", (PyCFunction)bpygpu_matrix_pop,
- METH_NOARGS, bpygpu_matrix_pop_doc},
-
- {"push_projection", (PyCFunction)bpygpu_matrix_push_projection,
- METH_NOARGS, bpygpu_matrix_push_projection_doc},
- {"pop_projection", (PyCFunction)bpygpu_matrix_pop_projection,
- METH_NOARGS, bpygpu_matrix_pop_projection_doc},
-
- /* Stack (Context Manager) */
- {"push_pop", (PyCFunction)bpygpu_matrix_push_pop,
- METH_NOARGS, bpygpu_matrix_push_pop_doc},
- {"push_pop_projection", (PyCFunction)bpygpu_matrix_push_pop_projection,
- METH_NOARGS, bpygpu_matrix_push_pop_projection_doc},
-
- /* Manipulate State */
- {"multiply_matrix", (PyCFunction)bpygpu_matrix_multiply_matrix,
- METH_O, bpygpu_matrix_multiply_matrix_doc},
- {"scale", (PyCFunction)bpygpu_matrix_scale,
- METH_O, bpygpu_matrix_scale_doc},
- {"scale_uniform", (PyCFunction)bpygpu_matrix_scale_uniform,
- METH_O, bpygpu_matrix_scale_uniform_doc},
- {"translate", (PyCFunction)bpygpu_matrix_translate,
- METH_O, bpygpu_matrix_translate_doc},
-
- /* TODO */
+ /* Manage Stack */
+ {"push", (PyCFunction)bpygpu_matrix_push, METH_NOARGS, bpygpu_matrix_push_doc},
+ {"pop", (PyCFunction)bpygpu_matrix_pop, METH_NOARGS, bpygpu_matrix_pop_doc},
+
+ {"push_projection",
+ (PyCFunction)bpygpu_matrix_push_projection,
+ METH_NOARGS,
+ bpygpu_matrix_push_projection_doc},
+ {"pop_projection",
+ (PyCFunction)bpygpu_matrix_pop_projection,
+ METH_NOARGS,
+ bpygpu_matrix_pop_projection_doc},
+
+ /* Stack (Context Manager) */
+ {"push_pop", (PyCFunction)bpygpu_matrix_push_pop, METH_NOARGS, bpygpu_matrix_push_pop_doc},
+ {"push_pop_projection",
+ (PyCFunction)bpygpu_matrix_push_pop_projection,
+ METH_NOARGS,
+ bpygpu_matrix_push_pop_projection_doc},
+
+ /* Manipulate State */
+ {"multiply_matrix",
+ (PyCFunction)bpygpu_matrix_multiply_matrix,
+ METH_O,
+ bpygpu_matrix_multiply_matrix_doc},
+ {"scale", (PyCFunction)bpygpu_matrix_scale, METH_O, bpygpu_matrix_scale_doc},
+ {"scale_uniform",
+ (PyCFunction)bpygpu_matrix_scale_uniform,
+ METH_O,
+ bpygpu_matrix_scale_uniform_doc},
+ {"translate", (PyCFunction)bpygpu_matrix_translate, METH_O, bpygpu_matrix_translate_doc},
+
+/* TODO */
#if 0
- {"rotate", (PyCFunction)bpygpu_matrix_rotate,
- METH_O, bpygpu_matrix_rotate_doc},
- {"rotate_axis", (PyCFunction)bpygpu_matrix_rotate_axis,
- METH_O, bpygpu_matrix_rotate_axis_doc},
- {"look_at", (PyCFunction)bpygpu_matrix_look_at,
- METH_O, bpygpu_matrix_look_at_doc},
+ {"rotate", (PyCFunction)bpygpu_matrix_rotate,
+ METH_O, bpygpu_matrix_rotate_doc},
+ {"rotate_axis", (PyCFunction)bpygpu_matrix_rotate_axis,
+ METH_O, bpygpu_matrix_rotate_axis_doc},
+ {"look_at", (PyCFunction)bpygpu_matrix_look_at,
+ METH_O, bpygpu_matrix_look_at_doc},
#endif
- /* Write State */
- {"reset", (PyCFunction)bpygpu_matrix_reset,
- METH_NOARGS, bpygpu_matrix_reset_doc},
- {"load_identity", (PyCFunction)bpygpu_matrix_load_identity,
- METH_NOARGS, bpygpu_matrix_load_identity_doc},
- {"load_matrix", (PyCFunction)bpygpu_matrix_load_matrix,
- METH_O, bpygpu_matrix_load_matrix_doc},
- {"load_projection_matrix", (PyCFunction)bpygpu_matrix_load_projection_matrix,
- METH_O, bpygpu_matrix_load_projection_matrix_doc},
-
- /* Read State */
- {"get_projection_matrix", (PyCFunction)bpygpu_matrix_get_projection_matrix,
- METH_NOARGS, bpygpu_matrix_get_projection_matrix_doc},
- {"get_model_view_matrix", (PyCFunction)bpygpu_matrix_get_model_view_matrix,
- METH_NOARGS, bpygpu_matrix_get_model_view_matrix_doc},
- {"get_normal_matrix", (PyCFunction)bpygpu_matrix_get_normal_matrix,
- METH_NOARGS, bpygpu_matrix_get_normal_matrix_doc},
-
- {NULL, NULL, 0, NULL},
+ /* Write State */
+ {"reset", (PyCFunction)bpygpu_matrix_reset, METH_NOARGS, bpygpu_matrix_reset_doc},
+ {"load_identity",
+ (PyCFunction)bpygpu_matrix_load_identity,
+ METH_NOARGS,
+ bpygpu_matrix_load_identity_doc},
+ {"load_matrix", (PyCFunction)bpygpu_matrix_load_matrix, METH_O, bpygpu_matrix_load_matrix_doc},
+ {"load_projection_matrix",
+ (PyCFunction)bpygpu_matrix_load_projection_matrix,
+ METH_O,
+ bpygpu_matrix_load_projection_matrix_doc},
+
+ /* Read State */
+ {"get_projection_matrix",
+ (PyCFunction)bpygpu_matrix_get_projection_matrix,
+ METH_NOARGS,
+ bpygpu_matrix_get_projection_matrix_doc},
+ {"get_model_view_matrix",
+ (PyCFunction)bpygpu_matrix_get_model_view_matrix,
+ METH_NOARGS,
+ bpygpu_matrix_get_model_view_matrix_doc},
+ {"get_normal_matrix",
+ (PyCFunction)bpygpu_matrix_get_normal_matrix,
+ METH_NOARGS,
+ bpygpu_matrix_get_normal_matrix_doc},
+
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(bpygpu_matrix_doc,
-"This module provides access to the matrix stack."
-);
+PyDoc_STRVAR(bpygpu_matrix_doc, "This module provides access to the matrix stack.");
static PyModuleDef BPyGPU_matrix_module_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "gpu.matrix",
- .m_doc = bpygpu_matrix_doc,
- .m_methods = bpygpu_matrix_methods,
+ PyModuleDef_HEAD_INIT,
+ .m_name = "gpu.matrix",
+ .m_doc = bpygpu_matrix_doc,
+ .m_methods = bpygpu_matrix_methods,
};
PyObject *BPyInit_gpu_matrix(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPyGPU_matrix_module_def);
+ submodule = PyModule_Create(&BPyGPU_matrix_module_def);
- if (PyType_Ready(&BPyGPU_matrix_stack_context_Type) < 0) {
- return NULL;
- }
+ if (PyType_Ready(&BPyGPU_matrix_stack_context_Type) < 0) {
+ return NULL;
+ }
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_matrix.h b/source/blender/python/gpu/gpu_py_matrix.h
index d17bce6a7d3..cf187dee002 100644
--- a/source/blender/python/gpu/gpu_py_matrix.h
+++ b/source/blender/python/gpu/gpu_py_matrix.h
@@ -23,4 +23,4 @@
PyObject *BPyInit_gpu_matrix(void);
-#endif /* __GPU_PY_MATRIX_H__ */
+#endif /* __GPU_PY_MATRIX_H__ */
diff --git a/source/blender/python/gpu/gpu_py_offscreen.c b/source/blender/python/gpu/gpu_py_offscreen.c
index cd9e162b1aa..5ea747b5cdc 100644
--- a/source/blender/python/gpu/gpu_py_offscreen.c
+++ b/source/blender/python/gpu/gpu_py_offscreen.c
@@ -51,316 +51,331 @@
#include "gpu_py_api.h"
#include "gpu_py_offscreen.h" /* own include */
-
/* -------------------------------------------------------------------- */
/** \name GPUOffScreen Common Utilities
* \{ */
static int bpygpu_offscreen_valid_check(BPyGPUOffScreen *bpygpu_ofs)
{
- if (UNLIKELY(bpygpu_ofs->ofs == NULL)) {
- PyErr_SetString(PyExc_ReferenceError, "GPU offscreen was freed, no further access is valid");
- return -1;
- }
- return 0;
+ if (UNLIKELY(bpygpu_ofs->ofs == NULL)) {
+ PyErr_SetString(PyExc_ReferenceError, "GPU offscreen was freed, no further access is valid");
+ return -1;
+ }
+ return 0;
}
-#define BPY_GPU_OFFSCREEN_CHECK_OBJ(bpygpu) { \
- if (UNLIKELY(bpygpu_offscreen_valid_check(bpygpu) == -1)) { \
- return NULL; \
- } \
-} ((void)0)
+#define BPY_GPU_OFFSCREEN_CHECK_OBJ(bpygpu) \
+ { \
+ if (UNLIKELY(bpygpu_offscreen_valid_check(bpygpu) == -1)) { \
+ return NULL; \
+ } \
+ } \
+ ((void)0)
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name GPUOffscreen Type
* \{ */
-
static PyObject *bpygpu_offscreen_new(PyTypeObject *UNUSED(self), PyObject *args, PyObject *kwds)
{
- BPYGPU_IS_INIT_OR_ERROR_OBJ;
-
- GPUOffScreen *ofs;
- int width, height, samples = 0;
- char err_out[256];
-
- static const char *_keywords[] = {"width", "height", "samples", NULL};
- static _PyArg_Parser _parser = {"ii|i:GPUOffScreen.__new__", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &width, &height, &samples))
- {
- return NULL;
- }
-
- ofs = GPU_offscreen_create(width, height, samples, true, false, err_out);
-
- if (ofs == NULL) {
- PyErr_Format(PyExc_RuntimeError,
- "gpu.offscreen.new(...) failed with '%s'",
- err_out[0] ? err_out : "unknown error");
- return NULL;
- }
-
- return BPyGPUOffScreen_CreatePyObject(ofs);
+ BPYGPU_IS_INIT_OR_ERROR_OBJ;
+
+ GPUOffScreen *ofs;
+ int width, height, samples = 0;
+ char err_out[256];
+
+ static const char *_keywords[] = {"width", "height", "samples", NULL};
+ static _PyArg_Parser _parser = {"ii|i:GPUOffScreen.__new__", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, &width, &height, &samples)) {
+ return NULL;
+ }
+
+ ofs = GPU_offscreen_create(width, height, samples, true, false, err_out);
+
+ if (ofs == NULL) {
+ PyErr_Format(PyExc_RuntimeError,
+ "gpu.offscreen.new(...) failed with '%s'",
+ err_out[0] ? err_out : "unknown error");
+ return NULL;
+ }
+
+ return BPyGPUOffScreen_CreatePyObject(ofs);
}
PyDoc_STRVAR(bpygpu_offscreen_width_doc, "Width of the texture.\n\n:type: `int`");
static PyObject *bpygpu_offscreen_width_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- return PyLong_FromLong(GPU_offscreen_width(self->ofs));
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ return PyLong_FromLong(GPU_offscreen_width(self->ofs));
}
PyDoc_STRVAR(bpygpu_offscreen_height_doc, "Height of the texture.\n\n:type: `int`");
static PyObject *bpygpu_offscreen_height_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- return PyLong_FromLong(GPU_offscreen_height(self->ofs));
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ return PyLong_FromLong(GPU_offscreen_height(self->ofs));
}
-PyDoc_STRVAR(bpygpu_offscreen_color_texture_doc, "OpenGL bindcode for the color texture.\n\n:type: `int`");
+PyDoc_STRVAR(bpygpu_offscreen_color_texture_doc,
+ "OpenGL bindcode for the color texture.\n\n:type: `int`");
static PyObject *bpygpu_offscreen_color_texture_get(BPyGPUOffScreen *self, void *UNUSED(type))
{
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- GPUTexture *texture = GPU_offscreen_color_texture(self->ofs);
- return PyLong_FromLong(GPU_texture_opengl_bindcode(texture));
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ GPUTexture *texture = GPU_offscreen_color_texture(self->ofs);
+ return PyLong_FromLong(GPU_texture_opengl_bindcode(texture));
}
-PyDoc_STRVAR(bpygpu_offscreen_bind_doc,
-".. method:: bind(save=True)\n"
-"\n"
-" Bind the offscreen object.\n"
-" To make sure that the offscreen gets unbind whether an exception occurs or not, pack it into a `with` statement.\n"
-"\n"
-" :arg save: Save the current OpenGL state, so that it can be restored when unbinding.\n"
-" :type save: `bool`\n"
-);
+PyDoc_STRVAR(
+ bpygpu_offscreen_bind_doc,
+ ".. method:: bind(save=True)\n"
+ "\n"
+ " Bind the offscreen object.\n"
+ " To make sure that the offscreen gets unbind whether an exception occurs or not, pack it "
+ "into a `with` statement.\n"
+ "\n"
+ " :arg save: Save the current OpenGL state, so that it can be restored when unbinding.\n"
+ " :type save: `bool`\n");
static PyObject *bpygpu_offscreen_bind(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
{
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- bool save = true;
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ bool save = true;
- static const char *_keywords[] = {"save", NULL};
- static _PyArg_Parser _parser = {"|O&:bind", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- PyC_ParseBool, &save))
- {
- return NULL;
- }
+ static const char *_keywords[] = {"save", NULL};
+ static _PyArg_Parser _parser = {"|O&:bind", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, PyC_ParseBool, &save)) {
+ return NULL;
+ }
- GPU_offscreen_bind(self->ofs, save);
+ GPU_offscreen_bind(self->ofs, save);
- self->is_saved = save;
- Py_INCREF(self);
+ self->is_saved = save;
+ Py_INCREF(self);
- return (PyObject *)self;
+ return (PyObject *)self;
}
PyDoc_STRVAR(bpygpu_offscreen_unbind_doc,
-".. method:: unbind(restore=True)\n"
-"\n"
-" Unbind the offscreen object.\n"
-"\n"
-" :arg restore: Restore the OpenGL state, can only be used when the state has been saved before.\n"
-" :type restore: `bool`\n"
-);
+ ".. method:: unbind(restore=True)\n"
+ "\n"
+ " Unbind the offscreen object.\n"
+ "\n"
+ " :arg restore: Restore the OpenGL state, can only be used when the state has been "
+ "saved before.\n"
+ " :type restore: `bool`\n");
static PyObject *bpygpu_offscreen_unbind(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
{
- bool restore = true;
+ bool restore = true;
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- static const char *_keywords[] = {"restore", NULL};
- static _PyArg_Parser _parser = {"|O&:unbind", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- PyC_ParseBool, &restore))
- {
- return NULL;
- }
+ static const char *_keywords[] = {"restore", NULL};
+ static _PyArg_Parser _parser = {"|O&:unbind", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, PyC_ParseBool, &restore)) {
+ return NULL;
+ }
- GPU_offscreen_unbind(self->ofs, restore);
- Py_RETURN_NONE;
+ GPU_offscreen_unbind(self->ofs, restore);
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpygpu_offscreen_draw_view3d_doc,
-".. method:: draw_view3d(scene, view3d, region, view_matrix, projection_matrix)\n"
-"\n"
-" Draw the 3d viewport in the offscreen object.\n"
-"\n"
-" :arg scene: Scene to draw.\n"
-" :type scene: :class:`bpy.types.Scene`\n"
-" :arg view_layer: View layer to draw.\n"
-" :type view_layer: :class:`bpy.types.ViewLayer`\n"
-" :arg view3d: 3D View to get the drawing settings from.\n"
-" :type view3d: :class:`bpy.types.SpaceView3D`\n"
-" :arg region: Region of the 3D View (required as temporary draw target).\n"
-" :type region: :class:`bpy.types.Region`\n"
-" :arg view_matrix: View Matrix (e.g. ``camera.matrix_world.inverted()``).\n"
-" :type view_matrix: :class:`mathutils.Matrix`\n"
-" :arg projection_matrix: Projection Matrix (e.g. ``camera.calc_matrix_camera(...)``).\n"
-" :type projection_matrix: :class:`mathutils.Matrix`\n"
-);
-static PyObject *bpygpu_offscreen_draw_view3d(BPyGPUOffScreen *self, PyObject *args, PyObject *kwds)
+PyDoc_STRVAR(
+ bpygpu_offscreen_draw_view3d_doc,
+ ".. method:: draw_view3d(scene, view3d, region, view_matrix, projection_matrix)\n"
+ "\n"
+ " Draw the 3d viewport in the offscreen object.\n"
+ "\n"
+ " :arg scene: Scene to draw.\n"
+ " :type scene: :class:`bpy.types.Scene`\n"
+ " :arg view_layer: View layer to draw.\n"
+ " :type view_layer: :class:`bpy.types.ViewLayer`\n"
+ " :arg view3d: 3D View to get the drawing settings from.\n"
+ " :type view3d: :class:`bpy.types.SpaceView3D`\n"
+ " :arg region: Region of the 3D View (required as temporary draw target).\n"
+ " :type region: :class:`bpy.types.Region`\n"
+ " :arg view_matrix: View Matrix (e.g. ``camera.matrix_world.inverted()``).\n"
+ " :type view_matrix: :class:`mathutils.Matrix`\n"
+ " :arg projection_matrix: Projection Matrix (e.g. ``camera.calc_matrix_camera(...)``).\n"
+ " :type projection_matrix: :class:`mathutils.Matrix`\n");
+static PyObject *bpygpu_offscreen_draw_view3d(BPyGPUOffScreen *self,
+ PyObject *args,
+ PyObject *kwds)
{
- MatrixObject *py_mat_view, *py_mat_projection;
- PyObject *py_scene, *py_view_layer, *py_region, *py_view3d;
-
- struct Depsgraph *depsgraph;
- struct Scene *scene;
- struct ViewLayer *view_layer;
- View3D *v3d;
- ARegion *ar;
- struct RV3DMatrixStore *rv3d_mats;
-
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
-
- static const char *_keywords[] = {
- "scene", "view_layer", "view3d", "region",
- "view_matrix", "projection_matrix", NULL};
-
- static _PyArg_Parser _parser = {"OOOOO&O&:draw_view3d", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &py_scene, &py_view_layer, &py_view3d, &py_region,
- Matrix_Parse4x4, &py_mat_view,
- Matrix_Parse4x4, &py_mat_projection) ||
- (!(scene = PyC_RNA_AsPointer(py_scene, "Scene")) ||
- !(view_layer = PyC_RNA_AsPointer(py_view_layer, "ViewLayer")) ||
- !(v3d = PyC_RNA_AsPointer(py_view3d, "SpaceView3D")) ||
- !(ar = PyC_RNA_AsPointer(py_region, "Region"))))
- {
- return NULL;
- }
-
- BLI_assert(BKE_id_is_in_global_main(&scene->id));
-
- depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
-
- rv3d_mats = ED_view3d_mats_rv3d_backup(ar->regiondata);
-
- GPU_offscreen_bind(self->ofs, true);
-
- ED_view3d_draw_offscreen(depsgraph,
- scene,
- v3d->shading.type,
- v3d,
- ar,
- GPU_offscreen_width(self->ofs),
- GPU_offscreen_height(self->ofs),
- (float(*)[4])py_mat_view->matrix,
- (float(*)[4])py_mat_projection->matrix,
- false,
- true,
- "",
- NULL,
- true,
- self->ofs,
- NULL);
-
- GPU_offscreen_unbind(self->ofs, true);
-
- ED_view3d_mats_rv3d_restore(ar->regiondata, rv3d_mats);
- MEM_freeN(rv3d_mats);
-
- Py_RETURN_NONE;
+ MatrixObject *py_mat_view, *py_mat_projection;
+ PyObject *py_scene, *py_view_layer, *py_region, *py_view3d;
+
+ struct Depsgraph *depsgraph;
+ struct Scene *scene;
+ struct ViewLayer *view_layer;
+ View3D *v3d;
+ ARegion *ar;
+ struct RV3DMatrixStore *rv3d_mats;
+
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+
+ static const char *_keywords[] = {
+ "scene", "view_layer", "view3d", "region", "view_matrix", "projection_matrix", NULL};
+
+ static _PyArg_Parser _parser = {"OOOOO&O&:draw_view3d", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kwds,
+ &_parser,
+ &py_scene,
+ &py_view_layer,
+ &py_view3d,
+ &py_region,
+ Matrix_Parse4x4,
+ &py_mat_view,
+ Matrix_Parse4x4,
+ &py_mat_projection) ||
+ (!(scene = PyC_RNA_AsPointer(py_scene, "Scene")) ||
+ !(view_layer = PyC_RNA_AsPointer(py_view_layer, "ViewLayer")) ||
+ !(v3d = PyC_RNA_AsPointer(py_view3d, "SpaceView3D")) ||
+ !(ar = PyC_RNA_AsPointer(py_region, "Region")))) {
+ return NULL;
+ }
+
+ BLI_assert(BKE_id_is_in_global_main(&scene->id));
+
+ depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true);
+
+ rv3d_mats = ED_view3d_mats_rv3d_backup(ar->regiondata);
+
+ GPU_offscreen_bind(self->ofs, true);
+
+ ED_view3d_draw_offscreen(depsgraph,
+ scene,
+ v3d->shading.type,
+ v3d,
+ ar,
+ GPU_offscreen_width(self->ofs),
+ GPU_offscreen_height(self->ofs),
+ (float(*)[4])py_mat_view->matrix,
+ (float(*)[4])py_mat_projection->matrix,
+ false,
+ true,
+ "",
+ NULL,
+ true,
+ self->ofs,
+ NULL);
+
+ GPU_offscreen_unbind(self->ofs, true);
+
+ ED_view3d_mats_rv3d_restore(ar->regiondata, rv3d_mats);
+ MEM_freeN(rv3d_mats);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_offscreen_free_doc,
-".. method:: free()\n"
-"\n"
-" Free the offscreen object.\n"
-" The framebuffer, texture and render objects will no longer be accessible.\n"
-);
+ ".. method:: free()\n"
+ "\n"
+ " Free the offscreen object.\n"
+ " The framebuffer, texture and render objects will no longer be accessible.\n");
static PyObject *bpygpu_offscreen_free(BPyGPUOffScreen *self)
{
- BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
+ BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
- GPU_offscreen_free(self->ofs);
- self->ofs = NULL;
- Py_RETURN_NONE;
+ GPU_offscreen_free(self->ofs);
+ self->ofs = NULL;
+ Py_RETURN_NONE;
}
static PyObject *bpygpu_offscreen_bind_context_enter(BPyGPUOffScreen *UNUSED(self))
{
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *bpygpu_offscreen_bind_context_exit(BPyGPUOffScreen *self, PyObject *UNUSED(args))
{
- GPU_offscreen_unbind(self->ofs, self->is_saved);
- Py_RETURN_NONE;
+ GPU_offscreen_unbind(self->ofs, self->is_saved);
+ Py_RETURN_NONE;
}
static void BPyGPUOffScreen__tp_dealloc(BPyGPUOffScreen *self)
{
- if (self->ofs) {
- GPU_offscreen_free(self->ofs);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (self->ofs) {
+ GPU_offscreen_free(self->ofs);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyGetSetDef bpygpu_offscreen_getseters[] = {
- {(char *)"color_texture", (getter)bpygpu_offscreen_color_texture_get, (setter)NULL, bpygpu_offscreen_color_texture_doc, NULL},
- {(char *)"width", (getter)bpygpu_offscreen_width_get, (setter)NULL, bpygpu_offscreen_width_doc, NULL},
- {(char *)"height", (getter)bpygpu_offscreen_height_get, (setter)NULL, bpygpu_offscreen_height_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"color_texture",
+ (getter)bpygpu_offscreen_color_texture_get,
+ (setter)NULL,
+ bpygpu_offscreen_color_texture_doc,
+ NULL},
+ {(char *)"width",
+ (getter)bpygpu_offscreen_width_get,
+ (setter)NULL,
+ bpygpu_offscreen_width_doc,
+ NULL},
+ {(char *)"height",
+ (getter)bpygpu_offscreen_height_get,
+ (setter)NULL,
+ bpygpu_offscreen_height_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static struct PyMethodDef bpygpu_offscreen_methods[] = {
- {"bind", (PyCFunction)bpygpu_offscreen_bind, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_bind_doc},
- {"unbind", (PyCFunction)bpygpu_offscreen_unbind, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_unbind_doc},
- {"draw_view3d", (PyCFunction)bpygpu_offscreen_draw_view3d, METH_VARARGS | METH_KEYWORDS, bpygpu_offscreen_draw_view3d_doc},
- {"free", (PyCFunction)bpygpu_offscreen_free, METH_NOARGS, bpygpu_offscreen_free_doc},
- {"__enter__", (PyCFunction)bpygpu_offscreen_bind_context_enter, METH_NOARGS},
- {"__exit__", (PyCFunction)bpygpu_offscreen_bind_context_exit, METH_VARARGS},
- {NULL, NULL, 0, NULL},
+ {"bind",
+ (PyCFunction)bpygpu_offscreen_bind,
+ METH_VARARGS | METH_KEYWORDS,
+ bpygpu_offscreen_bind_doc},
+ {"unbind",
+ (PyCFunction)bpygpu_offscreen_unbind,
+ METH_VARARGS | METH_KEYWORDS,
+ bpygpu_offscreen_unbind_doc},
+ {"draw_view3d",
+ (PyCFunction)bpygpu_offscreen_draw_view3d,
+ METH_VARARGS | METH_KEYWORDS,
+ bpygpu_offscreen_draw_view3d_doc},
+ {"free", (PyCFunction)bpygpu_offscreen_free, METH_NOARGS, bpygpu_offscreen_free_doc},
+ {"__enter__", (PyCFunction)bpygpu_offscreen_bind_context_enter, METH_NOARGS},
+ {"__exit__", (PyCFunction)bpygpu_offscreen_bind_context_exit, METH_VARARGS},
+ {NULL, NULL, 0, NULL},
};
PyDoc_STRVAR(bpygpu_offscreen_doc,
-".. class:: GPUOffScreen(width, height, samples=0)\n"
-"\n"
-" This object gives access to off screen buffers.\n"
-"\n"
-" :arg width: Horizontal dimension of the buffer.\n"
-" :type width: `int`\n"
-" :arg height: Vertical dimension of the buffer.\n"
-" :type height: `int`\n"
-" :arg samples: OpenGL samples to use for MSAA or zero to disable.\n"
-" :type samples: `int`\n"
-);
+ ".. class:: GPUOffScreen(width, height, samples=0)\n"
+ "\n"
+ " This object gives access to off screen buffers.\n"
+ "\n"
+ " :arg width: Horizontal dimension of the buffer.\n"
+ " :type width: `int`\n"
+ " :arg height: Vertical dimension of the buffer.\n"
+ " :type height: `int`\n"
+ " :arg samples: OpenGL samples to use for MSAA or zero to disable.\n"
+ " :type samples: `int`\n");
PyTypeObject BPyGPUOffScreen_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUOffScreen",
- .tp_basicsize = sizeof(BPyGPUOffScreen),
- .tp_dealloc = (destructor)BPyGPUOffScreen__tp_dealloc,
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_doc = bpygpu_offscreen_doc,
- .tp_methods = bpygpu_offscreen_methods,
- .tp_getset = bpygpu_offscreen_getseters,
- .tp_new = bpygpu_offscreen_new,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUOffScreen",
+ .tp_basicsize = sizeof(BPyGPUOffScreen),
+ .tp_dealloc = (destructor)BPyGPUOffScreen__tp_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = bpygpu_offscreen_doc,
+ .tp_methods = bpygpu_offscreen_methods,
+ .tp_getset = bpygpu_offscreen_getseters,
+ .tp_new = bpygpu_offscreen_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUOffScreen_CreatePyObject(GPUOffScreen *ofs)
{
- BPyGPUOffScreen *self;
+ BPyGPUOffScreen *self;
- self = PyObject_New(BPyGPUOffScreen, &BPyGPUOffScreen_Type);
- self->ofs = ofs;
+ self = PyObject_New(BPyGPUOffScreen, &BPyGPUOffScreen_Type);
+ self->ofs = ofs;
- return (PyObject *)self;
+ return (PyObject *)self;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_offscreen.h b/source/blender/python/gpu/gpu_py_offscreen.h
index c62f1e9051a..61d7bd82abc 100644
--- a/source/blender/python/gpu/gpu_py_offscreen.h
+++ b/source/blender/python/gpu/gpu_py_offscreen.h
@@ -25,12 +25,11 @@
extern PyTypeObject BPyGPUOffScreen_Type;
-#define BPyGPUOffScreen_Check(v) (Py_TYPE(v) == &BPyGPUOffScreen_Type)
+#define BPyGPUOffScreen_Check(v) (Py_TYPE(v) == &BPyGPUOffScreen_Type)
typedef struct BPyGPUOffScreen {
- PyObject_HEAD
- struct GPUOffScreen *ofs;
- bool is_saved;
+ PyObject_HEAD struct GPUOffScreen *ofs;
+ bool is_saved;
} BPyGPUOffScreen;
PyObject *BPyGPUOffScreen_CreatePyObject(struct GPUOffScreen *ofs) ATTR_NONNULL(1);
diff --git a/source/blender/python/gpu/gpu_py_select.c b/source/blender/python/gpu/gpu_py_select.c
index 0744d6b26ba..21832b58015 100644
--- a/source/blender/python/gpu/gpu_py_select.c
+++ b/source/blender/python/gpu/gpu_py_select.c
@@ -41,21 +41,20 @@
* \{ */
PyDoc_STRVAR(bpygpu_select_load_id_doc,
-"load_id(id)\n"
-"\n"
-" Set the selection ID.\n"
-"\n"
-" :param id: Number (32-bit unsigned int).\n"
-" :type select: int\n"
-);
+ "load_id(id)\n"
+ "\n"
+ " Set the selection ID.\n"
+ "\n"
+ " :param id: Number (32-bit unsigned int).\n"
+ " :type select: int\n");
static PyObject *bpygpu_select_load_id(PyObject *UNUSED(self), PyObject *value)
{
- uint id;
- if ((id = PyC_Long_AsU32(value)) == (uint)-1) {
- return NULL;
- }
- GPU_select_load_id(id);
- Py_RETURN_NONE;
+ uint id;
+ if ((id = PyC_Long_AsU32(value)) == (uint)-1) {
+ return NULL;
+ }
+ GPU_select_load_id(id);
+ Py_RETURN_NONE;
}
/** \} */
@@ -64,28 +63,26 @@ static PyObject *bpygpu_select_load_id(PyObject *UNUSED(self), PyObject *value)
* \{ */
static struct PyMethodDef bpygpu_select_methods[] = {
- /* Manage Stack */
- {"load_id", (PyCFunction)bpygpu_select_load_id, METH_O, bpygpu_select_load_id_doc},
- {NULL, NULL, 0, NULL},
+ /* Manage Stack */
+ {"load_id", (PyCFunction)bpygpu_select_load_id, METH_O, bpygpu_select_load_id_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(bpygpu_select_doc,
-"This module provides access to selection."
-);
+PyDoc_STRVAR(bpygpu_select_doc, "This module provides access to selection.");
static PyModuleDef BPyGPU_select_module_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "gpu.select",
- .m_doc = bpygpu_select_doc,
- .m_methods = bpygpu_select_methods,
+ PyModuleDef_HEAD_INIT,
+ .m_name = "gpu.select",
+ .m_doc = bpygpu_select_doc,
+ .m_methods = bpygpu_select_methods,
};
PyObject *BPyInit_gpu_select(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPyGPU_select_module_def);
+ submodule = PyModule_Create(&BPyGPU_select_module_def);
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_select.h b/source/blender/python/gpu/gpu_py_select.h
index 97cc4b8285f..814b6028da1 100644
--- a/source/blender/python/gpu/gpu_py_select.h
+++ b/source/blender/python/gpu/gpu_py_select.h
@@ -23,4 +23,4 @@
PyObject *BPyInit_gpu_select(void);
-#endif /* __GPU_PY_SELECT_H__ */
+#endif /* __GPU_PY_SELECT_H__ */
diff --git a/source/blender/python/gpu/gpu_py_shader.c b/source/blender/python/gpu/gpu_py_shader.c
index 37f4c17a956..0aada94c3c9 100644
--- a/source/blender/python/gpu/gpu_py_shader.c
+++ b/source/blender/python/gpu/gpu_py_shader.c
@@ -36,797 +36,755 @@
#include "gpu_py_shader.h" /* own include */
#include "gpu_py_vertex_format.h"
+/* -------------------------------------------------------------------- */
- /* -------------------------------------------------------------------- */
-
- /** \name Enum Conversion.
+/** \name Enum Conversion.
* \{ */
static int bpygpu_ParseBultinShaderEnum(PyObject *o, void *p)
{
- Py_ssize_t mode_id_len;
- const char *mode_id = _PyUnicode_AsStringAndSize(o, &mode_id_len);
- if (mode_id == NULL) {
- PyErr_Format(PyExc_ValueError,
- "expected a string, got %s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
+ Py_ssize_t mode_id_len;
+ const char *mode_id = _PyUnicode_AsStringAndSize(o, &mode_id_len);
+ if (mode_id == NULL) {
+ PyErr_Format(PyExc_ValueError, "expected a string, got %s", Py_TYPE(o)->tp_name);
+ return 0;
+ }
#define MATCH_ID(id) \
- if (mode_id_len == (Py_ssize_t)strlen(STRINGIFY(id))) { \
- if (STREQ(mode_id, STRINGIFY(id))) { \
- mode = GPU_SHADER_##id; \
- goto success; \
- } \
- } ((void)0)
-
- eGPUBuiltinShader mode;
- MATCH_ID(2D_UNIFORM_COLOR);
- MATCH_ID(2D_FLAT_COLOR);
- MATCH_ID(2D_SMOOTH_COLOR);
- MATCH_ID(2D_IMAGE);
- MATCH_ID(3D_UNIFORM_COLOR);
- MATCH_ID(3D_FLAT_COLOR);
- MATCH_ID(3D_SMOOTH_COLOR);
+ if (mode_id_len == (Py_ssize_t)strlen(STRINGIFY(id))) { \
+ if (STREQ(mode_id, STRINGIFY(id))) { \
+ mode = GPU_SHADER_##id; \
+ goto success; \
+ } \
+ } \
+ ((void)0)
+
+ eGPUBuiltinShader mode;
+ MATCH_ID(2D_UNIFORM_COLOR);
+ MATCH_ID(2D_FLAT_COLOR);
+ MATCH_ID(2D_SMOOTH_COLOR);
+ MATCH_ID(2D_IMAGE);
+ MATCH_ID(3D_UNIFORM_COLOR);
+ MATCH_ID(3D_FLAT_COLOR);
+ MATCH_ID(3D_SMOOTH_COLOR);
#undef MATCH_ID
- PyErr_Format(PyExc_ValueError,
- "unknown type literal: '%s'",
- mode_id);
- return 0;
+ PyErr_Format(PyExc_ValueError, "unknown type literal: '%s'", mode_id);
+ return 0;
success:
- (*(eGPUBuiltinShader *)p) = mode;
- return 1;
+ (*(eGPUBuiltinShader *)p) = mode;
+ return 1;
}
-static int bpygpu_uniform_location_get(GPUShader *shader, const char *name, const char *error_prefix)
+static int bpygpu_uniform_location_get(GPUShader *shader,
+ const char *name,
+ const char *error_prefix)
{
- int uniform = GPU_shader_get_uniform_ensure(shader, name);
+ int uniform = GPU_shader_get_uniform_ensure(shader, name);
- if (uniform == -1) {
- PyErr_Format(PyExc_ValueError, "%s: uniform %.32s %.32s not found", error_prefix, name);
- }
+ if (uniform == -1) {
+ PyErr_Format(PyExc_ValueError, "%s: uniform %.32s %.32s not found", error_prefix, name);
+ }
- return uniform;
+ return uniform;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Shader Type
* \{ */
static PyObject *bpygpu_shader_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- BPYGPU_IS_INIT_OR_ERROR_OBJ;
-
- struct {
- const char *vertexcode;
- const char *fragcode;
- const char *geocode;
- const char *libcode;
- const char *defines;
- } params = {0};
-
- static const char *_keywords[] = {
- "vertexcode", "fragcode", "geocode",
- "libcode", "defines", NULL};
-
- static _PyArg_Parser _parser = {"ss|$sss:GPUShader.__new__", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &params.vertexcode, &params.fragcode, &params.geocode,
- &params.libcode, &params.defines))
- {
- return NULL;
- }
-
- GPUShader *shader = GPU_shader_create(
- params.vertexcode,
- params.fragcode,
- params.geocode,
- params.libcode,
- params.defines,
- NULL);
-
- if (shader == NULL) {
- PyErr_SetString(PyExc_Exception,
- "Shader Compile Error, see console for more details");
- return NULL;
- }
-
- return BPyGPUShader_CreatePyObject(shader, false);
+ BPYGPU_IS_INIT_OR_ERROR_OBJ;
+
+ struct {
+ const char *vertexcode;
+ const char *fragcode;
+ const char *geocode;
+ const char *libcode;
+ const char *defines;
+ } params = {0};
+
+ static const char *_keywords[] = {
+ "vertexcode", "fragcode", "geocode", "libcode", "defines", NULL};
+
+ static _PyArg_Parser _parser = {"ss|$sss:GPUShader.__new__", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kwds,
+ &_parser,
+ &params.vertexcode,
+ &params.fragcode,
+ &params.geocode,
+ &params.libcode,
+ &params.defines)) {
+ return NULL;
+ }
+
+ GPUShader *shader = GPU_shader_create(
+ params.vertexcode, params.fragcode, params.geocode, params.libcode, params.defines, NULL);
+
+ if (shader == NULL) {
+ PyErr_SetString(PyExc_Exception, "Shader Compile Error, see console for more details");
+ return NULL;
+ }
+
+ return BPyGPUShader_CreatePyObject(shader, false);
}
-PyDoc_STRVAR(bpygpu_shader_bind_doc,
-".. method:: bind()\n"
-"\n"
-" Bind the shader object. Required to be able to change uniforms of this shader.\n"
-);
+PyDoc_STRVAR(
+ bpygpu_shader_bind_doc,
+ ".. method:: bind()\n"
+ "\n"
+ " Bind the shader object. Required to be able to change uniforms of this shader.\n");
static PyObject *bpygpu_shader_bind(BPyGPUShader *self)
{
- GPU_shader_bind(self->shader);
- Py_RETURN_NONE;
+ GPU_shader_bind(self->shader);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_uniform_from_name_doc,
-".. method:: uniform_from_name(name)\n"
-"\n"
-" Get uniform location by name.\n"
-"\n"
-" :param name: Name of the uniform variable whose location is to be queried.\n"
-" :type name: `str`\n"
-" :return: Location of the uniform variable.\n"
-" :rtype: `int`\n"
-);
-static PyObject *bpygpu_shader_uniform_from_name(
- BPyGPUShader *self, PyObject *arg)
+ ".. method:: uniform_from_name(name)\n"
+ "\n"
+ " Get uniform location by name.\n"
+ "\n"
+ " :param name: Name of the uniform variable whose location is to be queried.\n"
+ " :type name: `str`\n"
+ " :return: Location of the uniform variable.\n"
+ " :rtype: `int`\n");
+static PyObject *bpygpu_shader_uniform_from_name(BPyGPUShader *self, PyObject *arg)
{
- const char *name = PyUnicode_AsUTF8(arg);
- if (name == NULL) {
- return NULL;
- }
+ const char *name = PyUnicode_AsUTF8(arg);
+ if (name == NULL) {
+ return NULL;
+ }
- int uniform = bpygpu_uniform_location_get(
- self->shader, name, "GPUShader.get_uniform");
+ int uniform = bpygpu_uniform_location_get(self->shader, name, "GPUShader.get_uniform");
- if (uniform == -1) {
- return NULL;
- }
+ if (uniform == -1) {
+ return NULL;
+ }
- return PyLong_FromLong(uniform);
+ return PyLong_FromLong(uniform);
}
-PyDoc_STRVAR(bpygpu_shader_uniform_block_from_name_doc,
-".. method:: uniform_block_from_name(name)\n"
-"\n"
-" Get uniform block location by name.\n"
-"\n"
-" :param name: Name of the uniform block variable whose location is to be queried.\n"
-" :type name: `str`\n"
-" :return: The location of the uniform block variable.\n"
-" :rtype: `int`\n"
-);
-static PyObject *bpygpu_shader_uniform_block_from_name(
- BPyGPUShader *self, PyObject *arg)
+PyDoc_STRVAR(
+ bpygpu_shader_uniform_block_from_name_doc,
+ ".. method:: uniform_block_from_name(name)\n"
+ "\n"
+ " Get uniform block location by name.\n"
+ "\n"
+ " :param name: Name of the uniform block variable whose location is to be queried.\n"
+ " :type name: `str`\n"
+ " :return: The location of the uniform block variable.\n"
+ " :rtype: `int`\n");
+static PyObject *bpygpu_shader_uniform_block_from_name(BPyGPUShader *self, PyObject *arg)
{
- const char *name = PyUnicode_AsUTF8(arg);
- if (name == NULL) {
- return NULL;
- }
+ const char *name = PyUnicode_AsUTF8(arg);
+ if (name == NULL) {
+ return NULL;
+ }
- int uniform = GPU_shader_get_uniform_block(self->shader, name);
+ int uniform = GPU_shader_get_uniform_block(self->shader, name);
- if (uniform == -1) {
- PyErr_Format(PyExc_ValueError,
- "GPUShader.get_uniform_block: uniform %.32s not found", name);
- return NULL;
- }
+ if (uniform == -1) {
+ PyErr_Format(PyExc_ValueError, "GPUShader.get_uniform_block: uniform %.32s not found", name);
+ return NULL;
+ }
- return PyLong_FromLong(uniform);
+ return PyLong_FromLong(uniform);
}
-static bool bpygpu_shader_uniform_vector_imp(
- PyObject *args, int elem_size,
- int *r_location, int *r_length, int *r_count, Py_buffer *r_pybuffer)
+static bool bpygpu_shader_uniform_vector_imp(PyObject *args,
+ int elem_size,
+ int *r_location,
+ int *r_length,
+ int *r_count,
+ Py_buffer *r_pybuffer)
{
- PyObject *buffer;
-
- *r_count = 1;
- if (!PyArg_ParseTuple(
- args, "iOi|i:GPUShader.uniform_vector_*",
- r_location, &buffer, r_length, r_count))
- {
- return false;
- }
-
- if (PyObject_GetBuffer(buffer, r_pybuffer, PyBUF_SIMPLE) == -1) {
- /* PyObject_GetBuffer raise a PyExc_BufferError */
- return false;
- }
-
- if (r_pybuffer->len != (*r_length * *r_count * elem_size)) {
- PyErr_SetString(
- PyExc_BufferError,
- "GPUShader.uniform_vector_*: buffer size does not match.");
- return false;
- }
-
- return true;
+ PyObject *buffer;
+
+ *r_count = 1;
+ if (!PyArg_ParseTuple(
+ args, "iOi|i:GPUShader.uniform_vector_*", r_location, &buffer, r_length, r_count)) {
+ return false;
+ }
+
+ if (PyObject_GetBuffer(buffer, r_pybuffer, PyBUF_SIMPLE) == -1) {
+ /* PyObject_GetBuffer raise a PyExc_BufferError */
+ return false;
+ }
+
+ if (r_pybuffer->len != (*r_length * *r_count * elem_size)) {
+ PyErr_SetString(PyExc_BufferError, "GPUShader.uniform_vector_*: buffer size does not match.");
+ return false;
+ }
+
+ return true;
}
PyDoc_STRVAR(bpygpu_shader_uniform_vector_float_doc,
-".. method:: uniform_vector_float(location, buffer, length, count)\n"
-"\n"
-" Set the buffer to fill the uniform.\n"
-"\n"
-" :param location: Location of the uniform variable to be modified.\n"
-" :type location: int\n"
-" :param buffer: The data that should be set. Can support the buffer protocol.\n"
-" :type buffer: sequence of floats\n"
-" :param length: Size of the uniform data type:\n"
-"\n"
-" - 1: float\n"
-" - 2: vec2 or float[2]\n"
-" - 3: vec3 or float[3]\n"
-" - 4: vec4 or float[4]\n"
-" - 9: mat3\n"
-" - 16: mat4\n"
-"\n"
-" :type length: int\n"
-" :param count: Specifies the number of elements, vector or matrices that are to be modified.\n"
-" :type count: int\n"
-);
-static PyObject *bpygpu_shader_uniform_vector_float(
- BPyGPUShader *self, PyObject *args)
+ ".. method:: uniform_vector_float(location, buffer, length, count)\n"
+ "\n"
+ " Set the buffer to fill the uniform.\n"
+ "\n"
+ " :param location: Location of the uniform variable to be modified.\n"
+ " :type location: int\n"
+ " :param buffer: The data that should be set. Can support the buffer protocol.\n"
+ " :type buffer: sequence of floats\n"
+ " :param length: Size of the uniform data type:\n"
+ "\n"
+ " - 1: float\n"
+ " - 2: vec2 or float[2]\n"
+ " - 3: vec3 or float[3]\n"
+ " - 4: vec4 or float[4]\n"
+ " - 9: mat3\n"
+ " - 16: mat4\n"
+ "\n"
+ " :type length: int\n"
+ " :param count: Specifies the number of elements, vector or matrices that are to "
+ "be modified.\n"
+ " :type count: int\n");
+static PyObject *bpygpu_shader_uniform_vector_float(BPyGPUShader *self, PyObject *args)
{
- int location, length, count;
+ int location, length, count;
- Py_buffer pybuffer;
+ Py_buffer pybuffer;
- if (!bpygpu_shader_uniform_vector_imp(
- args, sizeof(float),
- &location, &length, &count, &pybuffer))
- {
- return NULL;
- }
+ if (!bpygpu_shader_uniform_vector_imp(
+ args, sizeof(float), &location, &length, &count, &pybuffer)) {
+ return NULL;
+ }
- GPU_shader_uniform_vector(
- self->shader, location, length,
- count, pybuffer.buf);
+ GPU_shader_uniform_vector(self->shader, location, length, count, pybuffer.buf);
- PyBuffer_Release(&pybuffer);
+ PyBuffer_Release(&pybuffer);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_uniform_vector_int_doc,
-".. method:: uniform_vector_int(location, buffer, length, count)\n"
-"\n"
-" See GPUShader.uniform_vector_float(...) description.\n"
-);
-static PyObject *bpygpu_shader_uniform_vector_int(
- BPyGPUShader *self, PyObject *args)
+ ".. method:: uniform_vector_int(location, buffer, length, count)\n"
+ "\n"
+ " See GPUShader.uniform_vector_float(...) description.\n");
+static PyObject *bpygpu_shader_uniform_vector_int(BPyGPUShader *self, PyObject *args)
{
- int location, length, count;
+ int location, length, count;
- Py_buffer pybuffer;
+ Py_buffer pybuffer;
- if (!bpygpu_shader_uniform_vector_imp(
- args, sizeof(int),
- &location, &length, &count, &pybuffer))
- {
- return NULL;
- }
+ if (!bpygpu_shader_uniform_vector_imp(
+ args, sizeof(int), &location, &length, &count, &pybuffer)) {
+ return NULL;
+ }
- GPU_shader_uniform_vector_int(
- self->shader, location, length,
- count, pybuffer.buf);
+ GPU_shader_uniform_vector_int(self->shader, location, length, count, pybuffer.buf);
- PyBuffer_Release(&pybuffer);
+ PyBuffer_Release(&pybuffer);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_uniform_bool_doc,
-".. method:: uniform_bool(name, seq)\n"
-"\n"
-" Specify the value of a uniform variable for the current program object.\n"
-"\n"
-" :param name: Name of the uniform variable whose value is to be changed.\n"
-" :type name: str\n"
-" :param seq: Value that will be used to update the specified uniform variable.\n"
-" :type seq: sequence of bools\n"
-);
-static PyObject *bpygpu_shader_uniform_bool(
- BPyGPUShader *self, PyObject *args)
+ ".. method:: uniform_bool(name, seq)\n"
+ "\n"
+ " Specify the value of a uniform variable for the current program object.\n"
+ "\n"
+ " :param name: Name of the uniform variable whose value is to be changed.\n"
+ " :type name: str\n"
+ " :param seq: Value that will be used to update the specified uniform variable.\n"
+ " :type seq: sequence of bools\n");
+static PyObject *bpygpu_shader_uniform_bool(BPyGPUShader *self, PyObject *args)
{
- const char *error_prefix = "GPUShader.uniform_bool";
-
- struct {
- const char *id;
- PyObject *seq;
- } params;
-
- if (!PyArg_ParseTuple(
- args, "sO:GPUShader.uniform_bool",
- &params.id, &params.seq))
- {
- return NULL;
- }
-
- int values[4];
- int length;
- int ret;
- {
- PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
- if (seq_fast == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%s: expected a sequence, got %s",
- error_prefix, Py_TYPE(params.seq)->tp_name);
- ret = -1;
- }
- else {
- length = PySequence_Fast_GET_SIZE(seq_fast);
- if (length == 0 || length > 4) {
- PyErr_Format(PyExc_TypeError,
- "%s: invalid sequence length. expected 1..4, got %d",
- error_prefix, length);
- ret = -1;
- }
- else {
- ret = PyC_AsArray_FAST(
- values, seq_fast, length, &PyLong_Type,
- false, error_prefix);
- }
- Py_DECREF(seq_fast);
- }
- }
- if (ret == -1) {
- return NULL;
- }
-
- const int location = bpygpu_uniform_location_get(
- self->shader, params.id, error_prefix);
-
- if (location == -1) {
- return NULL;
- }
-
- GPU_shader_uniform_vector_int(self->shader, location, length, 1, values);
-
- Py_RETURN_NONE;
+ const char *error_prefix = "GPUShader.uniform_bool";
+
+ struct {
+ const char *id;
+ PyObject *seq;
+ } params;
+
+ if (!PyArg_ParseTuple(args, "sO:GPUShader.uniform_bool", &params.id, &params.seq)) {
+ return NULL;
+ }
+
+ int values[4];
+ int length;
+ int ret;
+ {
+ PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
+ if (seq_fast == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: expected a sequence, got %s",
+ error_prefix,
+ Py_TYPE(params.seq)->tp_name);
+ ret = -1;
+ }
+ else {
+ length = PySequence_Fast_GET_SIZE(seq_fast);
+ if (length == 0 || length > 4) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: invalid sequence length. expected 1..4, got %d",
+ error_prefix,
+ length);
+ ret = -1;
+ }
+ else {
+ ret = PyC_AsArray_FAST(values, seq_fast, length, &PyLong_Type, false, error_prefix);
+ }
+ Py_DECREF(seq_fast);
+ }
+ }
+ if (ret == -1) {
+ return NULL;
+ }
+
+ const int location = bpygpu_uniform_location_get(self->shader, params.id, error_prefix);
+
+ if (location == -1) {
+ return NULL;
+ }
+
+ GPU_shader_uniform_vector_int(self->shader, location, length, 1, values);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_uniform_float_doc,
-".. method:: uniform_float(name, value)\n"
-"\n"
-" Specify the value of a uniform variable for the current program object.\n"
-"\n"
-" :param name: Name of the uniform variable whose value is to be changed.\n"
-" :type name: str\n"
-" :param value: Value that will be used to update the specified uniform variable.\n"
-" :type value: single number or sequence of numbers\n"
-);
-static PyObject *bpygpu_shader_uniform_float(
- BPyGPUShader *self, PyObject *args)
+ ".. method:: uniform_float(name, value)\n"
+ "\n"
+ " Specify the value of a uniform variable for the current program object.\n"
+ "\n"
+ " :param name: Name of the uniform variable whose value is to be changed.\n"
+ " :type name: str\n"
+ " :param value: Value that will be used to update the specified uniform variable.\n"
+ " :type value: single number or sequence of numbers\n");
+static PyObject *bpygpu_shader_uniform_float(BPyGPUShader *self, PyObject *args)
{
- const char *error_prefix = "GPUShader.uniform_float";
-
- struct {
- const char *id;
- PyObject *seq;
- } params;
-
- if (!PyArg_ParseTuple(
- args, "sO:GPUShader.uniform_float",
- &params.id, &params.seq))
- {
- return NULL;
- }
-
- float values[16];
- int length;
-
- if (PyFloat_Check(params.seq)) {
- values[0] = (float)PyFloat_AsDouble(params.seq);
- length = 1;
- }
- else if (PyLong_Check(params.seq)) {
- values[0] = (float)PyLong_AsDouble(params.seq);
- length = 1;
- }
- else if (MatrixObject_Check(params.seq)) {
- MatrixObject *mat = (MatrixObject *)params.seq;
- if (BaseMath_ReadCallback(mat) == -1) {
- return NULL;
- }
- if ((mat->num_row != mat->num_col) || !ELEM(mat->num_row, 3, 4)) {
- PyErr_SetString(PyExc_ValueError,
- "Expected 3x3 or 4x4 matrix");
- return NULL;
- }
- length = mat->num_row * mat->num_col;
- memcpy(values, mat->matrix, sizeof(float) * length);
- }
- else {
- length = mathutils_array_parse(values, 2, 16, params.seq, "");
- if (length == -1) {
- return NULL;
- }
- }
-
- if (!ELEM(length, 1, 2, 3, 4, 9, 16)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected a single float or a sequence of floats of length 1..4, 9 or 16.");
- return NULL;
- }
-
- const int location = bpygpu_uniform_location_get(
- self->shader, params.id, error_prefix);
-
- if (location == -1) {
- return NULL;
- }
-
- GPU_shader_uniform_vector(self->shader, location, length, 1, values);
-
- Py_RETURN_NONE;
+ const char *error_prefix = "GPUShader.uniform_float";
+
+ struct {
+ const char *id;
+ PyObject *seq;
+ } params;
+
+ if (!PyArg_ParseTuple(args, "sO:GPUShader.uniform_float", &params.id, &params.seq)) {
+ return NULL;
+ }
+
+ float values[16];
+ int length;
+
+ if (PyFloat_Check(params.seq)) {
+ values[0] = (float)PyFloat_AsDouble(params.seq);
+ length = 1;
+ }
+ else if (PyLong_Check(params.seq)) {
+ values[0] = (float)PyLong_AsDouble(params.seq);
+ length = 1;
+ }
+ else if (MatrixObject_Check(params.seq)) {
+ MatrixObject *mat = (MatrixObject *)params.seq;
+ if (BaseMath_ReadCallback(mat) == -1) {
+ return NULL;
+ }
+ if ((mat->num_row != mat->num_col) || !ELEM(mat->num_row, 3, 4)) {
+ PyErr_SetString(PyExc_ValueError, "Expected 3x3 or 4x4 matrix");
+ return NULL;
+ }
+ length = mat->num_row * mat->num_col;
+ memcpy(values, mat->matrix, sizeof(float) * length);
+ }
+ else {
+ length = mathutils_array_parse(values, 2, 16, params.seq, "");
+ if (length == -1) {
+ return NULL;
+ }
+ }
+
+ if (!ELEM(length, 1, 2, 3, 4, 9, 16)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected a single float or a sequence of floats of length 1..4, 9 or 16.");
+ return NULL;
+ }
+
+ const int location = bpygpu_uniform_location_get(self->shader, params.id, error_prefix);
+
+ if (location == -1) {
+ return NULL;
+ }
+
+ GPU_shader_uniform_vector(self->shader, location, length, 1, values);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_uniform_int_doc,
-".. method:: uniform_int(name, seq)\n"
-"\n"
-" Specify the value of a uniform variable for the current program object.\n"
-"\n"
-" :param name: name of the uniform variable whose value is to be changed.\n"
-" :type name: str\n"
-" :param seq: Value that will be used to update the specified uniform variable.\n"
-" :type seq: sequence of numbers\n"
-);
-static PyObject *bpygpu_shader_uniform_int(
- BPyGPUShader *self, PyObject *args)
+ ".. method:: uniform_int(name, seq)\n"
+ "\n"
+ " Specify the value of a uniform variable for the current program object.\n"
+ "\n"
+ " :param name: name of the uniform variable whose value is to be changed.\n"
+ " :type name: str\n"
+ " :param seq: Value that will be used to update the specified uniform variable.\n"
+ " :type seq: sequence of numbers\n");
+static PyObject *bpygpu_shader_uniform_int(BPyGPUShader *self, PyObject *args)
{
- const char *error_prefix = "GPUShader.uniform_int";
-
- struct {
- const char *id;
- PyObject *seq;
- } params;
-
- if (!PyArg_ParseTuple(
- args, "sO:GPUShader.uniform_int",
- &params.id, &params.seq))
- {
- return NULL;
- }
-
- int values[4];
- int length;
- int ret;
-
- if (PyLong_Check(params.seq)) {
- values[0] = PyC_Long_AsI32(params.seq);
- length = 1;
- ret = 0;
- }
- else {
- PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
- if (seq_fast == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%s: expected a sequence, got %s",
- error_prefix, Py_TYPE(params.seq)->tp_name);
- ret = -1;
- }
- else {
- length = PySequence_Fast_GET_SIZE(seq_fast);
- if (length == 0 || length > 4) {
- PyErr_Format(PyExc_TypeError,
- "%s: invalid sequence length. expected 1..4, got %d",
- error_prefix, length);
- ret = -1;
- }
- else {
- ret = PyC_AsArray_FAST(
- values, seq_fast, length, &PyLong_Type,
- false, error_prefix);
- }
- Py_DECREF(seq_fast);
- }
- }
- if (ret == -1) {
- return NULL;
- }
-
- const int location = bpygpu_uniform_location_get(
- self->shader, params.id, error_prefix);
-
- if (location == -1) {
- return NULL;
- }
-
- GPU_shader_uniform_vector_int(self->shader, location, length, 1, values);
-
- Py_RETURN_NONE;
+ const char *error_prefix = "GPUShader.uniform_int";
+
+ struct {
+ const char *id;
+ PyObject *seq;
+ } params;
+
+ if (!PyArg_ParseTuple(args, "sO:GPUShader.uniform_int", &params.id, &params.seq)) {
+ return NULL;
+ }
+
+ int values[4];
+ int length;
+ int ret;
+
+ if (PyLong_Check(params.seq)) {
+ values[0] = PyC_Long_AsI32(params.seq);
+ length = 1;
+ ret = 0;
+ }
+ else {
+ PyObject *seq_fast = PySequence_Fast(params.seq, error_prefix);
+ if (seq_fast == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: expected a sequence, got %s",
+ error_prefix,
+ Py_TYPE(params.seq)->tp_name);
+ ret = -1;
+ }
+ else {
+ length = PySequence_Fast_GET_SIZE(seq_fast);
+ if (length == 0 || length > 4) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: invalid sequence length. expected 1..4, got %d",
+ error_prefix,
+ length);
+ ret = -1;
+ }
+ else {
+ ret = PyC_AsArray_FAST(values, seq_fast, length, &PyLong_Type, false, error_prefix);
+ }
+ Py_DECREF(seq_fast);
+ }
+ }
+ if (ret == -1) {
+ return NULL;
+ }
+
+ const int location = bpygpu_uniform_location_get(self->shader, params.id, error_prefix);
+
+ if (location == -1) {
+ return NULL;
+ }
+
+ GPU_shader_uniform_vector_int(self->shader, location, length, 1, values);
+
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpygpu_shader_attr_from_name_doc,
-".. method:: attr_from_name(name)\n"
-"\n"
-" Get attribute location by name.\n"
-"\n"
-" :param name: The name of the attribute variable whose location is to be queried.\n"
-" :type name: str\n"
-" :return: The location of an attribute variable.\n"
-" :rtype: int\n"
-);
-static PyObject *bpygpu_shader_attr_from_name(
- BPyGPUShader *self, PyObject *arg)
+PyDoc_STRVAR(
+ bpygpu_shader_attr_from_name_doc,
+ ".. method:: attr_from_name(name)\n"
+ "\n"
+ " Get attribute location by name.\n"
+ "\n"
+ " :param name: The name of the attribute variable whose location is to be queried.\n"
+ " :type name: str\n"
+ " :return: The location of an attribute variable.\n"
+ " :rtype: int\n");
+static PyObject *bpygpu_shader_attr_from_name(BPyGPUShader *self, PyObject *arg)
{
- const char *name = PyUnicode_AsUTF8(arg);
- if (name == NULL) {
- return NULL;
- }
+ const char *name = PyUnicode_AsUTF8(arg);
+ if (name == NULL) {
+ return NULL;
+ }
- int attr = GPU_shader_get_attribute(self->shader, name);
+ int attr = GPU_shader_get_attribute(self->shader, name);
- if (attr == -1) {
- PyErr_Format(PyExc_ValueError,
- "GPUShader.attr_from_name: attribute %.32s not found", name);
- return NULL;
- }
+ if (attr == -1) {
+ PyErr_Format(PyExc_ValueError, "GPUShader.attr_from_name: attribute %.32s not found", name);
+ return NULL;
+ }
- return PyLong_FromLong(attr);
+ return PyLong_FromLong(attr);
}
PyDoc_STRVAR(bpygpu_shader_calc_format_doc,
-".. method:: calc_format()\n"
-"\n"
-" Build a new format based on the attributes of the shader.\n"
-"\n"
-" :return: vertex attribute format for the shader\n"
-" :rtype: GPUVertFormat\n"
-);
+ ".. method:: calc_format()\n"
+ "\n"
+ " Build a new format based on the attributes of the shader.\n"
+ "\n"
+ " :return: vertex attribute format for the shader\n"
+ " :rtype: GPUVertFormat\n");
static PyObject *bpygpu_shader_calc_format(BPyGPUShader *self, PyObject *UNUSED(arg))
{
- BPyGPUVertFormat *ret = (BPyGPUVertFormat *)BPyGPUVertFormat_CreatePyObject(NULL);
- GPU_vertformat_from_interface(&ret->fmt, GPU_shader_get_interface(self->shader));
- return (PyObject *)ret;
+ BPyGPUVertFormat *ret = (BPyGPUVertFormat *)BPyGPUVertFormat_CreatePyObject(NULL);
+ GPU_vertformat_from_interface(&ret->fmt, GPU_shader_get_interface(self->shader));
+ return (PyObject *)ret;
}
static struct PyMethodDef bpygpu_shader_methods[] = {
- {"bind", (PyCFunction)bpygpu_shader_bind,
- METH_NOARGS, bpygpu_shader_bind_doc},
- {"uniform_from_name",
- (PyCFunction)bpygpu_shader_uniform_from_name,
- METH_O, bpygpu_shader_uniform_from_name_doc},
- {"uniform_block_from_name",
- (PyCFunction)bpygpu_shader_uniform_block_from_name,
- METH_O, bpygpu_shader_uniform_block_from_name_doc},
- {"uniform_vector_float",
- (PyCFunction)bpygpu_shader_uniform_vector_float,
- METH_VARARGS, bpygpu_shader_uniform_vector_float_doc},
- {"uniform_vector_int",
- (PyCFunction)bpygpu_shader_uniform_vector_int,
- METH_VARARGS, bpygpu_shader_uniform_vector_int_doc},
- {"uniform_bool",
- (PyCFunction)bpygpu_shader_uniform_bool,
- METH_VARARGS, bpygpu_shader_uniform_bool_doc},
- {"uniform_float",
- (PyCFunction)bpygpu_shader_uniform_float,
- METH_VARARGS, bpygpu_shader_uniform_float_doc},
- {"uniform_int",
- (PyCFunction)bpygpu_shader_uniform_int,
- METH_VARARGS, bpygpu_shader_uniform_int_doc},
- {"attr_from_name",
- (PyCFunction)bpygpu_shader_attr_from_name,
- METH_O, bpygpu_shader_attr_from_name_doc},
- {"format_calc",
- (PyCFunction)bpygpu_shader_calc_format,
- METH_NOARGS, bpygpu_shader_calc_format_doc},
- {NULL, NULL, 0, NULL},
+ {"bind", (PyCFunction)bpygpu_shader_bind, METH_NOARGS, bpygpu_shader_bind_doc},
+ {"uniform_from_name",
+ (PyCFunction)bpygpu_shader_uniform_from_name,
+ METH_O,
+ bpygpu_shader_uniform_from_name_doc},
+ {"uniform_block_from_name",
+ (PyCFunction)bpygpu_shader_uniform_block_from_name,
+ METH_O,
+ bpygpu_shader_uniform_block_from_name_doc},
+ {"uniform_vector_float",
+ (PyCFunction)bpygpu_shader_uniform_vector_float,
+ METH_VARARGS,
+ bpygpu_shader_uniform_vector_float_doc},
+ {"uniform_vector_int",
+ (PyCFunction)bpygpu_shader_uniform_vector_int,
+ METH_VARARGS,
+ bpygpu_shader_uniform_vector_int_doc},
+ {"uniform_bool",
+ (PyCFunction)bpygpu_shader_uniform_bool,
+ METH_VARARGS,
+ bpygpu_shader_uniform_bool_doc},
+ {"uniform_float",
+ (PyCFunction)bpygpu_shader_uniform_float,
+ METH_VARARGS,
+ bpygpu_shader_uniform_float_doc},
+ {"uniform_int",
+ (PyCFunction)bpygpu_shader_uniform_int,
+ METH_VARARGS,
+ bpygpu_shader_uniform_int_doc},
+ {"attr_from_name",
+ (PyCFunction)bpygpu_shader_attr_from_name,
+ METH_O,
+ bpygpu_shader_attr_from_name_doc},
+ {"format_calc",
+ (PyCFunction)bpygpu_shader_calc_format,
+ METH_NOARGS,
+ bpygpu_shader_calc_format_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(bpygpu_shader_program_doc,
-"The name of the program object for use by the OpenGL API (read-only).\n\n:type: int"
-);
+PyDoc_STRVAR(
+ bpygpu_shader_program_doc,
+ "The name of the program object for use by the OpenGL API (read-only).\n\n:type: int");
static PyObject *bpygpu_shader_program_get(BPyGPUShader *self, void *UNUSED(closure))
{
- return PyLong_FromLong(GPU_shader_get_program(self->shader));
+ return PyLong_FromLong(GPU_shader_get_program(self->shader));
}
static PyGetSetDef bpygpu_shader_getseters[] = {
- {(char *)"program",
- (getter)bpygpu_shader_program_get, (setter)NULL,
- bpygpu_shader_program_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"program",
+ (getter)bpygpu_shader_program_get,
+ (setter)NULL,
+ bpygpu_shader_program_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
static void bpygpu_shader_dealloc(BPyGPUShader *self)
{
- if (self->is_builtin == false) {
- GPU_shader_free(self->shader);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (self->is_builtin == false) {
+ GPU_shader_free(self->shader);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
-
-PyDoc_STRVAR(bpygpu_shader_doc,
-".. class:: GPUShader(vertexcode, fragcode, geocode=None, libcode=None, defines=None)\n"
-"\n"
-" GPUShader combines multiple GLSL shaders into a program used for drawing.\n"
-" It must contain a vertex and fragment shaders, with an optional geometry shader.\n"
-"\n"
-" The GLSL #version directive is automatically included at the top of shaders, and set to 330.\n"
-" Some preprocessor directives are automatically added according to the Operating System or availability:\n"
-" ``GPU_ATI``, ``GPU_NVIDIA`` and ``GPU_INTEL``.\n"
-"\n"
-" The following extensions are enabled by default if supported by the GPU:\n"
-" ``GL_ARB_texture_gather`` and ``GL_ARB_texture_query_lod``.\n"
-"\n"
-" To debug shaders, use the --debug-gpu-shaders command line option"
-" to see full GLSL shader compilation and linking errors.\n"
-"\n"
-" :param vertexcode: Vertex shader code.\n"
-" :type vertexcode: str\n"
-" :param fragcode: Fragment shader code.\n"
-" :type value: str\n"
-" :param geocode: Geometry shader code.\n"
-" :type value: str\n"
-" :param libcode: Code with functions and presets to be shared between shaders.\n"
-" :type value: str\n"
-" :param defines: Preprocessor directives.\n"
-" :type value: str\n"
-);
+PyDoc_STRVAR(
+ bpygpu_shader_doc,
+ ".. class:: GPUShader(vertexcode, fragcode, geocode=None, libcode=None, defines=None)\n"
+ "\n"
+ " GPUShader combines multiple GLSL shaders into a program used for drawing.\n"
+ " It must contain a vertex and fragment shaders, with an optional geometry shader.\n"
+ "\n"
+ " The GLSL #version directive is automatically included at the top of shaders, and set to "
+ "330.\n"
+ " Some preprocessor directives are automatically added according to the Operating System or "
+ "availability:\n"
+ " ``GPU_ATI``, ``GPU_NVIDIA`` and ``GPU_INTEL``.\n"
+ "\n"
+ " The following extensions are enabled by default if supported by the GPU:\n"
+ " ``GL_ARB_texture_gather`` and ``GL_ARB_texture_query_lod``.\n"
+ "\n"
+ " To debug shaders, use the --debug-gpu-shaders command line option"
+ " to see full GLSL shader compilation and linking errors.\n"
+ "\n"
+ " :param vertexcode: Vertex shader code.\n"
+ " :type vertexcode: str\n"
+ " :param fragcode: Fragment shader code.\n"
+ " :type value: str\n"
+ " :param geocode: Geometry shader code.\n"
+ " :type value: str\n"
+ " :param libcode: Code with functions and presets to be shared between shaders.\n"
+ " :type value: str\n"
+ " :param defines: Preprocessor directives.\n"
+ " :type value: str\n");
PyTypeObject BPyGPUShader_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUShader",
- .tp_basicsize = sizeof(BPyGPUShader),
- .tp_dealloc = (destructor)bpygpu_shader_dealloc,
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_doc = bpygpu_shader_doc,
- .tp_methods = bpygpu_shader_methods,
- .tp_getset = bpygpu_shader_getseters,
- .tp_new = bpygpu_shader_new,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUShader",
+ .tp_basicsize = sizeof(BPyGPUShader),
+ .tp_dealloc = (destructor)bpygpu_shader_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = bpygpu_shader_doc,
+ .tp_methods = bpygpu_shader_methods,
+ .tp_getset = bpygpu_shader_getseters,
+ .tp_new = bpygpu_shader_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name gpu.shader Module API
* \{ */
PyDoc_STRVAR(bpygpu_shader_unbind_doc,
-".. function:: unbind()\n"
-"\n"
-" Unbind the bound shader object.\n"
-);
+ ".. function:: unbind()\n"
+ "\n"
+ " Unbind the bound shader object.\n");
static PyObject *bpygpu_shader_unbind(BPyGPUShader *UNUSED(self))
{
- GPU_shader_unbind();
- Py_RETURN_NONE;
+ GPU_shader_unbind();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpygpu_shader_from_builtin_doc,
-".. function:: from_builtin(shader_name)\n"
-"\n"
-" Shaders that are embedded in the blender internal code.\n"
-" They all read the uniform 'mat4 ModelViewProjectionMatrix', which can be edited by the 'gpu.matrix' module.\n"
-" For more details, you can check the shader code with the function 'gpu.shader.code_from_builtin';\n"
-"\n"
-" :param shader_name: One of these builtin shader names: {\n"
-" '2D_UNIFORM_COLOR',\n"
-" '2D_FLAT_COLOR',\n"
-" '2D_SMOOTH_COLOR',\n"
-" '2D_IMAGE',\n"
-" '3D_UNIFORM_COLOR',\n"
-" '3D_FLAT_COLOR',\n"
-" '3D_SMOOTH_COLOR'}\n"
-" :type shader_name: str\n"
-" :return: Shader object corresponding to the given name.\n"
-" :rtype: :class:`bpy.types.GPUShader`\n"
-);
+ ".. function:: from_builtin(shader_name)\n"
+ "\n"
+ " Shaders that are embedded in the blender internal code.\n"
+ " They all read the uniform 'mat4 ModelViewProjectionMatrix', which can be edited "
+ "by the 'gpu.matrix' module.\n"
+ " For more details, you can check the shader code with the function "
+ "'gpu.shader.code_from_builtin';\n"
+ "\n"
+ " :param shader_name: One of these builtin shader names: {\n"
+ " '2D_UNIFORM_COLOR',\n"
+ " '2D_FLAT_COLOR',\n"
+ " '2D_SMOOTH_COLOR',\n"
+ " '2D_IMAGE',\n"
+ " '3D_UNIFORM_COLOR',\n"
+ " '3D_FLAT_COLOR',\n"
+ " '3D_SMOOTH_COLOR'}\n"
+ " :type shader_name: str\n"
+ " :return: Shader object corresponding to the given name.\n"
+ " :rtype: :class:`bpy.types.GPUShader`\n");
static PyObject *bpygpu_shader_from_builtin(PyObject *UNUSED(self), PyObject *arg)
{
- BPYGPU_IS_INIT_OR_ERROR_OBJ;
+ BPYGPU_IS_INIT_OR_ERROR_OBJ;
- eGPUBuiltinShader shader_id;
+ eGPUBuiltinShader shader_id;
- if (!bpygpu_ParseBultinShaderEnum(arg, &shader_id)) {
- return NULL;
- }
+ if (!bpygpu_ParseBultinShaderEnum(arg, &shader_id)) {
+ return NULL;
+ }
- GPUShader *shader = GPU_shader_get_builtin_shader(shader_id);
+ GPUShader *shader = GPU_shader_get_builtin_shader(shader_id);
- return BPyGPUShader_CreatePyObject(shader, true);
+ return BPyGPUShader_CreatePyObject(shader, true);
}
PyDoc_STRVAR(bpygpu_shader_code_from_builtin_doc,
-".. function:: code_from_builtin(shader_name)\n"
-"\n"
-" Exposes the internal shader code for query.\n"
-"\n"
-" :param shader_name: One of these builtin shader names: {\n"
-" '2D_UNIFORM_COLOR',\n"
-" '2D_FLAT_COLOR',\n"
-" '2D_SMOOTH_COLOR',\n"
-" '2D_IMAGE',\n"
-" '3D_UNIFORM_COLOR',\n"
-" '3D_FLAT_COLOR',\n"
-" '3D_SMOOTH_COLOR'}\n"
-" :type shader_name: str\n"
-" :return: Vertex, fragment and geometry shader codes.\n"
-" :rtype: dict\n"
-);
+ ".. function:: code_from_builtin(shader_name)\n"
+ "\n"
+ " Exposes the internal shader code for query.\n"
+ "\n"
+ " :param shader_name: One of these builtin shader names: {\n"
+ " '2D_UNIFORM_COLOR',\n"
+ " '2D_FLAT_COLOR',\n"
+ " '2D_SMOOTH_COLOR',\n"
+ " '2D_IMAGE',\n"
+ " '3D_UNIFORM_COLOR',\n"
+ " '3D_FLAT_COLOR',\n"
+ " '3D_SMOOTH_COLOR'}\n"
+ " :type shader_name: str\n"
+ " :return: Vertex, fragment and geometry shader codes.\n"
+ " :rtype: dict\n");
static PyObject *bpygpu_shader_code_from_builtin(BPyGPUShader *UNUSED(self), PyObject *arg)
{
- eGPUBuiltinShader shader_id;
+ eGPUBuiltinShader shader_id;
- const char *vert;
- const char *frag;
- const char *geom;
- const char *defines;
+ const char *vert;
+ const char *frag;
+ const char *geom;
+ const char *defines;
- PyObject *item, *r_dict;
+ PyObject *item, *r_dict;
- if (!bpygpu_ParseBultinShaderEnum(arg, &shader_id)) {
- return NULL;
- }
+ if (!bpygpu_ParseBultinShaderEnum(arg, &shader_id)) {
+ return NULL;
+ }
- GPU_shader_get_builtin_shader_code(
- shader_id, &vert, &frag, &geom, &defines);
+ GPU_shader_get_builtin_shader_code(shader_id, &vert, &frag, &geom, &defines);
- r_dict = PyDict_New();
+ r_dict = PyDict_New();
- PyDict_SetItemString(r_dict, "vertex_shader", item = PyUnicode_FromString(vert));
- Py_DECREF(item);
+ PyDict_SetItemString(r_dict, "vertex_shader", item = PyUnicode_FromString(vert));
+ Py_DECREF(item);
- PyDict_SetItemString(r_dict, "fragment_shader", item = PyUnicode_FromString(frag));
- Py_DECREF(item);
+ PyDict_SetItemString(r_dict, "fragment_shader", item = PyUnicode_FromString(frag));
+ Py_DECREF(item);
- if (geom) {
- PyDict_SetItemString(r_dict, "geometry_shader", item = PyUnicode_FromString(geom));
- Py_DECREF(item);
- }
- if (defines) {
- PyDict_SetItemString(r_dict, "defines", item = PyUnicode_FromString(defines));
- Py_DECREF(item);
- }
- return r_dict;
+ if (geom) {
+ PyDict_SetItemString(r_dict, "geometry_shader", item = PyUnicode_FromString(geom));
+ Py_DECREF(item);
+ }
+ if (defines) {
+ PyDict_SetItemString(r_dict, "defines", item = PyUnicode_FromString(defines));
+ Py_DECREF(item);
+ }
+ return r_dict;
}
static struct PyMethodDef bpygpu_shader_module_methods[] = {
- {"unbind",
- (PyCFunction)bpygpu_shader_unbind,
- METH_NOARGS, bpygpu_shader_unbind_doc},
- {"from_builtin",
- (PyCFunction)bpygpu_shader_from_builtin,
- METH_O, bpygpu_shader_from_builtin_doc},
- {"code_from_builtin",
- (PyCFunction)bpygpu_shader_code_from_builtin,
- METH_O, bpygpu_shader_code_from_builtin_doc},
- {NULL, NULL, 0, NULL},
+ {"unbind", (PyCFunction)bpygpu_shader_unbind, METH_NOARGS, bpygpu_shader_unbind_doc},
+ {"from_builtin",
+ (PyCFunction)bpygpu_shader_from_builtin,
+ METH_O,
+ bpygpu_shader_from_builtin_doc},
+ {"code_from_builtin",
+ (PyCFunction)bpygpu_shader_code_from_builtin,
+ METH_O,
+ bpygpu_shader_code_from_builtin_doc},
+ {NULL, NULL, 0, NULL},
};
PyDoc_STRVAR(bpygpu_shader_module_doc,
-"This module provides access to GPUShader internal functions."
-);
+ "This module provides access to GPUShader internal functions.");
static PyModuleDef BPyGPU_shader_module_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "gpu.shader",
- .m_doc = bpygpu_shader_module_doc,
- .m_methods = bpygpu_shader_module_methods,
+ PyModuleDef_HEAD_INIT,
+ .m_name = "gpu.shader",
+ .m_doc = bpygpu_shader_module_doc,
+ .m_methods = bpygpu_shader_module_methods,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUShader_CreatePyObject(GPUShader *shader, bool is_builtin)
{
- BPyGPUShader *self;
+ BPyGPUShader *self;
- self = PyObject_New(BPyGPUShader, &BPyGPUShader_Type);
- self->shader = shader;
- self->is_builtin = is_builtin;
+ self = PyObject_New(BPyGPUShader, &BPyGPUShader_Type);
+ self->shader = shader;
+ self->is_builtin = is_builtin;
- return (PyObject *)self;
+ return (PyObject *)self;
}
PyObject *BPyInit_gpu_shader(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&BPyGPU_shader_module_def);
+ submodule = PyModule_Create(&BPyGPU_shader_module_def);
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_shader.h b/source/blender/python/gpu/gpu_py_shader.h
index a6fd9f5c915..92873753039 100644
--- a/source/blender/python/gpu/gpu_py_shader.h
+++ b/source/blender/python/gpu/gpu_py_shader.h
@@ -23,12 +23,11 @@
extern PyTypeObject BPyGPUShader_Type;
-#define BPyGPUShader_Check(v) (Py_TYPE(v) == &BPyGPUShader_Type)
+#define BPyGPUShader_Check(v) (Py_TYPE(v) == &BPyGPUShader_Type)
typedef struct BPyGPUShader {
- PyObject_VAR_HEAD
- struct GPUShader *shader;
- bool is_builtin;
+ PyObject_VAR_HEAD struct GPUShader *shader;
+ bool is_builtin;
} BPyGPUShader;
PyObject *BPyGPUShader_CreatePyObject(struct GPUShader *shader, bool is_builtin);
diff --git a/source/blender/python/gpu/gpu_py_types.c b/source/blender/python/gpu/gpu_py_types.c
index 67bdc070168..f7909e38f7b 100644
--- a/source/blender/python/gpu/gpu_py_types.c
+++ b/source/blender/python/gpu/gpu_py_types.c
@@ -30,53 +30,53 @@
/* -------------------------------------------------------------------- */
-
/** \name GPU Types Module
* \{ */
static struct PyModuleDef BPyGPU_types_module_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "gpu.types",
+ PyModuleDef_HEAD_INIT,
+ .m_name = "gpu.types",
};
PyObject *BPyInit_gpu_types(void)
{
- PyObject *submodule;
-
- submodule = PyModule_Create(&BPyGPU_types_module_def);
-
- if (PyType_Ready(&BPyGPUVertFormat_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&BPyGPUVertBuf_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&BPyGPUIndexBuf_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&BPyGPUBatch_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&BPyGPUOffScreen_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&BPyGPUShader_Type) < 0) {
- return NULL;
- }
+ PyObject *submodule;
+
+ submodule = PyModule_Create(&BPyGPU_types_module_def);
+
+ if (PyType_Ready(&BPyGPUVertFormat_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&BPyGPUVertBuf_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&BPyGPUIndexBuf_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&BPyGPUBatch_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&BPyGPUOffScreen_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&BPyGPUShader_Type) < 0) {
+ return NULL;
+ }
#define MODULE_TYPE_ADD(s, t) \
- PyModule_AddObject(s, t.tp_name, (PyObject *)&t); Py_INCREF((PyObject *)&t)
+ PyModule_AddObject(s, t.tp_name, (PyObject *)&t); \
+ Py_INCREF((PyObject *)&t)
- MODULE_TYPE_ADD(submodule, BPyGPUVertFormat_Type);
- MODULE_TYPE_ADD(submodule, BPyGPUVertBuf_Type);
- MODULE_TYPE_ADD(submodule, BPyGPUIndexBuf_Type);
- MODULE_TYPE_ADD(submodule, BPyGPUBatch_Type);
- MODULE_TYPE_ADD(submodule, BPyGPUOffScreen_Type);
- MODULE_TYPE_ADD(submodule, BPyGPUShader_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUVertFormat_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUVertBuf_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUIndexBuf_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUBatch_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUOffScreen_Type);
+ MODULE_TYPE_ADD(submodule, BPyGPUShader_Type);
#undef MODULE_TYPE_ADD
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_vertex_buffer.c b/source/blender/python/gpu/gpu_py_vertex_buffer.c
index 62c3b4f696f..9760c12d89f 100644
--- a/source/blender/python/gpu/gpu_py_vertex_buffer.c
+++ b/source/blender/python/gpu/gpu_py_vertex_buffer.c
@@ -40,48 +40,74 @@
* \{ */
#define PY_AS_NATIVE_SWITCH(attr) \
- switch (attr->comp_type) { \
- case GPU_COMP_I8: { PY_AS_NATIVE(int8_t, PyC_Long_AsI8); break; } \
- case GPU_COMP_U8: { PY_AS_NATIVE(uint8_t, PyC_Long_AsU8); break; } \
- case GPU_COMP_I16: { PY_AS_NATIVE(int16_t, PyC_Long_AsI16); break; } \
- case GPU_COMP_U16: { PY_AS_NATIVE(uint16_t, PyC_Long_AsU16); break; } \
- case GPU_COMP_I32: { PY_AS_NATIVE(int32_t, PyC_Long_AsI32); break; } \
- case GPU_COMP_U32: { PY_AS_NATIVE(uint32_t, PyC_Long_AsU32); break; } \
- case GPU_COMP_F32: { PY_AS_NATIVE(float, PyFloat_AsDouble); break; } \
- default: \
- BLI_assert(0); \
- } ((void)0)
+ switch (attr->comp_type) { \
+ case GPU_COMP_I8: { \
+ PY_AS_NATIVE(int8_t, PyC_Long_AsI8); \
+ break; \
+ } \
+ case GPU_COMP_U8: { \
+ PY_AS_NATIVE(uint8_t, PyC_Long_AsU8); \
+ break; \
+ } \
+ case GPU_COMP_I16: { \
+ PY_AS_NATIVE(int16_t, PyC_Long_AsI16); \
+ break; \
+ } \
+ case GPU_COMP_U16: { \
+ PY_AS_NATIVE(uint16_t, PyC_Long_AsU16); \
+ break; \
+ } \
+ case GPU_COMP_I32: { \
+ PY_AS_NATIVE(int32_t, PyC_Long_AsI32); \
+ break; \
+ } \
+ case GPU_COMP_U32: { \
+ PY_AS_NATIVE(uint32_t, PyC_Long_AsU32); \
+ break; \
+ } \
+ case GPU_COMP_F32: { \
+ PY_AS_NATIVE(float, PyFloat_AsDouble); \
+ break; \
+ } \
+ default: \
+ BLI_assert(0); \
+ } \
+ ((void)0)
/* No error checking, callers must run PyErr_Occurred */
static void fill_format_elem(void *data_dst_void, PyObject *py_src, const GPUVertAttr *attr)
{
#define PY_AS_NATIVE(ty_dst, py_as_native) \
-{ \
- ty_dst *data_dst = data_dst_void; \
- *data_dst = py_as_native(py_src); \
-} ((void)0)
+ { \
+ ty_dst *data_dst = data_dst_void; \
+ *data_dst = py_as_native(py_src); \
+ } \
+ ((void)0)
- PY_AS_NATIVE_SWITCH(attr);
+ PY_AS_NATIVE_SWITCH(attr);
#undef PY_AS_NATIVE
}
/* No error checking, callers must run PyErr_Occurred */
-static void fill_format_sequence(void *data_dst_void, PyObject *py_seq_fast, const GPUVertAttr *attr)
+static void fill_format_sequence(void *data_dst_void,
+ PyObject *py_seq_fast,
+ const GPUVertAttr *attr)
{
- const uint len = attr->comp_len;
- PyObject **value_fast_items = PySequence_Fast_ITEMS(py_seq_fast);
+ const uint len = attr->comp_len;
+ PyObject **value_fast_items = PySequence_Fast_ITEMS(py_seq_fast);
/**
* Args are constants, so range checks will be optimized out if they're nop's.
*/
#define PY_AS_NATIVE(ty_dst, py_as_native) \
- ty_dst *data_dst = data_dst_void; \
- for (uint i = 0; i < len; i++) { \
- data_dst[i] = py_as_native(value_fast_items[i]); \
- } ((void)0)
+ ty_dst *data_dst = data_dst_void; \
+ for (uint i = 0; i < len; i++) { \
+ data_dst[i] = py_as_native(value_fast_items[i]); \
+ } \
+ ((void)0)
- PY_AS_NATIVE_SWITCH(attr);
+ PY_AS_NATIVE_SWITCH(attr);
#undef PY_AS_NATIVE
}
@@ -90,125 +116,125 @@ static void fill_format_sequence(void *data_dst_void, PyObject *py_seq_fast, con
#undef WARN_TYPE_LIMIT_PUSH
#undef WARN_TYPE_LIMIT_POP
-static bool bpygpu_vertbuf_fill_impl(
- GPUVertBuf *vbo,
- uint data_id, PyObject *seq, const char *error_prefix)
+static bool bpygpu_vertbuf_fill_impl(GPUVertBuf *vbo,
+ uint data_id,
+ PyObject *seq,
+ const char *error_prefix)
{
- const char *exc_str_size_mismatch = "Expected a %s of size %d, got %u";
-
- bool ok = true;
- const GPUVertAttr *attr = &vbo->format.attrs[data_id];
-
- if (PyObject_CheckBuffer(seq)) {
- Py_buffer pybuffer;
-
- if (PyObject_GetBuffer(seq, &pybuffer, PyBUF_STRIDES | PyBUF_ND) == -1) {
- /* PyObject_GetBuffer raise a PyExc_BufferError */
- return false;
- }
-
- uint comp_len = pybuffer.ndim == 1 ? 1 : (uint)pybuffer.shape[1];
-
- if (pybuffer.shape[0] != vbo->vertex_len) {
- PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
- "sequence", vbo->vertex_len, pybuffer.shape[0]);
- ok = false;
- }
- else if (comp_len != attr->comp_len) {
- PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
- "component", attr->comp_len, comp_len);
- ok = false;
- }
- else {
- GPU_vertbuf_attr_fill_stride(vbo, data_id, pybuffer.strides[0], pybuffer.buf);
- }
-
- PyBuffer_Release(&pybuffer);
- }
- else {
- GPUVertBufRaw data_step;
- GPU_vertbuf_attr_get_raw_data(vbo, data_id, &data_step);
-
- PyObject *seq_fast = PySequence_Fast(seq, "Vertex buffer fill");
- if (seq_fast == NULL) {
- return false;
- }
-
- const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
-
- if (seq_len != vbo->vertex_len) {
- PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
- "sequence", vbo->vertex_len, seq_len);
- }
-
- PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
-
- if (attr->comp_len == 1) {
- for (uint i = 0; i < seq_len; i++) {
- uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
- PyObject *item = seq_items[i];
- fill_format_elem(data, item, attr);
- }
- }
- else {
- for (uint i = 0; i < seq_len; i++) {
- uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
- PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
-
- if (seq_fast_item == NULL) {
- ok = false;
- goto finally;
- }
- if (PySequence_Fast_GET_SIZE(seq_fast_item) != attr->comp_len) {
- PyErr_Format(PyExc_ValueError, exc_str_size_mismatch,
- "sequence", attr->comp_len, PySequence_Fast_GET_SIZE(seq_fast_item));
- ok = false;
- Py_DECREF(seq_fast_item);
- goto finally;
- }
-
- /* May trigger error, check below */
- fill_format_sequence(data, seq_fast_item, attr);
- Py_DECREF(seq_fast_item);
- }
- }
-
- if (PyErr_Occurred()) {
- ok = false;
- }
-
-finally:
-
- Py_DECREF(seq_fast);
- }
- return ok;
+ const char *exc_str_size_mismatch = "Expected a %s of size %d, got %u";
+
+ bool ok = true;
+ const GPUVertAttr *attr = &vbo->format.attrs[data_id];
+
+ if (PyObject_CheckBuffer(seq)) {
+ Py_buffer pybuffer;
+
+ if (PyObject_GetBuffer(seq, &pybuffer, PyBUF_STRIDES | PyBUF_ND) == -1) {
+ /* PyObject_GetBuffer raise a PyExc_BufferError */
+ return false;
+ }
+
+ uint comp_len = pybuffer.ndim == 1 ? 1 : (uint)pybuffer.shape[1];
+
+ if (pybuffer.shape[0] != vbo->vertex_len) {
+ PyErr_Format(
+ PyExc_ValueError, exc_str_size_mismatch, "sequence", vbo->vertex_len, pybuffer.shape[0]);
+ ok = false;
+ }
+ else if (comp_len != attr->comp_len) {
+ PyErr_Format(PyExc_ValueError, exc_str_size_mismatch, "component", attr->comp_len, comp_len);
+ ok = false;
+ }
+ else {
+ GPU_vertbuf_attr_fill_stride(vbo, data_id, pybuffer.strides[0], pybuffer.buf);
+ }
+
+ PyBuffer_Release(&pybuffer);
+ }
+ else {
+ GPUVertBufRaw data_step;
+ GPU_vertbuf_attr_get_raw_data(vbo, data_id, &data_step);
+
+ PyObject *seq_fast = PySequence_Fast(seq, "Vertex buffer fill");
+ if (seq_fast == NULL) {
+ return false;
+ }
+
+ const uint seq_len = PySequence_Fast_GET_SIZE(seq_fast);
+
+ if (seq_len != vbo->vertex_len) {
+ PyErr_Format(PyExc_ValueError, exc_str_size_mismatch, "sequence", vbo->vertex_len, seq_len);
+ }
+
+ PyObject **seq_items = PySequence_Fast_ITEMS(seq_fast);
+
+ if (attr->comp_len == 1) {
+ for (uint i = 0; i < seq_len; i++) {
+ uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
+ PyObject *item = seq_items[i];
+ fill_format_elem(data, item, attr);
+ }
+ }
+ else {
+ for (uint i = 0; i < seq_len; i++) {
+ uchar *data = (uchar *)GPU_vertbuf_raw_step(&data_step);
+ PyObject *seq_fast_item = PySequence_Fast(seq_items[i], error_prefix);
+
+ if (seq_fast_item == NULL) {
+ ok = false;
+ goto finally;
+ }
+ if (PySequence_Fast_GET_SIZE(seq_fast_item) != attr->comp_len) {
+ PyErr_Format(PyExc_ValueError,
+ exc_str_size_mismatch,
+ "sequence",
+ attr->comp_len,
+ PySequence_Fast_GET_SIZE(seq_fast_item));
+ ok = false;
+ Py_DECREF(seq_fast_item);
+ goto finally;
+ }
+
+ /* May trigger error, check below */
+ fill_format_sequence(data, seq_fast_item, attr);
+ Py_DECREF(seq_fast_item);
+ }
+ }
+
+ if (PyErr_Occurred()) {
+ ok = false;
+ }
+
+ finally:
+
+ Py_DECREF(seq_fast);
+ }
+ return ok;
}
-static int bpygpu_attr_fill(GPUVertBuf *buf, int id, PyObject *py_seq_data, const char *error_prefix)
+static int bpygpu_attr_fill(GPUVertBuf *buf,
+ int id,
+ PyObject *py_seq_data,
+ const char *error_prefix)
{
- if (id < 0 || id >= buf->format.attr_len) {
- PyErr_Format(PyExc_ValueError,
- "Format id %d out of range",
- id);
- return 0;
- }
-
- if (buf->data == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "Can't fill, static buffer already in use");
- return 0;
- }
-
- if (!bpygpu_vertbuf_fill_impl(buf, (uint)id, py_seq_data, error_prefix)) {
- return 0;
- }
-
- return 1;
-}
+ if (id < 0 || id >= buf->format.attr_len) {
+ PyErr_Format(PyExc_ValueError, "Format id %d out of range", id);
+ return 0;
+ }
+ if (buf->data == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Can't fill, static buffer already in use");
+ return 0;
+ }
-/** \} */
+ if (!bpygpu_vertbuf_fill_impl(buf, (uint)id, py_seq_data, error_prefix)) {
+ return 0;
+ }
+
+ return 1;
+}
+/** \} */
/* -------------------------------------------------------------------- */
/** \name VertBuf Type
@@ -216,130 +242,118 @@ static int bpygpu_attr_fill(GPUVertBuf *buf, int id, PyObject *py_seq_data, cons
static PyObject *bpygpu_VertBuf_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- struct {
- PyObject *py_fmt;
- uint len;
- } params;
-
- static const char *_keywords[] = {"format", "len", NULL};
- static _PyArg_Parser _parser = {"O!I:GPUVertBuf.__new__", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &BPyGPUVertFormat_Type, &params.py_fmt,
- &params.len))
- {
- return NULL;
- }
-
- const GPUVertFormat *fmt = &((BPyGPUVertFormat *)params.py_fmt)->fmt;
- GPUVertBuf *vbo = GPU_vertbuf_create_with_format(fmt);
-
- GPU_vertbuf_data_alloc(vbo, params.len);
-
- return BPyGPUVertBuf_CreatePyObject(vbo);
+ struct {
+ PyObject *py_fmt;
+ uint len;
+ } params;
+
+ static const char *_keywords[] = {"format", "len", NULL};
+ static _PyArg_Parser _parser = {"O!I:GPUVertBuf.__new__", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kwds, &_parser, &BPyGPUVertFormat_Type, &params.py_fmt, &params.len)) {
+ return NULL;
+ }
+
+ const GPUVertFormat *fmt = &((BPyGPUVertFormat *)params.py_fmt)->fmt;
+ GPUVertBuf *vbo = GPU_vertbuf_create_with_format(fmt);
+
+ GPU_vertbuf_data_alloc(vbo, params.len);
+
+ return BPyGPUVertBuf_CreatePyObject(vbo);
}
PyDoc_STRVAR(bpygpu_VertBuf_attr_fill_doc,
-".. method:: attr_fill(id, data)\n"
-"\n"
-" Insert data into the buffer for a single attribute.\n"
-"\n"
-" :param id: Either the name or the id of the attribute.\n"
-" :type id: int or str\n"
-" :param data: Sequence of data that should be stored in the buffer\n"
-" :type data: sequence of values or tuples\n"
-);
+ ".. method:: attr_fill(id, data)\n"
+ "\n"
+ " Insert data into the buffer for a single attribute.\n"
+ "\n"
+ " :param id: Either the name or the id of the attribute.\n"
+ " :type id: int or str\n"
+ " :param data: Sequence of data that should be stored in the buffer\n"
+ " :type data: sequence of values or tuples\n");
static PyObject *bpygpu_VertBuf_attr_fill(BPyGPUVertBuf *self, PyObject *args, PyObject *kwds)
{
- PyObject *data;
- PyObject *identifier;
-
- static const char *_keywords[] = {"id", "data", NULL};
- static _PyArg_Parser _parser = {"OO:attr_fill", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &identifier, &data))
- {
- return NULL;
- }
-
- int id;
-
- if (PyLong_Check(identifier)) {
- id = PyLong_AsLong(identifier);
- }
- else if (PyUnicode_Check(identifier)) {
- const char *name = PyUnicode_AsUTF8(identifier);
- id = GPU_vertformat_attr_id_get(&self->buf->format, name);
- if (id == -1) {
- PyErr_SetString(PyExc_ValueError,
- "Unknown attribute name");
- return NULL;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "expected int or str type as identifier");
- return NULL;
- }
-
-
- if (!bpygpu_attr_fill(self->buf, id, data, "GPUVertBuf.attr_fill")) {
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyObject *data;
+ PyObject *identifier;
+
+ static const char *_keywords[] = {"id", "data", NULL};
+ static _PyArg_Parser _parser = {"OO:attr_fill", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, &identifier, &data)) {
+ return NULL;
+ }
+
+ int id;
+
+ if (PyLong_Check(identifier)) {
+ id = PyLong_AsLong(identifier);
+ }
+ else if (PyUnicode_Check(identifier)) {
+ const char *name = PyUnicode_AsUTF8(identifier);
+ id = GPU_vertformat_attr_id_get(&self->buf->format, name);
+ if (id == -1) {
+ PyErr_SetString(PyExc_ValueError, "Unknown attribute name");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "expected int or str type as identifier");
+ return NULL;
+ }
+
+ if (!bpygpu_attr_fill(self->buf, id, data, "GPUVertBuf.attr_fill")) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
-
static struct PyMethodDef bpygpu_VertBuf_methods[] = {
- {"attr_fill", (PyCFunction) bpygpu_VertBuf_attr_fill,
- METH_VARARGS | METH_KEYWORDS, bpygpu_VertBuf_attr_fill_doc},
- {NULL, NULL, 0, NULL},
+ {"attr_fill",
+ (PyCFunction)bpygpu_VertBuf_attr_fill,
+ METH_VARARGS | METH_KEYWORDS,
+ bpygpu_VertBuf_attr_fill_doc},
+ {NULL, NULL, 0, NULL},
};
static void bpygpu_VertBuf_dealloc(BPyGPUVertBuf *self)
{
- GPU_vertbuf_discard(self->buf);
- Py_TYPE(self)->tp_free(self);
+ GPU_vertbuf_discard(self->buf);
+ Py_TYPE(self)->tp_free(self);
}
PyDoc_STRVAR(py_gpu_vertex_buffer_doc,
-".. class:: GPUVertBuf(len, format)\n"
-"\n"
-" Contains a VBO.\n"
-"\n"
-" :param len: Amount of vertices that will fit into this buffer.\n"
-" :type type: `int`\n"
-" :param format: Vertex format.\n"
-" :type buf: :class:`gpu.types.GPUVertFormat`\n"
-);
+ ".. class:: GPUVertBuf(len, format)\n"
+ "\n"
+ " Contains a VBO.\n"
+ "\n"
+ " :param len: Amount of vertices that will fit into this buffer.\n"
+ " :type type: `int`\n"
+ " :param format: Vertex format.\n"
+ " :type buf: :class:`gpu.types.GPUVertFormat`\n");
PyTypeObject BPyGPUVertBuf_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUVertBuf",
- .tp_basicsize = sizeof(BPyGPUVertBuf),
- .tp_dealloc = (destructor)bpygpu_VertBuf_dealloc,
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_doc = py_gpu_vertex_buffer_doc,
- .tp_methods = bpygpu_VertBuf_methods,
- .tp_new = bpygpu_VertBuf_new,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUVertBuf",
+ .tp_basicsize = sizeof(BPyGPUVertBuf),
+ .tp_dealloc = (destructor)bpygpu_VertBuf_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = py_gpu_vertex_buffer_doc,
+ .tp_methods = bpygpu_VertBuf_methods,
+ .tp_new = bpygpu_VertBuf_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUVertBuf_CreatePyObject(GPUVertBuf *buf)
{
- BPyGPUVertBuf *self;
+ BPyGPUVertBuf *self;
- self = PyObject_New(BPyGPUVertBuf, &BPyGPUVertBuf_Type);
- self->buf = buf;
+ self = PyObject_New(BPyGPUVertBuf, &BPyGPUVertBuf_Type);
+ self->buf = buf;
- return (PyObject *)self;
+ return (PyObject *)self;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_vertex_buffer.h b/source/blender/python/gpu/gpu_py_vertex_buffer.h
index 2037c145704..b7124d245a9 100644
--- a/source/blender/python/gpu/gpu_py_vertex_buffer.h
+++ b/source/blender/python/gpu/gpu_py_vertex_buffer.h
@@ -25,12 +25,12 @@
extern PyTypeObject BPyGPUVertBuf_Type;
-#define BPyGPUVertBuf_Check(v) (Py_TYPE(v) == &BPyGPUVertBuf_Type)
+#define BPyGPUVertBuf_Check(v) (Py_TYPE(v) == &BPyGPUVertBuf_Type)
typedef struct BPyGPUVertBuf {
- PyObject_VAR_HEAD
- /* The buf is owned, we may support thin wrapped batches later. */
- struct GPUVertBuf *buf;
+ PyObject_VAR_HEAD
+ /* The buf is owned, we may support thin wrapped batches later. */
+ struct GPUVertBuf *buf;
} BPyGPUVertBuf;
PyObject *BPyGPUVertBuf_CreatePyObject(struct GPUVertBuf *vbo) ATTR_NONNULL(1);
diff --git a/source/blender/python/gpu/gpu_py_vertex_format.c b/source/blender/python/gpu/gpu_py_vertex_format.c
index 2cadbaf17ff..34df4cb1a4b 100644
--- a/source/blender/python/gpu/gpu_py_vertex_format.c
+++ b/source/blender/python/gpu/gpu_py_vertex_format.c
@@ -33,15 +33,15 @@
#include "gpu_py_vertex_format.h" /* own include */
#ifdef __BIG_ENDIAN__
- /* big endian */
-# define MAKE_ID2(c, d) ((c) << 8 | (d))
-# define MAKE_ID3(a, b, c) ( (int)(a) << 24 | (int)(b) << 16 | (c) << 8 )
-# define MAKE_ID4(a, b, c, d) ( (int)(a) << 24 | (int)(b) << 16 | (c) << 8 | (d) )
+/* big endian */
+# define MAKE_ID2(c, d) ((c) << 8 | (d))
+# define MAKE_ID3(a, b, c) ((int)(a) << 24 | (int)(b) << 16 | (c) << 8)
+# define MAKE_ID4(a, b, c, d) ((int)(a) << 24 | (int)(b) << 16 | (c) << 8 | (d))
#else
- /* little endian */
-# define MAKE_ID2(c, d) ((d) << 8 | (c))
-# define MAKE_ID3(a, b, c) ( (int)(c) << 16 | (b) << 8 | (a) )
-# define MAKE_ID4(a, b, c, d) ( (int)(d) << 24 | (int)(c) << 16 | (b) << 8 | (a) )
+/* little endian */
+# define MAKE_ID2(c, d) ((d) << 8 | (c))
+# define MAKE_ID3(a, b, c) ((int)(c) << 16 | (b) << 8 | (a))
+# define MAKE_ID4(a, b, c, d) ((int)(d) << 24 | (int)(c) << 16 | (b) << 8 | (a))
#endif
/* -------------------------------------------------------------------- */
@@ -52,205 +52,211 @@
static int bpygpu_parse_component_type(const char *str, int length)
{
- if (length == 2) {
- switch (*((ushort *)str)) {
- case MAKE_ID2('I', '8'): return GPU_COMP_I8;
- case MAKE_ID2('U', '8'): return GPU_COMP_U8;
- default: break;
- }
- }
- else if (length == 3) {
- switch (*((uint *)str)) {
- case MAKE_ID3('I', '1', '6'): return GPU_COMP_I16;
- case MAKE_ID3('U', '1', '6'): return GPU_COMP_U16;
- case MAKE_ID3('I', '3', '2'): return GPU_COMP_I32;
- case MAKE_ID3('U', '3', '2'): return GPU_COMP_U32;
- case MAKE_ID3('F', '3', '2'): return GPU_COMP_F32;
- case MAKE_ID3('I', '1', '0'): return GPU_COMP_I10;
- default: break;
- }
- }
- return -1;
+ if (length == 2) {
+ switch (*((ushort *)str)) {
+ case MAKE_ID2('I', '8'):
+ return GPU_COMP_I8;
+ case MAKE_ID2('U', '8'):
+ return GPU_COMP_U8;
+ default:
+ break;
+ }
+ }
+ else if (length == 3) {
+ switch (*((uint *)str)) {
+ case MAKE_ID3('I', '1', '6'):
+ return GPU_COMP_I16;
+ case MAKE_ID3('U', '1', '6'):
+ return GPU_COMP_U16;
+ case MAKE_ID3('I', '3', '2'):
+ return GPU_COMP_I32;
+ case MAKE_ID3('U', '3', '2'):
+ return GPU_COMP_U32;
+ case MAKE_ID3('F', '3', '2'):
+ return GPU_COMP_F32;
+ case MAKE_ID3('I', '1', '0'):
+ return GPU_COMP_I10;
+ default:
+ break;
+ }
+ }
+ return -1;
}
static int bpygpu_parse_fetch_mode(const char *str, int length)
{
#define MATCH_ID(id) \
- if (length == strlen(STRINGIFY(id))) { \
- if (STREQ(str, STRINGIFY(id))) { \
- return GPU_FETCH_##id; \
- } \
- } ((void)0)
-
- MATCH_ID(FLOAT);
- MATCH_ID(INT);
- MATCH_ID(INT_TO_FLOAT_UNIT);
- MATCH_ID(INT_TO_FLOAT);
+ if (length == strlen(STRINGIFY(id))) { \
+ if (STREQ(str, STRINGIFY(id))) { \
+ return GPU_FETCH_##id; \
+ } \
+ } \
+ ((void)0)
+
+ MATCH_ID(FLOAT);
+ MATCH_ID(INT);
+ MATCH_ID(INT_TO_FLOAT_UNIT);
+ MATCH_ID(INT_TO_FLOAT);
#undef MATCH_ID
- return -1;
+ return -1;
}
static int bpygpu_ParseVertCompType(PyObject *o, void *p)
{
- Py_ssize_t length;
- const char *str = _PyUnicode_AsStringAndSize(o, &length);
-
- if (str == NULL) {
- PyErr_Format(PyExc_ValueError,
- "expected a string, got %s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
-
- int comp_type = bpygpu_parse_component_type(str, length);
- if (comp_type == -1) {
- PyErr_Format(PyExc_ValueError,
- "unkown component type: '%s",
- str);
- return 0;
- }
-
- *((GPUVertCompType *)p) = comp_type;
- return 1;
+ Py_ssize_t length;
+ const char *str = _PyUnicode_AsStringAndSize(o, &length);
+
+ if (str == NULL) {
+ PyErr_Format(PyExc_ValueError, "expected a string, got %s", Py_TYPE(o)->tp_name);
+ return 0;
+ }
+
+ int comp_type = bpygpu_parse_component_type(str, length);
+ if (comp_type == -1) {
+ PyErr_Format(PyExc_ValueError, "unkown component type: '%s", str);
+ return 0;
+ }
+
+ *((GPUVertCompType *)p) = comp_type;
+ return 1;
}
static int bpygpu_ParseVertFetchMode(PyObject *o, void *p)
{
- Py_ssize_t length;
- const char *str = _PyUnicode_AsStringAndSize(o, &length);
-
- if (str == NULL) {
- PyErr_Format(PyExc_ValueError,
- "expected a string, got %s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
-
- int fetch_mode = bpygpu_parse_fetch_mode(str, length);
- if (fetch_mode == -1) {
- PyErr_Format(PyExc_ValueError,
- "unknown type literal: '%s'",
- str);
- return 0;
- }
-
- (*(GPUVertFetchMode *)p) = fetch_mode;
- return 1;
+ Py_ssize_t length;
+ const char *str = _PyUnicode_AsStringAndSize(o, &length);
+
+ if (str == NULL) {
+ PyErr_Format(PyExc_ValueError, "expected a string, got %s", Py_TYPE(o)->tp_name);
+ return 0;
+ }
+
+ int fetch_mode = bpygpu_parse_fetch_mode(str, length);
+ if (fetch_mode == -1) {
+ PyErr_Format(PyExc_ValueError, "unknown type literal: '%s'", str);
+ return 0;
+ }
+
+ (*(GPUVertFetchMode *)p) = fetch_mode;
+ return 1;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name VertFormat Type
* \{ */
static PyObject *bpygpu_VertFormat_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
- if (PyTuple_GET_SIZE(args) || (kwds && PyDict_Size(kwds))) {
- PyErr_SetString(PyExc_ValueError, "This function takes no arguments");
- return NULL;
- }
- return BPyGPUVertFormat_CreatePyObject(NULL);
+ if (PyTuple_GET_SIZE(args) || (kwds && PyDict_Size(kwds))) {
+ PyErr_SetString(PyExc_ValueError, "This function takes no arguments");
+ return NULL;
+ }
+ return BPyGPUVertFormat_CreatePyObject(NULL);
}
-PyDoc_STRVAR(bpygpu_VertFormat_attr_add_doc,
-".. method:: attr_add(id, comp_type, len, fetch_mode)\n"
-"\n"
-" Add a new attribute to the format.\n"
-"\n"
-" :param id: Name the attribute. Often `position`, `normal`, ...\n"
-" :type id: str\n"
-" :param comp_type: The data type that will be used store the value in memory.\n"
-" Possible values are `I8`, `U8`, `I16`, `U16`, `I32`, `U32`, `F32` and `I10`.\n"
-" :type comp_type: `str`\n"
-" :param len: How many individual values the attribute consists of (e.g. 2 for uv coordinates).\n"
-" :type len: int\n"
-" :param fetch_mode: How values from memory will be converted when used in the shader.\n"
-" This is mainly useful for memory optimizations when you want to store values with reduced precision.\n"
-" E.g. you can store a float in only 1 byte but it will be converted to a normal 4 byte float when used.\n"
-" Possible values are `FLOAT`, `INT`, `INT_TO_FLOAT_UNIT` and `INT_TO_FLOAT`.\n"
-" :type fetch_mode: `str`\n"
-);
+PyDoc_STRVAR(
+ bpygpu_VertFormat_attr_add_doc,
+ ".. method:: attr_add(id, comp_type, len, fetch_mode)\n"
+ "\n"
+ " Add a new attribute to the format.\n"
+ "\n"
+ " :param id: Name the attribute. Often `position`, `normal`, ...\n"
+ " :type id: str\n"
+ " :param comp_type: The data type that will be used store the value in memory.\n"
+ " Possible values are `I8`, `U8`, `I16`, `U16`, `I32`, `U32`, `F32` and `I10`.\n"
+ " :type comp_type: `str`\n"
+ " :param len: How many individual values the attribute consists of (e.g. 2 for uv "
+ "coordinates).\n"
+ " :type len: int\n"
+ " :param fetch_mode: How values from memory will be converted when used in the shader.\n"
+ " This is mainly useful for memory optimizations when you want to store values with "
+ "reduced precision.\n"
+ " E.g. you can store a float in only 1 byte but it will be converted to a normal 4 byte "
+ "float when used.\n"
+ " Possible values are `FLOAT`, `INT`, `INT_TO_FLOAT_UNIT` and `INT_TO_FLOAT`.\n"
+ " :type fetch_mode: `str`\n");
static PyObject *bpygpu_VertFormat_attr_add(BPyGPUVertFormat *self, PyObject *args, PyObject *kwds)
{
- struct {
- const char *id;
- GPUVertCompType comp_type;
- uint len;
- GPUVertFetchMode fetch_mode;
- } params;
-
- if (self->fmt.attr_len == GPU_VERT_ATTR_MAX_LEN) {
- PyErr_SetString(PyExc_ValueError, "Maxumum attr reached " STRINGIFY(GPU_VERT_ATTR_MAX_LEN));
- return NULL;
- }
-
- static const char *_keywords[] = {"id", "comp_type", "len", "fetch_mode", NULL};
- static _PyArg_Parser _parser = {"$sO&IO&:attr_add", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &params.id,
- bpygpu_ParseVertCompType, &params.comp_type,
- &params.len,
- bpygpu_ParseVertFetchMode, &params.fetch_mode))
- {
- return NULL;
- }
-
- uint attr_id = GPU_vertformat_attr_add(&self->fmt, params.id, params.comp_type, params.len, params.fetch_mode);
- return PyLong_FromLong(attr_id);
+ struct {
+ const char *id;
+ GPUVertCompType comp_type;
+ uint len;
+ GPUVertFetchMode fetch_mode;
+ } params;
+
+ if (self->fmt.attr_len == GPU_VERT_ATTR_MAX_LEN) {
+ PyErr_SetString(PyExc_ValueError, "Maxumum attr reached " STRINGIFY(GPU_VERT_ATTR_MAX_LEN));
+ return NULL;
+ }
+
+ static const char *_keywords[] = {"id", "comp_type", "len", "fetch_mode", NULL};
+ static _PyArg_Parser _parser = {"$sO&IO&:attr_add", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kwds,
+ &_parser,
+ &params.id,
+ bpygpu_ParseVertCompType,
+ &params.comp_type,
+ &params.len,
+ bpygpu_ParseVertFetchMode,
+ &params.fetch_mode)) {
+ return NULL;
+ }
+
+ uint attr_id = GPU_vertformat_attr_add(
+ &self->fmt, params.id, params.comp_type, params.len, params.fetch_mode);
+ return PyLong_FromLong(attr_id);
}
static struct PyMethodDef bpygpu_VertFormat_methods[] = {
- {"attr_add", (PyCFunction)bpygpu_VertFormat_attr_add,
- METH_VARARGS | METH_KEYWORDS, bpygpu_VertFormat_attr_add_doc},
- {NULL, NULL, 0, NULL},
+ {"attr_add",
+ (PyCFunction)bpygpu_VertFormat_attr_add,
+ METH_VARARGS | METH_KEYWORDS,
+ bpygpu_VertFormat_attr_add_doc},
+ {NULL, NULL, 0, NULL},
};
-
static void bpygpu_VertFormat_dealloc(BPyGPUVertFormat *self)
{
- Py_TYPE(self)->tp_free(self);
+ Py_TYPE(self)->tp_free(self);
}
PyDoc_STRVAR(bpygpu_VertFormat_doc,
-".. class:: GPUVertFormat()\n"
-"\n"
-" This object contains information about the structure of a vertex buffer.\n"
-);
+ ".. class:: GPUVertFormat()\n"
+ "\n"
+ " This object contains information about the structure of a vertex buffer.\n");
PyTypeObject BPyGPUVertFormat_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- .tp_name = "GPUVertFormat",
- .tp_basicsize = sizeof(BPyGPUVertFormat),
- .tp_dealloc = (destructor)bpygpu_VertFormat_dealloc,
- .tp_flags = Py_TPFLAGS_DEFAULT,
- .tp_doc = bpygpu_VertFormat_doc,
- .tp_methods = bpygpu_VertFormat_methods,
- .tp_new = bpygpu_VertFormat_new,
+ PyVarObject_HEAD_INIT(NULL, 0).tp_name = "GPUVertFormat",
+ .tp_basicsize = sizeof(BPyGPUVertFormat),
+ .tp_dealloc = (destructor)bpygpu_VertFormat_dealloc,
+ .tp_flags = Py_TPFLAGS_DEFAULT,
+ .tp_doc = bpygpu_VertFormat_doc,
+ .tp_methods = bpygpu_VertFormat_methods,
+ .tp_new = bpygpu_VertFormat_new,
};
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Public API
* \{ */
PyObject *BPyGPUVertFormat_CreatePyObject(GPUVertFormat *fmt)
{
- BPyGPUVertFormat *self;
+ BPyGPUVertFormat *self;
- self = PyObject_New(BPyGPUVertFormat, &BPyGPUVertFormat_Type);
- if (fmt) {
- self->fmt = *fmt;
- }
- else {
- memset(&self->fmt, 0, sizeof(self->fmt));
- }
+ self = PyObject_New(BPyGPUVertFormat, &BPyGPUVertFormat_Type);
+ if (fmt) {
+ self->fmt = *fmt;
+ }
+ else {
+ memset(&self->fmt, 0, sizeof(self->fmt));
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
/** \} */
diff --git a/source/blender/python/gpu/gpu_py_vertex_format.h b/source/blender/python/gpu/gpu_py_vertex_format.h
index ba09c055aca..8ef466aa918 100644
--- a/source/blender/python/gpu/gpu_py_vertex_format.h
+++ b/source/blender/python/gpu/gpu_py_vertex_format.h
@@ -25,11 +25,10 @@
extern PyTypeObject BPyGPUVertFormat_Type;
-#define BPyGPUVertFormat_Check(v) (Py_TYPE(v) == &BPyGPUVertFormat_Type)
+#define BPyGPUVertFormat_Check(v) (Py_TYPE(v) == &BPyGPUVertFormat_Type)
typedef struct BPyGPUVertFormat {
- PyObject_VAR_HEAD
- struct GPUVertFormat fmt;
+ PyObject_VAR_HEAD struct GPUVertFormat fmt;
} BPyGPUVertFormat;
PyObject *BPyGPUVertFormat_CreatePyObject(struct GPUVertFormat *fmt);
diff --git a/source/blender/python/intern/CMakeLists.txt b/source/blender/python/intern/CMakeLists.txt
index 95f3edb8045..7eb008efeef 100644
--- a/source/blender/python/intern/CMakeLists.txt
+++ b/source/blender/python/intern/CMakeLists.txt
@@ -19,293 +19,293 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- ..
- ../../blenkernel
- ../../blenlib
- ../../blenloader
- ../../blentranslation
- ../../editors/include
- ../../gpu
- ../../imbuf
- ../../makesdna
- ../../makesrna
- ../../windowmanager
- ../../../../intern/clog
- ../../../../intern/guardedalloc
- ../../../../intern/opencolorio
+ ..
+ ../../blenkernel
+ ../../blenlib
+ ../../blenloader
+ ../../blentranslation
+ ../../editors/include
+ ../../gpu
+ ../../imbuf
+ ../../makesdna
+ ../../makesrna
+ ../../windowmanager
+ ../../../../intern/clog
+ ../../../../intern/guardedalloc
+ ../../../../intern/opencolorio
)
set(INC_SYS
- ${PYTHON_INCLUDE_DIRS}
+ ${PYTHON_INCLUDE_DIRS}
)
set(SRC
- bpy.c
- bpy_app.c
- bpy_app_alembic.c
- bpy_app_build_options.c
- bpy_app_ffmpeg.c
- bpy_app_handlers.c
- bpy_app_icons.c
- bpy_app_ocio.c
- bpy_app_oiio.c
- bpy_app_opensubdiv.c
- bpy_app_openvdb.c
- bpy_app_sdl.c
- bpy_app_timers.c
- bpy_app_translations.c
- bpy_capi_utils.c
- bpy_driver.c
- bpy_gizmo_wrap.c
- bpy_interface.c
- bpy_interface_atexit.c
- bpy_intern_string.c
- bpy_library_load.c
- bpy_library_write.c
- bpy_msgbus.c
- bpy_operator.c
- bpy_operator_wrap.c
- bpy_path.c
- bpy_props.c
- bpy_rna.c
- bpy_rna_anim.c
- bpy_rna_array.c
- bpy_rna_callback.c
- bpy_rna_driver.c
- bpy_rna_gizmo.c
- bpy_rna_id_collection.c
- bpy_traceback.c
- bpy_utils_previews.c
- bpy_utils_units.c
- stubs.c
-
- bpy.h
- bpy_app.h
- bpy_app_alembic.h
- bpy_app_build_options.h
- bpy_app_ffmpeg.h
- bpy_app_handlers.h
- bpy_app_icons.h
- bpy_app_ocio.h
- bpy_app_oiio.h
- bpy_app_opensubdiv.h
- bpy_app_openvdb.h
- bpy_app_sdl.h
- bpy_app_timers.h
- bpy_app_translations.h
- bpy_capi_utils.h
- bpy_driver.h
- bpy_gizmo_wrap.h
- bpy_intern_string.h
- bpy_library.h
- bpy_msgbus.h
- bpy_operator.h
- bpy_operator_wrap.h
- bpy_path.h
- bpy_props.h
- bpy_rna.h
- bpy_rna_anim.h
- bpy_rna_callback.h
- bpy_rna_driver.h
- bpy_rna_gizmo.h
- bpy_rna_id_collection.h
- bpy_traceback.h
- bpy_utils_previews.h
- bpy_utils_units.h
- ../BPY_extern.h
- ../BPY_extern_clog.h
+ bpy.c
+ bpy_app.c
+ bpy_app_alembic.c
+ bpy_app_build_options.c
+ bpy_app_ffmpeg.c
+ bpy_app_handlers.c
+ bpy_app_icons.c
+ bpy_app_ocio.c
+ bpy_app_oiio.c
+ bpy_app_opensubdiv.c
+ bpy_app_openvdb.c
+ bpy_app_sdl.c
+ bpy_app_timers.c
+ bpy_app_translations.c
+ bpy_capi_utils.c
+ bpy_driver.c
+ bpy_gizmo_wrap.c
+ bpy_interface.c
+ bpy_interface_atexit.c
+ bpy_intern_string.c
+ bpy_library_load.c
+ bpy_library_write.c
+ bpy_msgbus.c
+ bpy_operator.c
+ bpy_operator_wrap.c
+ bpy_path.c
+ bpy_props.c
+ bpy_rna.c
+ bpy_rna_anim.c
+ bpy_rna_array.c
+ bpy_rna_callback.c
+ bpy_rna_driver.c
+ bpy_rna_gizmo.c
+ bpy_rna_id_collection.c
+ bpy_traceback.c
+ bpy_utils_previews.c
+ bpy_utils_units.c
+ stubs.c
+
+ bpy.h
+ bpy_app.h
+ bpy_app_alembic.h
+ bpy_app_build_options.h
+ bpy_app_ffmpeg.h
+ bpy_app_handlers.h
+ bpy_app_icons.h
+ bpy_app_ocio.h
+ bpy_app_oiio.h
+ bpy_app_opensubdiv.h
+ bpy_app_openvdb.h
+ bpy_app_sdl.h
+ bpy_app_timers.h
+ bpy_app_translations.h
+ bpy_capi_utils.h
+ bpy_driver.h
+ bpy_gizmo_wrap.h
+ bpy_intern_string.h
+ bpy_library.h
+ bpy_msgbus.h
+ bpy_operator.h
+ bpy_operator_wrap.h
+ bpy_path.h
+ bpy_props.h
+ bpy_rna.h
+ bpy_rna_anim.h
+ bpy_rna_callback.h
+ bpy_rna_driver.h
+ bpy_rna_gizmo.h
+ bpy_rna_id_collection.h
+ bpy_traceback.h
+ bpy_utils_previews.h
+ bpy_utils_units.h
+ ../BPY_extern.h
+ ../BPY_extern_clog.h
)
set(LIB
- bf_editor_animation
- bf_editor_interface
- bf_editor_space_api
- bf_python_gpu
+ bf_editor_animation
+ bf_editor_interface
+ bf_editor_space_api
+ bf_python_gpu
)
# only to check if buildinfo is available
if(WITH_BUILDINFO)
- add_definitions(-DBUILD_DATE)
+ add_definitions(-DBUILD_DATE)
endif()
if(WITH_PYTHON_MODULE)
- add_definitions(-DWITH_PYTHON_MODULE)
+ add_definitions(-DWITH_PYTHON_MODULE)
endif()
if(WITH_PYTHON_SAFETY)
- add_definitions(-DWITH_PYTHON_SAFETY)
+ add_definitions(-DWITH_PYTHON_SAFETY)
endif()
if(WITH_AUDASPACE)
- add_definitions(-DWITH_AUDASPACE)
+ add_definitions(-DWITH_AUDASPACE)
endif()
if(WITH_BULLET)
- add_definitions(-DWITH_BULLET)
+ add_definitions(-DWITH_BULLET)
endif()
if(WITH_CODEC_AVI)
- add_definitions(-DWITH_AVI)
+ add_definitions(-DWITH_AVI)
endif()
if(WITH_CODEC_FFMPEG)
- list(APPEND INC_SYS
- ${FFMPEG_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_FFMPEG)
+ list(APPEND INC_SYS
+ ${FFMPEG_INCLUDE_DIRS}
+ )
+ add_definitions(-DWITH_FFMPEG)
endif()
if(WITH_CODEC_SNDFILE)
- add_definitions(-DWITH_SNDFILE)
+ add_definitions(-DWITH_SNDFILE)
endif()
if(WITH_COMPOSITOR)
- add_definitions(-DWITH_COMPOSITOR)
+ add_definitions(-DWITH_COMPOSITOR)
endif()
if(WITH_CYCLES)
- list(APPEND INC
- ../../../../intern/cycles/blender
- )
- list(APPEND LIB
- bf_intern_cycles
- )
- add_definitions(-DWITH_CYCLES)
+ list(APPEND INC
+ ../../../../intern/cycles/blender
+ )
+ list(APPEND LIB
+ bf_intern_cycles
+ )
+ add_definitions(-DWITH_CYCLES)
endif()
if(WITH_CYCLES_OSL)
- add_definitions(-DWITH_CYCLES_OSL)
+ add_definitions(-DWITH_CYCLES_OSL)
endif()
if(WITH_CYCLES_EMBREE)
- add_definitions(-DWITH_CYCLES_EMBREE)
+ add_definitions(-DWITH_CYCLES_EMBREE)
endif()
if(WITH_FREESTYLE)
- list(APPEND INC
- ../../freestyle/intern/python
- )
- add_definitions(-DWITH_FREESTYLE)
+ list(APPEND INC
+ ../../freestyle/intern/python
+ )
+ add_definitions(-DWITH_FREESTYLE)
endif()
if(WITH_IMAGE_CINEON)
- add_definitions(-DWITH_CINEON)
+ add_definitions(-DWITH_CINEON)
endif()
if(WITH_IMAGE_DDS)
- add_definitions(-DWITH_DDS)
+ add_definitions(-DWITH_DDS)
endif()
if(WITH_IMAGE_HDR)
- add_definitions(-DWITH_HDR)
+ add_definitions(-DWITH_HDR)
endif()
if(WITH_IMAGE_OPENEXR)
- add_definitions(-DWITH_OPENEXR)
+ add_definitions(-DWITH_OPENEXR)
endif()
if(WITH_OPENIMAGEIO)
- add_definitions(-DWITH_OPENIMAGEIO)
+ add_definitions(-DWITH_OPENIMAGEIO)
endif()
if(WITH_IMAGE_OPENJPEG)
- add_definitions(-DWITH_OPENJPEG)
+ add_definitions(-DWITH_OPENJPEG)
endif()
if(WITH_IMAGE_TIFF)
- add_definitions(-DWITH_TIFF)
+ add_definitions(-DWITH_TIFF)
endif()
if(WITH_INPUT_NDOF)
- add_definitions(-DWITH_INPUT_NDOF)
+ add_definitions(-DWITH_INPUT_NDOF)
endif()
if(WITH_INTERNATIONAL)
- add_definitions(-DWITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
endif()
if(WITH_OPENAL)
- add_definitions(-DWITH_OPENAL)
+ add_definitions(-DWITH_OPENAL)
endif()
if(WITH_SDL)
- list(APPEND INC_SYS
- ${SDL_INCLUDE_DIR}
- )
- add_definitions(-DWITH_SDL)
+ list(APPEND INC_SYS
+ ${SDL_INCLUDE_DIR}
+ )
+ add_definitions(-DWITH_SDL)
endif()
if(WITH_SDL_DYNLOAD)
- list(APPEND INC
- ../../../../extern/sdlew/include
- )
- add_definitions(-DWITH_SDL_DYNLOAD)
+ list(APPEND INC
+ ../../../../extern/sdlew/include
+ )
+ add_definitions(-DWITH_SDL_DYNLOAD)
endif()
if(WITH_JACK)
- add_definitions(-DWITH_JACK)
+ add_definitions(-DWITH_JACK)
endif()
if(WITH_LIBMV)
- add_definitions(-DWITH_LIBMV)
+ add_definitions(-DWITH_LIBMV)
endif()
if(WITH_MOD_FLUID)
- add_definitions(-DWITH_MOD_FLUID)
+ add_definitions(-DWITH_MOD_FLUID)
endif()
if(WITH_MOD_OCEANSIM)
- add_definitions(-DWITH_OCEANSIM)
+ add_definitions(-DWITH_OCEANSIM)
endif()
if(WITH_MOD_REMESH)
- add_definitions(-DWITH_MOD_REMESH)
+ add_definitions(-DWITH_MOD_REMESH)
endif()
if(WITH_MOD_SMOKE)
- add_definitions(-DWITH_SMOKE)
+ add_definitions(-DWITH_SMOKE)
endif()
if(WITH_OPENCOLLADA)
- add_definitions(-DWITH_COLLADA)
+ add_definitions(-DWITH_COLLADA)
endif()
if(WITH_ALEMBIC)
- add_definitions(-DWITH_ALEMBIC)
+ add_definitions(-DWITH_ALEMBIC)
endif()
if(WITH_OPENCOLORIO)
- add_definitions(-DWITH_OCIO)
+ add_definitions(-DWITH_OCIO)
endif()
if(WITH_OPENVDB)
- add_definitions(-DWITH_OPENVDB)
- list(APPEND INC
- ../../../../intern/openvdb
- )
+ add_definitions(-DWITH_OPENVDB)
+ list(APPEND INC
+ ../../../../intern/openvdb
+ )
endif()
if(WITH_ALEMBIC)
- add_definitions(-DWITH_ALEMBIC)
- list(APPEND INC
- ../../alembic
- )
+ add_definitions(-DWITH_ALEMBIC)
+ list(APPEND INC
+ ../../alembic
+ )
endif()
if(WITH_OPENIMAGEIO)
- add_definitions(-DWITH_OPENIMAGEIO)
- list(APPEND INC
- ../../imbuf/intern/oiio
- )
+ add_definitions(-DWITH_OPENIMAGEIO)
+ list(APPEND INC
+ ../../imbuf/intern/oiio
+ )
endif()
if(WITH_OPENSUBDIV)
- add_definitions(-DWITH_OPENSUBDIV)
- list(APPEND INC
- ../../../../intern/opensubdiv
- )
+ add_definitions(-DWITH_OPENSUBDIV)
+ list(APPEND INC
+ ../../../../intern/opensubdiv
+ )
endif()
add_definitions(${GL_DEFINITIONS})
diff --git a/source/blender/python/intern/bpy.c b/source/blender/python/intern/bpy.c
index f67ed1a3713..ed576c553e4 100644
--- a/source/blender/python/intern/bpy.c
+++ b/source/blender/python/intern/bpy.c
@@ -61,320 +61,347 @@
PyObject *bpy_package_py = NULL;
PyDoc_STRVAR(bpy_script_paths_doc,
-".. function:: script_paths()\n"
-"\n"
-" Return 2 paths to blender scripts directories.\n"
-"\n"
-" :return: (system, user) strings will be empty when not found.\n"
-" :rtype: tuple of strings\n"
-);
+ ".. function:: script_paths()\n"
+ "\n"
+ " Return 2 paths to blender scripts directories.\n"
+ "\n"
+ " :return: (system, user) strings will be empty when not found.\n"
+ " :rtype: tuple of strings\n");
static PyObject *bpy_script_paths(PyObject *UNUSED(self))
{
- PyObject *ret = PyTuple_New(2);
- PyObject *item;
- const char *path;
-
- path = BKE_appdir_folder_id(BLENDER_SYSTEM_SCRIPTS, NULL);
- item = PyC_UnicodeFromByte(path ? path : "");
- BLI_assert(item != NULL);
- PyTuple_SET_ITEM(ret, 0, item);
- path = BKE_appdir_folder_id(BLENDER_USER_SCRIPTS, NULL);
- item = PyC_UnicodeFromByte(path ? path : "");
- BLI_assert(item != NULL);
- PyTuple_SET_ITEM(ret, 1, item);
-
- return ret;
+ PyObject *ret = PyTuple_New(2);
+ PyObject *item;
+ const char *path;
+
+ path = BKE_appdir_folder_id(BLENDER_SYSTEM_SCRIPTS, NULL);
+ item = PyC_UnicodeFromByte(path ? path : "");
+ BLI_assert(item != NULL);
+ PyTuple_SET_ITEM(ret, 0, item);
+ path = BKE_appdir_folder_id(BLENDER_USER_SCRIPTS, NULL);
+ item = PyC_UnicodeFromByte(path ? path : "");
+ BLI_assert(item != NULL);
+ PyTuple_SET_ITEM(ret, 1, item);
+
+ return ret;
}
static bool bpy_blend_paths_visit_cb(void *userdata, char *UNUSED(path_dst), const char *path_src)
{
- PyList_APPEND((PyObject *)userdata, PyC_UnicodeFromByte(path_src));
- return false; /* never edits the path */
+ PyList_APPEND((PyObject *)userdata, PyC_UnicodeFromByte(path_src));
+ return false; /* never edits the path */
}
PyDoc_STRVAR(bpy_blend_paths_doc,
-".. function:: blend_paths(absolute=False, packed=False, local=False)\n"
-"\n"
-" Returns a list of paths to external files referenced by the loaded .blend file.\n"
-"\n"
-" :arg absolute: When true the paths returned are made absolute.\n"
-" :type absolute: boolean\n"
-" :arg packed: When true skip file paths for packed data.\n"
-" :type packed: boolean\n"
-" :arg local: When true skip linked library paths.\n"
-" :type local: boolean\n"
-" :return: path list.\n"
-" :rtype: list of strings\n"
-);
+ ".. function:: blend_paths(absolute=False, packed=False, local=False)\n"
+ "\n"
+ " Returns a list of paths to external files referenced by the loaded .blend file.\n"
+ "\n"
+ " :arg absolute: When true the paths returned are made absolute.\n"
+ " :type absolute: boolean\n"
+ " :arg packed: When true skip file paths for packed data.\n"
+ " :type packed: boolean\n"
+ " :arg local: When true skip linked library paths.\n"
+ " :type local: boolean\n"
+ " :return: path list.\n"
+ " :rtype: list of strings\n");
static PyObject *bpy_blend_paths(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- int flag = 0;
- PyObject *list;
-
- bool absolute = false;
- bool packed = false;
- bool local = false;
-
- static const char *_keywords[] = {"absolute", "packed", "local", NULL};
- static _PyArg_Parser _parser = {"|O&O&O&:blend_paths", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- PyC_ParseBool, &absolute,
- PyC_ParseBool, &packed,
- PyC_ParseBool, &local))
- {
- return NULL;
- }
-
- if (absolute) {
- flag |= BKE_BPATH_TRAVERSE_ABS;
- }
- if (!packed) {
- flag |= BKE_BPATH_TRAVERSE_SKIP_PACKED;
- }
- if (local) {
- flag |= BKE_BPATH_TRAVERSE_SKIP_LIBRARY;
- }
-
- list = PyList_New(0);
-
- BKE_bpath_traverse_main(G_MAIN, bpy_blend_paths_visit_cb, flag, (void *)list);
-
- return list;
+ int flag = 0;
+ PyObject *list;
+
+ bool absolute = false;
+ bool packed = false;
+ bool local = false;
+
+ static const char *_keywords[] = {"absolute", "packed", "local", NULL};
+ static _PyArg_Parser _parser = {"|O&O&O&:blend_paths", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ PyC_ParseBool,
+ &absolute,
+ PyC_ParseBool,
+ &packed,
+ PyC_ParseBool,
+ &local)) {
+ return NULL;
+ }
+
+ if (absolute) {
+ flag |= BKE_BPATH_TRAVERSE_ABS;
+ }
+ if (!packed) {
+ flag |= BKE_BPATH_TRAVERSE_SKIP_PACKED;
+ }
+ if (local) {
+ flag |= BKE_BPATH_TRAVERSE_SKIP_LIBRARY;
+ }
+
+ list = PyList_New(0);
+
+ BKE_bpath_traverse_main(G_MAIN, bpy_blend_paths_visit_cb, flag, (void *)list);
+
+ return list;
}
-
// PyDoc_STRVAR(bpy_user_resource_doc[] = // now in bpy/utils.py
static PyObject *bpy_user_resource(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- const char *type;
- const char *subdir = NULL;
- int folder_id;
-
- const char *path;
-
- static const char *_keywords[] = {"type", "subdir", NULL};
- static _PyArg_Parser _parser = {"s|s:user_resource", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &type, &subdir))
- {
- return NULL;
- }
-
- /* stupid string compare */
- if (STREQ(type, "DATAFILES")) { folder_id = BLENDER_USER_DATAFILES; }
- else if (STREQ(type, "CONFIG")) { folder_id = BLENDER_USER_CONFIG; }
- else if (STREQ(type, "SCRIPTS")) { folder_id = BLENDER_USER_SCRIPTS; }
- else if (STREQ(type, "AUTOSAVE")) { folder_id = BLENDER_USER_AUTOSAVE; }
- else {
- PyErr_SetString(PyExc_ValueError, "invalid resource argument");
- return NULL;
- }
-
- /* same logic as BKE_appdir_folder_id_create(), but best leave it up to the script author to create */
- path = BKE_appdir_folder_id_user_notest(folder_id, subdir);
-
- return PyC_UnicodeFromByte(path ? path : "");
+ const char *type;
+ const char *subdir = NULL;
+ int folder_id;
+
+ const char *path;
+
+ static const char *_keywords[] = {"type", "subdir", NULL};
+ static _PyArg_Parser _parser = {"s|s:user_resource", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &type, &subdir)) {
+ return NULL;
+ }
+
+ /* stupid string compare */
+ if (STREQ(type, "DATAFILES")) {
+ folder_id = BLENDER_USER_DATAFILES;
+ }
+ else if (STREQ(type, "CONFIG")) {
+ folder_id = BLENDER_USER_CONFIG;
+ }
+ else if (STREQ(type, "SCRIPTS")) {
+ folder_id = BLENDER_USER_SCRIPTS;
+ }
+ else if (STREQ(type, "AUTOSAVE")) {
+ folder_id = BLENDER_USER_AUTOSAVE;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "invalid resource argument");
+ return NULL;
+ }
+
+ /* same logic as BKE_appdir_folder_id_create(), but best leave it up to the script author to create */
+ path = BKE_appdir_folder_id_user_notest(folder_id, subdir);
+
+ return PyC_UnicodeFromByte(path ? path : "");
}
-PyDoc_STRVAR(bpy_resource_path_doc,
-".. function:: resource_path(type, major=bpy.app.version[0], minor=bpy.app.version[1])\n"
-"\n"
-" Return the base path for storing system files.\n"
-"\n"
-" :arg type: string in ['USER', 'LOCAL', 'SYSTEM'].\n"
-" :type type: string\n"
-" :arg major: major version, defaults to current.\n"
-" :type major: int\n"
-" :arg minor: minor version, defaults to current.\n"
-" :type minor: string\n"
-" :return: the resource path (not necessarily existing).\n"
-" :rtype: string\n"
-);
+PyDoc_STRVAR(
+ bpy_resource_path_doc,
+ ".. function:: resource_path(type, major=bpy.app.version[0], minor=bpy.app.version[1])\n"
+ "\n"
+ " Return the base path for storing system files.\n"
+ "\n"
+ " :arg type: string in ['USER', 'LOCAL', 'SYSTEM'].\n"
+ " :type type: string\n"
+ " :arg major: major version, defaults to current.\n"
+ " :type major: int\n"
+ " :arg minor: minor version, defaults to current.\n"
+ " :type minor: string\n"
+ " :return: the resource path (not necessarily existing).\n"
+ " :rtype: string\n");
static PyObject *bpy_resource_path(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- const char *type;
- int major = BLENDER_VERSION / 100, minor = BLENDER_VERSION % 100;
- int folder_id;
- const char *path;
-
- static const char *_keywords[] = {"type", "major", "minor", NULL};
- static _PyArg_Parser _parser = {"s|ii:resource_path", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &type, &major, &minor))
- {
- return NULL;
- }
-
- /* stupid string compare */
- if (STREQ(type, "USER")) { folder_id = BLENDER_RESOURCE_PATH_USER; }
- else if (STREQ(type, "LOCAL")) { folder_id = BLENDER_RESOURCE_PATH_LOCAL; }
- else if (STREQ(type, "SYSTEM")) { folder_id = BLENDER_RESOURCE_PATH_SYSTEM; }
- else {
- PyErr_SetString(PyExc_ValueError, "invalid resource argument");
- return NULL;
- }
-
- path = BKE_appdir_folder_id_version(folder_id, (major * 100) + minor, false);
-
- return PyC_UnicodeFromByte(path ? path : "");
+ const char *type;
+ int major = BLENDER_VERSION / 100, minor = BLENDER_VERSION % 100;
+ int folder_id;
+ const char *path;
+
+ static const char *_keywords[] = {"type", "major", "minor", NULL};
+ static _PyArg_Parser _parser = {"s|ii:resource_path", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &type, &major, &minor)) {
+ return NULL;
+ }
+
+ /* stupid string compare */
+ if (STREQ(type, "USER")) {
+ folder_id = BLENDER_RESOURCE_PATH_USER;
+ }
+ else if (STREQ(type, "LOCAL")) {
+ folder_id = BLENDER_RESOURCE_PATH_LOCAL;
+ }
+ else if (STREQ(type, "SYSTEM")) {
+ folder_id = BLENDER_RESOURCE_PATH_SYSTEM;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "invalid resource argument");
+ return NULL;
+ }
+
+ path = BKE_appdir_folder_id_version(folder_id, (major * 100) + minor, false);
+
+ return PyC_UnicodeFromByte(path ? path : "");
}
PyDoc_STRVAR(bpy_escape_identifier_doc,
-".. function:: escape_identifier(string)\n"
-"\n"
-" Simple string escaping function used for animation paths.\n"
-"\n"
-" :arg string: text\n"
-" :type string: string\n"
-" :return: The escaped string.\n"
-" :rtype: string\n"
-);
+ ".. function:: escape_identifier(string)\n"
+ "\n"
+ " Simple string escaping function used for animation paths.\n"
+ "\n"
+ " :arg string: text\n"
+ " :type string: string\n"
+ " :return: The escaped string.\n"
+ " :rtype: string\n");
static PyObject *bpy_escape_identifier(PyObject *UNUSED(self), PyObject *value)
{
- const char *value_str;
- Py_ssize_t value_str_len;
+ const char *value_str;
+ Py_ssize_t value_str_len;
- char *value_escape_str;
- Py_ssize_t value_escape_str_len;
- PyObject *value_escape;
- size_t size;
+ char *value_escape_str;
+ Py_ssize_t value_escape_str_len;
+ PyObject *value_escape;
+ size_t size;
- value_str = _PyUnicode_AsStringAndSize(value, &value_str_len);
+ value_str = _PyUnicode_AsStringAndSize(value, &value_str_len);
- if (value_str == NULL) {
- PyErr_SetString(PyExc_TypeError, "expected a string");
- return NULL;
- }
+ if (value_str == NULL) {
+ PyErr_SetString(PyExc_TypeError, "expected a string");
+ return NULL;
+ }
- size = (value_str_len * 2) + 1;
- value_escape_str = PyMem_MALLOC(size);
- value_escape_str_len = BLI_strescape(value_escape_str, value_str, size);
+ size = (value_str_len * 2) + 1;
+ value_escape_str = PyMem_MALLOC(size);
+ value_escape_str_len = BLI_strescape(value_escape_str, value_str, size);
- if (value_escape_str_len == value_str_len) {
- Py_INCREF(value);
- value_escape = value;
- }
- else {
- value_escape = PyUnicode_FromStringAndSize(value_escape_str, value_escape_str_len);
- }
+ if (value_escape_str_len == value_str_len) {
+ Py_INCREF(value);
+ value_escape = value;
+ }
+ else {
+ value_escape = PyUnicode_FromStringAndSize(value_escape_str, value_escape_str_len);
+ }
- PyMem_FREE(value_escape_str);
+ PyMem_FREE(value_escape_str);
- return value_escape;
+ return value_escape;
}
-static PyMethodDef meth_bpy_script_paths =
- {"script_paths", (PyCFunction)bpy_script_paths, METH_NOARGS, bpy_script_paths_doc};
-static PyMethodDef meth_bpy_blend_paths =
- {"blend_paths", (PyCFunction)bpy_blend_paths, METH_VARARGS | METH_KEYWORDS, bpy_blend_paths_doc};
-static PyMethodDef meth_bpy_user_resource =
- {"user_resource", (PyCFunction)bpy_user_resource, METH_VARARGS | METH_KEYWORDS, NULL};
-static PyMethodDef meth_bpy_resource_path =
- {"resource_path", (PyCFunction)bpy_resource_path, METH_VARARGS | METH_KEYWORDS, bpy_resource_path_doc};
-static PyMethodDef meth_bpy_escape_identifier =
- {"escape_identifier", (PyCFunction)bpy_escape_identifier, METH_O, bpy_escape_identifier_doc};
+static PyMethodDef meth_bpy_script_paths = {
+ "script_paths", (PyCFunction)bpy_script_paths, METH_NOARGS, bpy_script_paths_doc};
+static PyMethodDef meth_bpy_blend_paths = {"blend_paths",
+ (PyCFunction)bpy_blend_paths,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_blend_paths_doc};
+static PyMethodDef meth_bpy_user_resource = {
+ "user_resource", (PyCFunction)bpy_user_resource, METH_VARARGS | METH_KEYWORDS, NULL};
+static PyMethodDef meth_bpy_resource_path = {"resource_path",
+ (PyCFunction)bpy_resource_path,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_resource_path_doc};
+static PyMethodDef meth_bpy_escape_identifier = {
+ "escape_identifier", (PyCFunction)bpy_escape_identifier, METH_O, bpy_escape_identifier_doc};
static PyObject *bpy_import_test(const char *modname)
{
- PyObject *mod = PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
- if (mod) {
- Py_DECREF(mod);
- }
- else {
- PyErr_Print();
- PyErr_Clear();
- }
-
- return mod;
+ PyObject *mod = PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
+ if (mod) {
+ Py_DECREF(mod);
+ }
+ else {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ return mod;
}
-
/******************************************************************************
* Description: Creates the bpy module and adds it to sys.modules for importing
******************************************************************************/
void BPy_init_modules(void)
{
- PointerRNA ctx_ptr;
- PyObject *mod;
-
- /* Needs to be first since this dir is needed for future modules */
- const char * const modpath = BKE_appdir_folder_id(BLENDER_SYSTEM_SCRIPTS, "modules");
- if (modpath) {
- // printf("bpy: found module path '%s'.\n", modpath);
- PyObject *sys_path = PySys_GetObject("path"); /* borrow */
- PyObject *py_modpath = PyUnicode_FromString(modpath);
- PyList_Insert(sys_path, 0, py_modpath); /* add first */
- Py_DECREF(py_modpath);
- }
- else {
- printf("bpy: couldnt find 'scripts/modules', blender probably wont start.\n");
- }
- /* stand alone utility modules not related to blender directly */
- IDProp_Init_Types(); /* not actually a submodule, just types */
+ PointerRNA ctx_ptr;
+ PyObject *mod;
+
+ /* Needs to be first since this dir is needed for future modules */
+ const char *const modpath = BKE_appdir_folder_id(BLENDER_SYSTEM_SCRIPTS, "modules");
+ if (modpath) {
+ // printf("bpy: found module path '%s'.\n", modpath);
+ PyObject *sys_path = PySys_GetObject("path"); /* borrow */
+ PyObject *py_modpath = PyUnicode_FromString(modpath);
+ PyList_Insert(sys_path, 0, py_modpath); /* add first */
+ Py_DECREF(py_modpath);
+ }
+ else {
+ printf("bpy: couldnt find 'scripts/modules', blender probably wont start.\n");
+ }
+ /* stand alone utility modules not related to blender directly */
+ IDProp_Init_Types(); /* not actually a submodule, just types */
#ifdef WITH_FREESTYLE
- Freestyle_Init();
+ Freestyle_Init();
#endif
- mod = PyModule_New("_bpy");
-
- /* add the module so we can import it */
- PyDict_SetItemString(PyImport_GetModuleDict(), "_bpy", mod);
- Py_DECREF(mod);
-
- /* run first, initializes rna types */
- BPY_rna_init();
-
- /* needs to be first so bpy_types can run */
- PyModule_AddObject(mod, "types", BPY_rna_types());
-
- /* needs to be first so bpy_types can run */
- BPY_library_load_module(mod);
- BPY_library_write_module(mod);
-
- BPY_rna_id_collection_module(mod);
-
- BPY_rna_gizmo_module(mod);
-
- bpy_import_test("bpy_types");
- PyModule_AddObject(mod, "data", BPY_rna_module()); /* imports bpy_types by running this */
- bpy_import_test("bpy_types");
- PyModule_AddObject(mod, "props", BPY_rna_props());
- /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
- PyModule_AddObject(mod, "ops", BPY_operator_module());
- PyModule_AddObject(mod, "app", BPY_app_struct());
- PyModule_AddObject(mod, "_utils_units", BPY_utils_units());
- PyModule_AddObject(mod, "_utils_previews", BPY_utils_previews_module());
- PyModule_AddObject(mod, "msgbus", BPY_msgbus_module());
-
- /* bpy context */
- RNA_pointer_create(NULL, &RNA_Context, (void *)BPy_GetContext(), &ctx_ptr);
- bpy_context_module = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ctx_ptr);
- /* odd that this is needed, 1 ref on creation and another for the module
- * but without we get a crash on exit */
- Py_INCREF(bpy_context_module);
-
- PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module);
-
- /* register bpy/rna classmethod callbacks */
- BPY_rna_register_cb();
-
- /* utility func's that have nowhere else to go */
- PyModule_AddObject(mod, meth_bpy_script_paths.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_script_paths, NULL));
- PyModule_AddObject(mod, meth_bpy_blend_paths.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_blend_paths, NULL));
- PyModule_AddObject(mod, meth_bpy_user_resource.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_user_resource, NULL));
- PyModule_AddObject(mod, meth_bpy_resource_path.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_resource_path, NULL));
- PyModule_AddObject(mod, meth_bpy_escape_identifier.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_escape_identifier, NULL));
-
- /* register funcs (bpy_rna.c) */
- PyModule_AddObject(mod, meth_bpy_register_class.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_register_class, NULL));
- PyModule_AddObject(mod, meth_bpy_unregister_class.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_unregister_class, NULL));
-
- PyModule_AddObject(mod, meth_bpy_owner_id_get.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_owner_id_get, NULL));
- PyModule_AddObject(mod, meth_bpy_owner_id_set.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_owner_id_set, NULL));
-
- /* add our own modules dir, this is a python package */
- bpy_package_py = bpy_import_test("bpy");
+ mod = PyModule_New("_bpy");
+
+ /* add the module so we can import it */
+ PyDict_SetItemString(PyImport_GetModuleDict(), "_bpy", mod);
+ Py_DECREF(mod);
+
+ /* run first, initializes rna types */
+ BPY_rna_init();
+
+ /* needs to be first so bpy_types can run */
+ PyModule_AddObject(mod, "types", BPY_rna_types());
+
+ /* needs to be first so bpy_types can run */
+ BPY_library_load_module(mod);
+ BPY_library_write_module(mod);
+
+ BPY_rna_id_collection_module(mod);
+
+ BPY_rna_gizmo_module(mod);
+
+ bpy_import_test("bpy_types");
+ PyModule_AddObject(mod, "data", BPY_rna_module()); /* imports bpy_types by running this */
+ bpy_import_test("bpy_types");
+ PyModule_AddObject(mod, "props", BPY_rna_props());
+ /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
+ PyModule_AddObject(mod, "ops", BPY_operator_module());
+ PyModule_AddObject(mod, "app", BPY_app_struct());
+ PyModule_AddObject(mod, "_utils_units", BPY_utils_units());
+ PyModule_AddObject(mod, "_utils_previews", BPY_utils_previews_module());
+ PyModule_AddObject(mod, "msgbus", BPY_msgbus_module());
+
+ /* bpy context */
+ RNA_pointer_create(NULL, &RNA_Context, (void *)BPy_GetContext(), &ctx_ptr);
+ bpy_context_module = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ctx_ptr);
+ /* odd that this is needed, 1 ref on creation and another for the module
+ * but without we get a crash on exit */
+ Py_INCREF(bpy_context_module);
+
+ PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module);
+
+ /* register bpy/rna classmethod callbacks */
+ BPY_rna_register_cb();
+
+ /* utility func's that have nowhere else to go */
+ PyModule_AddObject(mod,
+ meth_bpy_script_paths.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_script_paths, NULL));
+ PyModule_AddObject(
+ mod, meth_bpy_blend_paths.ml_name, (PyObject *)PyCFunction_New(&meth_bpy_blend_paths, NULL));
+ PyModule_AddObject(mod,
+ meth_bpy_user_resource.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_user_resource, NULL));
+ PyModule_AddObject(mod,
+ meth_bpy_resource_path.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_resource_path, NULL));
+ PyModule_AddObject(mod,
+ meth_bpy_escape_identifier.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_escape_identifier, NULL));
+
+ /* register funcs (bpy_rna.c) */
+ PyModule_AddObject(mod,
+ meth_bpy_register_class.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_register_class, NULL));
+ PyModule_AddObject(mod,
+ meth_bpy_unregister_class.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_unregister_class, NULL));
+
+ PyModule_AddObject(mod,
+ meth_bpy_owner_id_get.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_owner_id_get, NULL));
+ PyModule_AddObject(mod,
+ meth_bpy_owner_id_set.ml_name,
+ (PyObject *)PyCFunction_New(&meth_bpy_owner_id_set, NULL));
+
+ /* add our own modules dir, this is a python package */
+ bpy_package_py = bpy_import_test("bpy");
}
diff --git a/source/blender/python/intern/bpy.h b/source/blender/python/intern/bpy.h
index bd0212cb52a..88d1db6f8bc 100644
--- a/source/blender/python/intern/bpy.h
+++ b/source/blender/python/intern/bpy.h
@@ -31,4 +31,4 @@ void BPY_atexit_unregister(void);
extern struct CLG_LogRef *BPY_LOG_CONTEXT;
extern struct CLG_LogRef *BPY_LOG_RNA;
-#endif /* __BPY_H__ */
+#endif /* __BPY_H__ */
diff --git a/source/blender/python/intern/bpy_app.c b/source/blender/python/intern/bpy_app.c
index 2cd3086dae1..f0a3c7f4d5f 100644
--- a/source/blender/python/intern/bpy_app.c
+++ b/source/blender/python/intern/bpy_app.c
@@ -22,7 +22,6 @@
* however some writable variables have been added such as 'debug' and 'tempdir'
*/
-
#include <Python.h>
#include "bpy_app.h"
@@ -82,407 +81,504 @@ extern char build_system[];
static PyTypeObject BlenderAppType;
static PyStructSequence_Field app_info_fields[] = {
- {(char *)"version", (char *)"The Blender version as a tuple of 3 numbers. eg. (2, 50, 11)"},
- {(char *)"version_string", (char *)"The Blender version formatted as a string"},
- {(char *)"version_char", (char *)"The Blender version character (for minor releases)"},
- {(char *)"version_cycle", (char *)"The release status of this build alpha/beta/rc/release"},
- {(char *)"binary_path", (char *)"The location of blenders executable, useful for utilities that spawn new instances"},
- {(char *)"background", (char *)"Boolean, True when blender is running without a user interface (started with -b)"},
- {(char *)"factory_startup", (char *)"Boolean, True when blender is running with --factory-startup)"},
-
- /* buildinfo */
- {(char *)"build_date", (char *)"The date this blender instance was built"},
- {(char *)"build_time", (char *)"The time this blender instance was built"},
- {(char *)"build_commit_timestamp", (char *)"The unix timestamp of commit this blender instance was built"},
- {(char *)"build_commit_date", (char *)"The date of commit this blender instance was built"},
- {(char *)"build_commit_time", (char *)"The time of commit this blender instance was built"},
- {(char *)"build_hash", (char *)"The commit hash this blender instance was built with"},
- {(char *)"build_branch", (char *)"The branch this blender instance was built from"},
- {(char *)"build_platform", (char *)"The platform this blender instance was built for"},
- {(char *)"build_type", (char *)"The type of build (Release, Debug)"},
- {(char *)"build_cflags", (char *)"C compiler flags"},
- {(char *)"build_cxxflags", (char *)"C++ compiler flags"},
- {(char *)"build_linkflags", (char *)"Binary linking flags"},
- {(char *)"build_system", (char *)"Build system used"},
-
- /* submodules */
- {(char *)"alembic", (char *)"Alembic library information backend"},
- {(char *)"ffmpeg", (char *)"FFmpeg library information backend"},
- {(char *)"ocio", (char *)"OpenColorIO library information backend"},
- {(char *)"oiio", (char *)"OpenImageIO library information backend"},
- {(char *)"opensubdiv", (char *)"OpenSubdiv library information backend"},
- {(char *)"openvdb", (char *)"OpenVDB library information backend"},
- {(char *)"sdl", (char *)"SDL library information backend"},
- {(char *)"build_options", (char *)"A set containing most important enabled optional build features"},
- {(char *)"handlers", (char *)"Application handler callbacks"},
- {(char *)"translations", (char *)"Application and addons internationalization API"},
-
- /* Modules (not struct sequence). */
- {(char *)"icons", (char *)"Manage custom icons"},
- {(char *)"timers", (char *)"Manage timers"},
- {NULL},
+ {(char *)"version", (char *)"The Blender version as a tuple of 3 numbers. eg. (2, 50, 11)"},
+ {(char *)"version_string", (char *)"The Blender version formatted as a string"},
+ {(char *)"version_char", (char *)"The Blender version character (for minor releases)"},
+ {(char *)"version_cycle", (char *)"The release status of this build alpha/beta/rc/release"},
+ {(char *)"binary_path",
+ (char *)"The location of blenders executable, useful for utilities that spawn new instances"},
+ {(char *)"background",
+ (char *)"Boolean, True when blender is running without a user interface (started with -b)"},
+ {(char *)"factory_startup",
+ (char *)"Boolean, True when blender is running with --factory-startup)"},
+
+ /* buildinfo */
+ {(char *)"build_date", (char *)"The date this blender instance was built"},
+ {(char *)"build_time", (char *)"The time this blender instance was built"},
+ {(char *)"build_commit_timestamp",
+ (char *)"The unix timestamp of commit this blender instance was built"},
+ {(char *)"build_commit_date", (char *)"The date of commit this blender instance was built"},
+ {(char *)"build_commit_time", (char *)"The time of commit this blender instance was built"},
+ {(char *)"build_hash", (char *)"The commit hash this blender instance was built with"},
+ {(char *)"build_branch", (char *)"The branch this blender instance was built from"},
+ {(char *)"build_platform", (char *)"The platform this blender instance was built for"},
+ {(char *)"build_type", (char *)"The type of build (Release, Debug)"},
+ {(char *)"build_cflags", (char *)"C compiler flags"},
+ {(char *)"build_cxxflags", (char *)"C++ compiler flags"},
+ {(char *)"build_linkflags", (char *)"Binary linking flags"},
+ {(char *)"build_system", (char *)"Build system used"},
+
+ /* submodules */
+ {(char *)"alembic", (char *)"Alembic library information backend"},
+ {(char *)"ffmpeg", (char *)"FFmpeg library information backend"},
+ {(char *)"ocio", (char *)"OpenColorIO library information backend"},
+ {(char *)"oiio", (char *)"OpenImageIO library information backend"},
+ {(char *)"opensubdiv", (char *)"OpenSubdiv library information backend"},
+ {(char *)"openvdb", (char *)"OpenVDB library information backend"},
+ {(char *)"sdl", (char *)"SDL library information backend"},
+ {(char *)"build_options",
+ (char *)"A set containing most important enabled optional build features"},
+ {(char *)"handlers", (char *)"Application handler callbacks"},
+ {(char *)"translations", (char *)"Application and addons internationalization API"},
+
+ /* Modules (not struct sequence). */
+ {(char *)"icons", (char *)"Manage custom icons"},
+ {(char *)"timers", (char *)"Manage timers"},
+ {NULL},
};
PyDoc_STRVAR(bpy_app_doc,
-"This module contains application values that remain unchanged during runtime.\n"
-"\n"
-"Submodules:\n"
-"\n"
-".. toctree::\n"
-" :maxdepth: 1\n"
-"\n"
-" bpy.app.handlers.rst\n"
-" bpy.app.icons.rst\n"
-" bpy.app.timers.rst\n"
-" bpy.app.translations.rst\n"
-);
+ "This module contains application values that remain unchanged during runtime.\n"
+ "\n"
+ "Submodules:\n"
+ "\n"
+ ".. toctree::\n"
+ " :maxdepth: 1\n"
+ "\n"
+ " bpy.app.handlers.rst\n"
+ " bpy.app.icons.rst\n"
+ " bpy.app.timers.rst\n"
+ " bpy.app.translations.rst\n");
static PyStructSequence_Desc app_info_desc = {
- (char *)"bpy.app", /* name */
- bpy_app_doc, /* doc */
- app_info_fields, /* fields */
- ARRAY_SIZE(app_info_fields) - 1,
+ (char *)"bpy.app", /* name */
+ bpy_app_doc, /* doc */
+ app_info_fields, /* fields */
+ ARRAY_SIZE(app_info_fields) - 1,
};
static PyObject *make_app_info(void)
{
- PyObject *app_info;
- int pos = 0;
-
- app_info = PyStructSequence_New(&BlenderAppType);
- if (app_info == NULL) {
- return NULL;
- }
-#define SetIntItem(flag) \
- PyStructSequence_SET_ITEM(app_info, pos++, PyLong_FromLong(flag))
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(app_info, pos++, PyUnicode_FromString(str))
-#define SetBytesItem(str) \
- PyStructSequence_SET_ITEM(app_info, pos++, PyBytes_FromString(str))
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(app_info, pos++, obj)
-
- SetObjItem(PyC_Tuple_Pack_I32(BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
- SetObjItem(PyUnicode_FromFormat("%d.%02d (sub %d)",
- BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
-
- SetStrItem(STRINGIFY(BLENDER_VERSION_CHAR));
- SetStrItem(STRINGIFY(BLENDER_VERSION_CYCLE));
- SetStrItem(BKE_appdir_program_path());
- SetObjItem(PyBool_FromLong(G.background));
- SetObjItem(PyBool_FromLong(G.factory_startup));
-
- /* build info, use bytes since we can't assume _any_ encoding:
- * see patch [#30154] for issue */
+ PyObject *app_info;
+ int pos = 0;
+
+ app_info = PyStructSequence_New(&BlenderAppType);
+ if (app_info == NULL) {
+ return NULL;
+ }
+#define SetIntItem(flag) PyStructSequence_SET_ITEM(app_info, pos++, PyLong_FromLong(flag))
+#define SetStrItem(str) PyStructSequence_SET_ITEM(app_info, pos++, PyUnicode_FromString(str))
+#define SetBytesItem(str) PyStructSequence_SET_ITEM(app_info, pos++, PyBytes_FromString(str))
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(app_info, pos++, obj)
+
+ SetObjItem(PyC_Tuple_Pack_I32(BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
+ SetObjItem(PyUnicode_FromFormat(
+ "%d.%02d (sub %d)", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
+
+ SetStrItem(STRINGIFY(BLENDER_VERSION_CHAR));
+ SetStrItem(STRINGIFY(BLENDER_VERSION_CYCLE));
+ SetStrItem(BKE_appdir_program_path());
+ SetObjItem(PyBool_FromLong(G.background));
+ SetObjItem(PyBool_FromLong(G.factory_startup));
+
+ /* build info, use bytes since we can't assume _any_ encoding:
+ * see patch [#30154] for issue */
#ifdef BUILD_DATE
- SetBytesItem(build_date);
- SetBytesItem(build_time);
- SetIntItem(build_commit_timestamp);
- SetBytesItem(build_commit_date);
- SetBytesItem(build_commit_time);
- SetBytesItem(build_hash);
- SetBytesItem(build_branch);
- SetBytesItem(build_platform);
- SetBytesItem(build_type);
- SetBytesItem(build_cflags);
- SetBytesItem(build_cxxflags);
- SetBytesItem(build_linkflags);
- SetBytesItem(build_system);
+ SetBytesItem(build_date);
+ SetBytesItem(build_time);
+ SetIntItem(build_commit_timestamp);
+ SetBytesItem(build_commit_date);
+ SetBytesItem(build_commit_time);
+ SetBytesItem(build_hash);
+ SetBytesItem(build_branch);
+ SetBytesItem(build_platform);
+ SetBytesItem(build_type);
+ SetBytesItem(build_cflags);
+ SetBytesItem(build_cxxflags);
+ SetBytesItem(build_linkflags);
+ SetBytesItem(build_system);
#else
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetIntItem(0);
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
- SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetIntItem(0);
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
+ SetBytesItem("Unknown");
#endif
- SetObjItem(BPY_app_alembic_struct());
- SetObjItem(BPY_app_ffmpeg_struct());
- SetObjItem(BPY_app_ocio_struct());
- SetObjItem(BPY_app_oiio_struct());
- SetObjItem(BPY_app_opensubdiv_struct());
- SetObjItem(BPY_app_openvdb_struct());
- SetObjItem(BPY_app_sdl_struct());
- SetObjItem(BPY_app_build_options_struct());
- SetObjItem(BPY_app_handlers_struct());
- SetObjItem(BPY_app_translations_struct());
-
- /* modules */
- SetObjItem(BPY_app_icons_module());
- SetObjItem(BPY_app_timers_module());
+ SetObjItem(BPY_app_alembic_struct());
+ SetObjItem(BPY_app_ffmpeg_struct());
+ SetObjItem(BPY_app_ocio_struct());
+ SetObjItem(BPY_app_oiio_struct());
+ SetObjItem(BPY_app_opensubdiv_struct());
+ SetObjItem(BPY_app_openvdb_struct());
+ SetObjItem(BPY_app_sdl_struct());
+ SetObjItem(BPY_app_build_options_struct());
+ SetObjItem(BPY_app_handlers_struct());
+ SetObjItem(BPY_app_translations_struct());
+
+ /* modules */
+ SetObjItem(BPY_app_icons_module());
+ SetObjItem(BPY_app_timers_module());
#undef SetIntItem
#undef SetStrItem
#undef SetBytesItem
#undef SetObjItem
- if (PyErr_Occurred()) {
- Py_CLEAR(app_info);
- return NULL;
- }
- return app_info;
+ if (PyErr_Occurred()) {
+ Py_CLEAR(app_info);
+ return NULL;
+ }
+ return app_info;
}
/* a few getsets because it makes sense for them to be in bpy.app even though
* they are not static */
-PyDoc_STRVAR(bpy_app_debug_doc,
-"Boolean, for debug info (started with --debug / --debug_* matching this attribute name)"
-);
+PyDoc_STRVAR(
+ bpy_app_debug_doc,
+ "Boolean, for debug info (started with --debug / --debug_* matching this attribute name)");
static PyObject *bpy_app_debug_get(PyObject *UNUSED(self), void *closure)
{
- const int flag = POINTER_AS_INT(closure);
- return PyBool_FromLong(G.debug & flag);
+ const int flag = POINTER_AS_INT(closure);
+ return PyBool_FromLong(G.debug & flag);
}
static int bpy_app_debug_set(PyObject *UNUSED(self), PyObject *value, void *closure)
{
- const int flag = POINTER_AS_INT(closure);
- const int param = PyObject_IsTrue(value);
-
- if (param == -1) {
- PyErr_SetString(PyExc_TypeError, "bpy.app.debug can only be True/False");
- return -1;
- }
-
- if (param) {
- G.debug |= flag;
- }
- else {
- G.debug &= ~flag;
- }
-
- return 0;
+ const int flag = POINTER_AS_INT(closure);
+ const int param = PyObject_IsTrue(value);
+
+ if (param == -1) {
+ PyErr_SetString(PyExc_TypeError, "bpy.app.debug can only be True/False");
+ return -1;
+ }
+
+ if (param) {
+ G.debug |= flag;
+ }
+ else {
+ G.debug &= ~flag;
+ }
+
+ return 0;
}
-PyDoc_STRVAR(bpy_app_global_flag_doc,
-"Boolean, for application behavior (started with --enable-* matching this attribute name)"
-);
+PyDoc_STRVAR(
+ bpy_app_global_flag_doc,
+ "Boolean, for application behavior (started with --enable-* matching this attribute name)");
static PyObject *bpy_app_global_flag_get(PyObject *UNUSED(self), void *closure)
{
- const int flag = POINTER_AS_INT(closure);
- return PyBool_FromLong(G.f & flag);
+ const int flag = POINTER_AS_INT(closure);
+ return PyBool_FromLong(G.f & flag);
}
static int bpy_app_global_flag_set(PyObject *UNUSED(self), PyObject *value, void *closure)
{
- const int flag = POINTER_AS_INT(closure);
- const int param = PyObject_IsTrue(value);
-
- if (param == -1) {
- PyErr_SetString(PyExc_TypeError, "bpy.app.use_* can only be True/False");
- return -1;
- }
-
- if (param) {
- G.f |= flag;
- }
- else {
- G.f &= ~flag;
- }
-
- return 0;
+ const int flag = POINTER_AS_INT(closure);
+ const int param = PyObject_IsTrue(value);
+
+ if (param == -1) {
+ PyErr_SetString(PyExc_TypeError, "bpy.app.use_* can only be True/False");
+ return -1;
+ }
+
+ if (param) {
+ G.f |= flag;
+ }
+ else {
+ G.f &= ~flag;
+ }
+
+ return 0;
}
-static int bpy_app_global_flag_set__only_disable(PyObject *UNUSED(self), PyObject *value, void *closure)
+static int bpy_app_global_flag_set__only_disable(PyObject *UNUSED(self),
+ PyObject *value,
+ void *closure)
{
- const int param = PyObject_IsTrue(value);
- if (param == 1) {
- PyErr_SetString(PyExc_ValueError, "This bpy.app.use_* option can only be disabled");
- return -1;
- }
- return bpy_app_global_flag_set(NULL, value, closure);
+ const int param = PyObject_IsTrue(value);
+ if (param == 1) {
+ PyErr_SetString(PyExc_ValueError, "This bpy.app.use_* option can only be disabled");
+ return -1;
+ }
+ return bpy_app_global_flag_set(NULL, value, closure);
}
#define BROKEN_BINARY_PATH_PYTHON_HACK
PyDoc_STRVAR(bpy_app_binary_path_python_doc,
-"String, the path to the python executable (read-only)"
-);
+ "String, the path to the python executable (read-only)");
static PyObject *bpy_app_binary_path_python_get(PyObject *self, void *UNUSED(closure))
{
- /* refcount is held in BlenderAppType.tp_dict */
- static PyObject *ret = NULL;
-
- if (ret == NULL) {
- /* only run once */
- char fullpath[1024];
- BKE_appdir_program_python_search(
- fullpath, sizeof(fullpath),
- PY_MAJOR_VERSION, PY_MINOR_VERSION);
- ret = PyC_UnicodeFromByte(fullpath);
+ /* refcount is held in BlenderAppType.tp_dict */
+ static PyObject *ret = NULL;
+
+ if (ret == NULL) {
+ /* only run once */
+ char fullpath[1024];
+ BKE_appdir_program_python_search(
+ fullpath, sizeof(fullpath), PY_MAJOR_VERSION, PY_MINOR_VERSION);
+ ret = PyC_UnicodeFromByte(fullpath);
#ifdef BROKEN_BINARY_PATH_PYTHON_HACK
- Py_INCREF(ret);
- UNUSED_VARS(self);
+ Py_INCREF(ret);
+ UNUSED_VARS(self);
#else
- PyDict_SetItem(BlenderAppType.tp_dict, /* XXX BAAAADDDDDD! self is not a PyDescr at all! it's bpy.app!!! */ PyDescr_NAME(self), ret);
+ PyDict_SetItem(
+ BlenderAppType.tp_dict,
+ /* XXX BAAAADDDDDD! self is not a PyDescr at all! it's bpy.app!!! */ PyDescr_NAME(self),
+ ret);
#endif
- }
- else {
- Py_INCREF(ret);
- }
+ }
+ else {
+ Py_INCREF(ret);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_app_debug_value_doc,
-"Short, number which can be set to non-zero values for testing purposes"
-);
+ "Short, number which can be set to non-zero values for testing purposes");
static PyObject *bpy_app_debug_value_get(PyObject *UNUSED(self), void *UNUSED(closure))
{
- return PyLong_FromLong(G.debug_value);
+ return PyLong_FromLong(G.debug_value);
}
static int bpy_app_debug_value_set(PyObject *UNUSED(self), PyObject *value, void *UNUSED(closure))
{
- short param = PyC_Long_AsI16(value);
+ short param = PyC_Long_AsI16(value);
- if (param == -1 && PyErr_Occurred()) {
- PyC_Err_SetString_Prefix(
- PyExc_TypeError,
- "bpy.app.debug_value can only be set to a whole number");
- return -1;
- }
+ if (param == -1 && PyErr_Occurred()) {
+ PyC_Err_SetString_Prefix(PyExc_TypeError,
+ "bpy.app.debug_value can only be set to a whole number");
+ return -1;
+ }
- G.debug_value = param;
+ G.debug_value = param;
- WM_main_add_notifier(NC_WINDOW, NULL);
+ WM_main_add_notifier(NC_WINDOW, NULL);
- return 0;
+ return 0;
}
-PyDoc_STRVAR(bpy_app_tempdir_doc,
-"String, the temp directory used by blender (read-only)"
-);
+PyDoc_STRVAR(bpy_app_tempdir_doc, "String, the temp directory used by blender (read-only)");
static PyObject *bpy_app_tempdir_get(PyObject *UNUSED(self), void *UNUSED(closure))
{
- return PyC_UnicodeFromByte(BKE_tempdir_session());
+ return PyC_UnicodeFromByte(BKE_tempdir_session());
}
-PyDoc_STRVAR(bpy_app_driver_dict_doc,
-"Dictionary for drivers namespace, editable in-place, reset on file load (read-only)"
-);
+PyDoc_STRVAR(
+ bpy_app_driver_dict_doc,
+ "Dictionary for drivers namespace, editable in-place, reset on file load (read-only)");
static PyObject *bpy_app_driver_dict_get(PyObject *UNUSED(self), void *UNUSED(closure))
{
- if (bpy_pydriver_Dict == NULL) {
- if (bpy_pydriver_create_dict() != 0) {
- PyErr_SetString(PyExc_RuntimeError, "bpy.app.driver_namespace failed to create dictionary");
- return NULL;
- }
- }
-
- return Py_INCREF_RET(bpy_pydriver_Dict);
+ if (bpy_pydriver_Dict == NULL) {
+ if (bpy_pydriver_create_dict() != 0) {
+ PyErr_SetString(PyExc_RuntimeError, "bpy.app.driver_namespace failed to create dictionary");
+ return NULL;
+ }
+ }
+
+ return Py_INCREF_RET(bpy_pydriver_Dict);
}
PyDoc_STRVAR(bpy_app_preview_render_size_doc,
-"Reference size for icon/preview renders (read-only)"
-);
+ "Reference size for icon/preview renders (read-only)");
static PyObject *bpy_app_preview_render_size_get(PyObject *UNUSED(self), void *closure)
{
- return PyLong_FromLong((long)UI_preview_render_size(POINTER_AS_INT(closure)));
+ return PyLong_FromLong((long)UI_preview_render_size(POINTER_AS_INT(closure)));
}
static PyObject *bpy_app_autoexec_fail_message_get(PyObject *UNUSED(self), void *UNUSED(closure))
{
- return PyC_UnicodeFromByte(G.autoexec_fail);
+ return PyC_UnicodeFromByte(G.autoexec_fail);
}
-
PyDoc_STRVAR(bpy_app_use_static_override_doc,
-"Boolean, whether static override is exposed in UI or not."
-);
+ "Boolean, whether static override is exposed in UI or not.");
static PyObject *bpy_app_use_static_override_get(PyObject *UNUSED(self), void *UNUSED(closure))
{
- return PyBool_FromLong((long)BKE_override_static_is_enabled());
+ return PyBool_FromLong((long)BKE_override_static_is_enabled());
}
-static int bpy_app_use_static_override_set(PyObject *UNUSED(self), PyObject *value, void *UNUSED(closure))
+static int bpy_app_use_static_override_set(PyObject *UNUSED(self),
+ PyObject *value,
+ void *UNUSED(closure))
{
- const int param = PyC_Long_AsBool(value);
+ const int param = PyC_Long_AsBool(value);
- if (param == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "bpy.app.use_static_override must be a boolean");
- return -1;
- }
+ if (param == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "bpy.app.use_static_override must be a boolean");
+ return -1;
+ }
- BKE_override_static_enable((const bool)param);
+ BKE_override_static_enable((const bool)param);
- return 0;
+ return 0;
}
-
static PyGetSetDef bpy_app_getsets[] = {
- {(char *)"debug", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG},
- {(char *)"debug_ffmpeg", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_FFMPEG},
- {(char *)"debug_freestyle", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_FREESTYLE},
- {(char *)"debug_python", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_PYTHON},
- {(char *)"debug_events", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_EVENTS},
- {(char *)"debug_handlers", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_HANDLERS},
- {(char *)"debug_wm", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_WM},
- {(char *)"debug_depsgraph", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH},
- {(char *)"debug_depsgraph_build", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_BUILD},
- {(char *)"debug_depsgraph_eval", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_EVAL},
- {(char *)"debug_depsgraph_tag", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_TAG},
- {(char *)"debug_depsgraph_time", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_TIME},
- {(char *)"debug_depsgraph_pretty", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_PRETTY},
- {(char *)"debug_simdata", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_SIMDATA},
- {(char *)"debug_gpumem", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_GPU_MEM},
- {(char *)"debug_io", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_IO},
-
- {(char *)"use_static_override", bpy_app_use_static_override_get, bpy_app_use_static_override_set, (char *)bpy_app_use_static_override_doc, NULL},
- {(char *)"use_event_simulate", bpy_app_global_flag_get, bpy_app_global_flag_set__only_disable, (char *)bpy_app_global_flag_doc, (void *)G_FLAG_EVENT_SIMULATE},
-
- {(char *)"binary_path_python", bpy_app_binary_path_python_get, NULL, (char *)bpy_app_binary_path_python_doc, NULL},
-
- {(char *)"debug_value", bpy_app_debug_value_get, bpy_app_debug_value_set, (char *)bpy_app_debug_value_doc, NULL},
- {(char *)"tempdir", bpy_app_tempdir_get, NULL, (char *)bpy_app_tempdir_doc, NULL},
- {(char *)"driver_namespace", bpy_app_driver_dict_get, NULL, (char *)bpy_app_driver_dict_doc, NULL},
-
- {(char *)"render_icon_size", bpy_app_preview_render_size_get, NULL, (char *)bpy_app_preview_render_size_doc, (void *)ICON_SIZE_ICON},
- {(char *)"render_preview_size", bpy_app_preview_render_size_get, NULL, (char *)bpy_app_preview_render_size_doc, (void *)ICON_SIZE_PREVIEW},
-
- /* security */
- {(char *)"autoexec_fail", bpy_app_global_flag_get, NULL, NULL, (void *)G_FLAG_SCRIPT_AUTOEXEC_FAIL},
- {(char *)"autoexec_fail_quiet", bpy_app_global_flag_get, NULL, NULL, (void *)G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET},
- {(char *)"autoexec_fail_message", bpy_app_autoexec_fail_message_get, NULL, NULL, NULL},
- {NULL, NULL, NULL, NULL, NULL},
+ {(char *)"debug",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG},
+ {(char *)"debug_ffmpeg",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_FFMPEG},
+ {(char *)"debug_freestyle",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_FREESTYLE},
+ {(char *)"debug_python",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_PYTHON},
+ {(char *)"debug_events",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_EVENTS},
+ {(char *)"debug_handlers",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_HANDLERS},
+ {(char *)"debug_wm",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_WM},
+ {(char *)"debug_depsgraph",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH},
+ {(char *)"debug_depsgraph_build",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH_BUILD},
+ {(char *)"debug_depsgraph_eval",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH_EVAL},
+ {(char *)"debug_depsgraph_tag",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH_TAG},
+ {(char *)"debug_depsgraph_time",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH_TIME},
+ {(char *)"debug_depsgraph_pretty",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_DEPSGRAPH_PRETTY},
+ {(char *)"debug_simdata",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_SIMDATA},
+ {(char *)"debug_gpumem",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_GPU_MEM},
+ {(char *)"debug_io",
+ bpy_app_debug_get,
+ bpy_app_debug_set,
+ (char *)bpy_app_debug_doc,
+ (void *)G_DEBUG_IO},
+
+ {(char *)"use_static_override",
+ bpy_app_use_static_override_get,
+ bpy_app_use_static_override_set,
+ (char *)bpy_app_use_static_override_doc,
+ NULL},
+ {(char *)"use_event_simulate",
+ bpy_app_global_flag_get,
+ bpy_app_global_flag_set__only_disable,
+ (char *)bpy_app_global_flag_doc,
+ (void *)G_FLAG_EVENT_SIMULATE},
+
+ {(char *)"binary_path_python",
+ bpy_app_binary_path_python_get,
+ NULL,
+ (char *)bpy_app_binary_path_python_doc,
+ NULL},
+
+ {(char *)"debug_value",
+ bpy_app_debug_value_get,
+ bpy_app_debug_value_set,
+ (char *)bpy_app_debug_value_doc,
+ NULL},
+ {(char *)"tempdir", bpy_app_tempdir_get, NULL, (char *)bpy_app_tempdir_doc, NULL},
+ {(char *)"driver_namespace",
+ bpy_app_driver_dict_get,
+ NULL,
+ (char *)bpy_app_driver_dict_doc,
+ NULL},
+
+ {(char *)"render_icon_size",
+ bpy_app_preview_render_size_get,
+ NULL,
+ (char *)bpy_app_preview_render_size_doc,
+ (void *)ICON_SIZE_ICON},
+ {(char *)"render_preview_size",
+ bpy_app_preview_render_size_get,
+ NULL,
+ (char *)bpy_app_preview_render_size_doc,
+ (void *)ICON_SIZE_PREVIEW},
+
+ /* security */
+ {(char *)"autoexec_fail",
+ bpy_app_global_flag_get,
+ NULL,
+ NULL,
+ (void *)G_FLAG_SCRIPT_AUTOEXEC_FAIL},
+ {(char *)"autoexec_fail_quiet",
+ bpy_app_global_flag_get,
+ NULL,
+ NULL,
+ (void *)G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET},
+ {(char *)"autoexec_fail_message", bpy_app_autoexec_fail_message_get, NULL, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL},
};
static void py_struct_seq_getset_init(void)
{
- /* tricky dynamic members, not to py-spec! */
- for (PyGetSetDef *getset = bpy_app_getsets; getset->name; getset++) {
- PyObject *item = PyDescr_NewGetSet(&BlenderAppType, getset);
- PyDict_SetItem(BlenderAppType.tp_dict, PyDescr_NAME(item), item);
- Py_DECREF(item);
- }
+ /* tricky dynamic members, not to py-spec! */
+ for (PyGetSetDef *getset = bpy_app_getsets; getset->name; getset++) {
+ PyObject *item = PyDescr_NewGetSet(&BlenderAppType, getset);
+ PyDict_SetItem(BlenderAppType.tp_dict, PyDescr_NAME(item), item);
+ Py_DECREF(item);
+ }
}
/* end dynamic bpy.app */
-
PyObject *BPY_app_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppType, &app_info_desc);
+ PyStructSequence_InitType(&BlenderAppType, &app_info_desc);
- ret = make_app_info();
+ ret = make_app_info();
- /* prevent user from creating new instances */
- BlenderAppType.tp_init = NULL;
- BlenderAppType.tp_new = NULL;
- BlenderAppType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppType.tp_init = NULL;
+ BlenderAppType.tp_new = NULL;
+ BlenderAppType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- /* kindof a hack ontop of PyStructSequence */
- py_struct_seq_getset_init();
+ /* kindof a hack ontop of PyStructSequence */
+ py_struct_seq_getset_init();
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app.h b/source/blender/python/intern/bpy_app.h
index e9ab3cd2858..b46de025599 100644
--- a/source/blender/python/intern/bpy_app.h
+++ b/source/blender/python/intern/bpy_app.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_struct(void);
-#endif /* __BPY_APP_H__ */
+#endif /* __BPY_APP_H__ */
diff --git a/source/blender/python/intern/bpy_app_alembic.c b/source/blender/python/intern/bpy_app_alembic.c
index 6f2874dcefa..6032e062d09 100644
--- a/source/blender/python/intern/bpy_app_alembic.c
+++ b/source/blender/python/intern/bpy_app_alembic.c
@@ -35,73 +35,72 @@
static PyTypeObject BlenderAppABCType;
static PyStructSequence_Field app_alembic_info_fields[] = {
- {(char *)"supported", (char *)"Boolean, True when Blender is built with Alembic support"},
- {(char *)"version", (char *)"The Alembic version as a tuple of 3 numbers"},
- {(char *)"version_string", (char *)"The Alembic version formatted as a string"},
- {NULL},
+ {(char *)"supported", (char *)"Boolean, True when Blender is built with Alembic support"},
+ {(char *)"version", (char *)"The Alembic version as a tuple of 3 numbers"},
+ {(char *)"version_string", (char *)"The Alembic version formatted as a string"},
+ {NULL},
};
static PyStructSequence_Desc app_alembic_info_desc = {
- (char *)"bpy.app.alembic", /* name */
- (char *)"This module contains information about Alembic blender is linked against", /* doc */
- app_alembic_info_fields, /* fields */
- ARRAY_SIZE(app_alembic_info_fields) - 1,
+ (char *)"bpy.app.alembic", /* name */
+ (char *)"This module contains information about Alembic blender is linked against", /* doc */
+ app_alembic_info_fields, /* fields */
+ ARRAY_SIZE(app_alembic_info_fields) - 1,
};
static PyObject *make_alembic_info(void)
{
- PyObject *alembic_info = PyStructSequence_New(&BlenderAppABCType);
+ PyObject *alembic_info = PyStructSequence_New(&BlenderAppABCType);
- if (alembic_info == NULL) {
- return NULL;
- }
+ if (alembic_info == NULL) {
+ return NULL;
+ }
- int pos = 0;
+ int pos = 0;
#ifndef WITH_ALEMBIC
-# define SetStrItem(str) \
- PyStructSequence_SET_ITEM(alembic_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) PyStructSequence_SET_ITEM(alembic_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(alembic_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(alembic_info, pos++, obj)
#ifdef WITH_ALEMBIC
- const int curversion = ABC_get_version();
- const int major = curversion / 10000;
- const int minor = (curversion / 100) - (major * 100);
- const int patch = curversion - ((curversion / 100 ) * 100);
-
- SetObjItem(PyBool_FromLong(1));
- SetObjItem(PyC_Tuple_Pack_I32(major, minor, patch));
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d", major, minor, patch));
+ const int curversion = ABC_get_version();
+ const int major = curversion / 10000;
+ const int minor = (curversion / 100) - (major * 100);
+ const int patch = curversion - ((curversion / 100) * 100);
+
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(PyC_Tuple_Pack_I32(major, minor, patch));
+ SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d", major, minor, patch));
#else
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(alembic_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(alembic_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return alembic_info;
+ return alembic_info;
}
PyObject *BPY_app_alembic_struct(void)
{
- PyStructSequence_InitType(&BlenderAppABCType, &app_alembic_info_desc);
+ PyStructSequence_InitType(&BlenderAppABCType, &app_alembic_info_desc);
- PyObject *ret = make_alembic_info();
+ PyObject *ret = make_alembic_info();
- /* prevent user from creating new instances */
- BlenderAppABCType.tp_init = NULL;
- BlenderAppABCType.tp_new = NULL;
- BlenderAppABCType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppABCType.tp_init = NULL;
+ BlenderAppABCType.tp_new = NULL;
+ BlenderAppABCType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_alembic.h b/source/blender/python/intern/bpy_app_alembic.h
index dfa652c8d15..4cc890ec64d 100644
--- a/source/blender/python/intern/bpy_app_alembic.h
+++ b/source/blender/python/intern/bpy_app_alembic.h
@@ -26,4 +26,4 @@
PyObject *BPY_app_alembic_struct(void);
-#endif /* __BPY_APP_ALEMBIC_H__ */
+#endif /* __BPY_APP_ALEMBIC_H__ */
diff --git a/source/blender/python/intern/bpy_app_build_options.c b/source/blender/python/intern/bpy_app_build_options.c
index a80156a23bf..a841e974e85 100644
--- a/source/blender/python/intern/bpy_app_build_options.c
+++ b/source/blender/python/intern/bpy_app_build_options.c
@@ -27,265 +27,265 @@
static PyTypeObject BlenderAppBuildOptionsType;
static PyStructSequence_Field app_builtopts_info_fields[] = {
- /* names mostly follow CMake options, lowercase, after WITH_ */
- {(char *)"bullet", NULL},
- {(char *)"codec_avi", NULL},
- {(char *)"codec_ffmpeg", NULL},
- {(char *)"codec_sndfile", NULL},
- {(char *)"compositor", NULL},
- {(char *)"cycles", NULL},
- {(char *)"cycles_osl", NULL},
- {(char *)"freestyle", NULL},
- {(char *)"image_cineon", NULL},
- {(char *)"image_dds", NULL},
- {(char *)"image_hdr", NULL},
- {(char *)"image_openexr", NULL},
- {(char *)"image_openjpeg", NULL},
- {(char *)"image_tiff", NULL},
- {(char *)"input_ndof", NULL},
- {(char *)"audaspace", NULL},
- {(char *)"international", NULL},
- {(char *)"openal", NULL},
- {(char *)"sdl", NULL},
- {(char *)"sdl_dynload", NULL},
- {(char *)"jack", NULL},
- {(char *)"libmv", NULL},
- {(char *)"mod_fluid", NULL},
- {(char *)"mod_oceansim", NULL},
- {(char *)"mod_remesh", NULL},
- {(char *)"mod_smoke", NULL},
- {(char *)"collada", NULL},
- {(char *)"opencolorio", NULL},
- {(char *)"openmp", NULL},
- {(char *)"openvdb", NULL},
- {(char *)"alembic", NULL},
- {NULL},
+ /* names mostly follow CMake options, lowercase, after WITH_ */
+ {(char *)"bullet", NULL},
+ {(char *)"codec_avi", NULL},
+ {(char *)"codec_ffmpeg", NULL},
+ {(char *)"codec_sndfile", NULL},
+ {(char *)"compositor", NULL},
+ {(char *)"cycles", NULL},
+ {(char *)"cycles_osl", NULL},
+ {(char *)"freestyle", NULL},
+ {(char *)"image_cineon", NULL},
+ {(char *)"image_dds", NULL},
+ {(char *)"image_hdr", NULL},
+ {(char *)"image_openexr", NULL},
+ {(char *)"image_openjpeg", NULL},
+ {(char *)"image_tiff", NULL},
+ {(char *)"input_ndof", NULL},
+ {(char *)"audaspace", NULL},
+ {(char *)"international", NULL},
+ {(char *)"openal", NULL},
+ {(char *)"sdl", NULL},
+ {(char *)"sdl_dynload", NULL},
+ {(char *)"jack", NULL},
+ {(char *)"libmv", NULL},
+ {(char *)"mod_fluid", NULL},
+ {(char *)"mod_oceansim", NULL},
+ {(char *)"mod_remesh", NULL},
+ {(char *)"mod_smoke", NULL},
+ {(char *)"collada", NULL},
+ {(char *)"opencolorio", NULL},
+ {(char *)"openmp", NULL},
+ {(char *)"openvdb", NULL},
+ {(char *)"alembic", NULL},
+ {NULL},
};
-
static PyStructSequence_Desc app_builtopts_info_desc = {
- (char *)"bpy.app.build_options", /* name */
- (char *)"This module contains information about options blender is built with", /* doc */
- app_builtopts_info_fields, /* fields */
- ARRAY_SIZE(app_builtopts_info_fields) - 1,
+ (char *)"bpy.app.build_options", /* name */
+ (char *)"This module contains information about options blender is built with", /* doc */
+ app_builtopts_info_fields, /* fields */
+ ARRAY_SIZE(app_builtopts_info_fields) - 1,
};
static PyObject *make_builtopts_info(void)
{
- PyObject *builtopts_info;
- int pos = 0;
+ PyObject *builtopts_info;
+ int pos = 0;
- builtopts_info = PyStructSequence_New(&BlenderAppBuildOptionsType);
- if (builtopts_info == NULL) {
- return NULL;
- }
+ builtopts_info = PyStructSequence_New(&BlenderAppBuildOptionsType);
+ if (builtopts_info == NULL) {
+ return NULL;
+ }
#define SetObjIncref(item) \
- PyStructSequence_SET_ITEM(builtopts_info, pos++, (Py_IncRef(item), item))
+ PyStructSequence_SET_ITEM(builtopts_info, pos++, (Py_IncRef(item), item))
#ifdef WITH_BULLET
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_AVI
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_FFMPEG
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_SNDFILE
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_COMPOSITOR
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_CYCLES
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_CYCLES_OSL
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_FREESTYLE
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_CINEON
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_DDS
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_HDR
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OPENEXR
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OPENJPEG
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_TIFF
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_INPUT_NDOF
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_AUDASPACE
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_INTERNATIONAL
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OPENAL
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_SDL
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_SDL_DYNLOAD
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_JACK
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_LIBMV
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_MOD_FLUID
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OCEANSIM
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_MOD_REMESH
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_SMOKE
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_COLLADA
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OCIO
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef _OPENMP
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_OPENVDB
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#ifdef WITH_ALEMBIC
- SetObjIncref(Py_True);
+ SetObjIncref(Py_True);
#else
- SetObjIncref(Py_False);
+ SetObjIncref(Py_False);
#endif
#undef SetObjIncref
- return builtopts_info;
+ return builtopts_info;
}
PyObject *BPY_app_build_options_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppBuildOptionsType, &app_builtopts_info_desc);
+ PyStructSequence_InitType(&BlenderAppBuildOptionsType, &app_builtopts_info_desc);
- ret = make_builtopts_info();
+ ret = make_builtopts_info();
- /* prevent user from creating new instances */
- BlenderAppBuildOptionsType.tp_init = NULL;
- BlenderAppBuildOptionsType.tp_new = NULL;
- BlenderAppBuildOptionsType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppBuildOptionsType.tp_init = NULL;
+ BlenderAppBuildOptionsType.tp_new = NULL;
+ BlenderAppBuildOptionsType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_build_options.h b/source/blender/python/intern/bpy_app_build_options.h
index e15887d9caf..52c2e57c12a 100644
--- a/source/blender/python/intern/bpy_app_build_options.h
+++ b/source/blender/python/intern/bpy_app_build_options.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_build_options_struct(void);
-#endif /* __BPY_APP_BUILD_OPTIONS_H__ */
+#endif /* __BPY_APP_BUILD_OPTIONS_H__ */
diff --git a/source/blender/python/intern/bpy_app_ffmpeg.c b/source/blender/python/intern/bpy_app_ffmpeg.c
index 6fb53f60f90..d1aa7817538 100644
--- a/source/blender/python/intern/bpy_app_ffmpeg.c
+++ b/source/blender/python/intern/bpy_app_ffmpeg.c
@@ -26,116 +26,121 @@
#include "../generic/py_capi_utils.h"
#ifdef WITH_FFMPEG
-#include <libavcodec/avcodec.h>
-#include <libavdevice/avdevice.h>
-#include <libavformat/avformat.h>
-#include <libavutil/avutil.h>
-#include <libswscale/swscale.h>
+# include <libavcodec/avcodec.h>
+# include <libavdevice/avdevice.h>
+# include <libavformat/avformat.h>
+# include <libavutil/avutil.h>
+# include <libswscale/swscale.h>
#endif
static PyTypeObject BlenderAppFFmpegType;
#define DEF_FFMPEG_LIB_VERSION(lib) \
- {(char *)(#lib "_version"), (char *)("The " #lib " version as a tuple of 3 numbers")}, \
- {(char *)(#lib "_version_string"), (char *)("The " #lib " version formatted as a string")}
+ {(char *)(#lib "_version"), (char *)("The " #lib " version as a tuple of 3 numbers")}, \
+ { \
+ (char *)(#lib "_version_string"), (char *)("The " #lib " version formatted as a string") \
+ }
static PyStructSequence_Field app_ffmpeg_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with FFmpeg support")},
-
- DEF_FFMPEG_LIB_VERSION(avcodec),
- DEF_FFMPEG_LIB_VERSION(avdevice),
- DEF_FFMPEG_LIB_VERSION(avformat),
- DEF_FFMPEG_LIB_VERSION(avutil),
- DEF_FFMPEG_LIB_VERSION(swscale),
- {NULL},
+ {(char *)"supported", (char *)("Boolean, True when Blender is built with FFmpeg support")},
+
+ DEF_FFMPEG_LIB_VERSION(avcodec),
+ DEF_FFMPEG_LIB_VERSION(avdevice),
+ DEF_FFMPEG_LIB_VERSION(avformat),
+ DEF_FFMPEG_LIB_VERSION(avutil),
+ DEF_FFMPEG_LIB_VERSION(swscale),
+ {NULL},
};
#undef DEF_FFMPEG_LIB_VERSION
static PyStructSequence_Desc app_ffmpeg_info_desc = {
- (char *)"bpy.app.ffmpeg", /* name */
- (char *)"This module contains information about FFmpeg blender is linked against", /* doc */
- app_ffmpeg_info_fields, /* fields */
- ARRAY_SIZE(app_ffmpeg_info_fields) - 1,
+ (char *)"bpy.app.ffmpeg", /* name */
+ (char *)"This module contains information about FFmpeg blender is linked against", /* doc */
+ app_ffmpeg_info_fields, /* fields */
+ ARRAY_SIZE(app_ffmpeg_info_fields) - 1,
};
static PyObject *make_ffmpeg_info(void)
{
- PyObject *ffmpeg_info;
- int pos = 0;
+ PyObject *ffmpeg_info;
+ int pos = 0;
#ifdef WITH_FFMPEG
- int curversion;
+ int curversion;
#endif
- ffmpeg_info = PyStructSequence_New(&BlenderAppFFmpegType);
- if (ffmpeg_info == NULL) {
- return NULL;
- }
+ ffmpeg_info = PyStructSequence_New(&BlenderAppFFmpegType);
+ if (ffmpeg_info == NULL) {
+ return NULL;
+ }
-#if 0 // UNUSED
-#define SetIntItem(flag) \
- PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyLong_FromLong(flag))
+#if 0 // UNUSED
+# define SetIntItem(flag) PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyLong_FromLong(flag))
#endif
#ifndef WITH_FFMPEG
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) PyStructSequence_SET_ITEM(ffmpeg_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(ffmpeg_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(ffmpeg_info, pos++, obj)
#ifdef WITH_FFMPEG
-# define FFMPEG_LIB_VERSION(lib) { \
- curversion = lib ## _version(); \
- SetObjItem(PyC_Tuple_Pack_I32(curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d", \
- curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
-} (void)0
+# define FFMPEG_LIB_VERSION(lib) \
+ { \
+ curversion = lib##_version(); \
+ SetObjItem( \
+ PyC_Tuple_Pack_I32(curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
+ SetObjItem(PyUnicode_FromFormat( \
+ "%2d, %2d, %2d", curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
+ } \
+ (void)0
#else
-# define FFMPEG_LIB_VERSION(lib) { \
- SetStrItem("Unknown"); \
- SetStrItem("Unknown"); \
-} (void)0
+# define FFMPEG_LIB_VERSION(lib) \
+ { \
+ SetStrItem("Unknown"); \
+ SetStrItem("Unknown"); \
+ } \
+ (void)0
#endif
#ifdef WITH_FFMPEG
- SetObjItem(PyBool_FromLong(1));
+ SetObjItem(PyBool_FromLong(1));
#else
- SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyBool_FromLong(0));
#endif
- FFMPEG_LIB_VERSION(avcodec);
- FFMPEG_LIB_VERSION(avdevice);
- FFMPEG_LIB_VERSION(avformat);
- FFMPEG_LIB_VERSION(avutil);
- FFMPEG_LIB_VERSION(swscale);
+ FFMPEG_LIB_VERSION(avcodec);
+ FFMPEG_LIB_VERSION(avdevice);
+ FFMPEG_LIB_VERSION(avformat);
+ FFMPEG_LIB_VERSION(avutil);
+ FFMPEG_LIB_VERSION(swscale);
#undef FFMPEG_LIB_VERSION
- if (PyErr_Occurred()) {
- Py_CLEAR(ffmpeg_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(ffmpeg_info);
+ return NULL;
+ }
// #undef SetIntItem
#undef SetStrItem
#undef SetObjItem
- return ffmpeg_info;
+ return ffmpeg_info;
}
PyObject *BPY_app_ffmpeg_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppFFmpegType, &app_ffmpeg_info_desc);
+ PyStructSequence_InitType(&BlenderAppFFmpegType, &app_ffmpeg_info_desc);
- ret = make_ffmpeg_info();
+ ret = make_ffmpeg_info();
- /* prevent user from creating new instances */
- BlenderAppFFmpegType.tp_init = NULL;
- BlenderAppFFmpegType.tp_new = NULL;
- BlenderAppFFmpegType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppFFmpegType.tp_init = NULL;
+ BlenderAppFFmpegType.tp_new = NULL;
+ BlenderAppFFmpegType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_ffmpeg.h b/source/blender/python/intern/bpy_app_ffmpeg.h
index 063781a54a5..63fff2b1b4b 100644
--- a/source/blender/python/intern/bpy_app_ffmpeg.h
+++ b/source/blender/python/intern/bpy_app_ffmpeg.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_ffmpeg_struct(void);
-#endif /* __BPY_APP_FFMPEG_H__ */
+#endif /* __BPY_APP_FFMPEG_H__ */
diff --git a/source/blender/python/intern/bpy_app_handlers.c b/source/blender/python/intern/bpy_app_handlers.c
index c91c0d69a16..7134bf520ac 100644
--- a/source/blender/python/intern/bpy_app_handlers.c
+++ b/source/blender/python/intern/bpy_app_handlers.c
@@ -40,40 +40,42 @@ void bpy_app_generic_callback(struct Main *main, struct ID *id, void *arg);
static PyTypeObject BlenderAppCbType;
static PyStructSequence_Field app_cb_info_fields[] = {
- {(char *)"frame_change_pre", (char *)"on frame change for playback and rendering (before)"},
- {(char *)"frame_change_post", (char *)"on frame change for playback and rendering (after)"},
- {(char *)"render_pre", (char *)"on render (before)"},
- {(char *)"render_post", (char *)"on render (after)"},
- {(char *)"render_write", (char *)"on writing a render frame (directly after the frame is written)"},
- {(char *)"render_stats", (char *)"on printing render statistics"},
- {(char *)"render_init", (char *)"on initialization of a render job"},
- {(char *)"render_complete", (char *)"on completion of render job"},
- {(char *)"render_cancel", (char *)"on canceling a render job"},
- {(char *)"load_pre", (char *)"on loading a new blend file (before)"},
- {(char *)"load_post", (char *)"on loading a new blend file (after)"},
- {(char *)"save_pre", (char *)"on saving a blend file (before)"},
- {(char *)"save_post", (char *)"on saving a blend file (after)"},
- {(char *)"undo_pre", (char *)"on loading an undo step (before)"},
- {(char *)"undo_post", (char *)"on loading an undo step (after)"},
- {(char *)"redo_pre", (char *)"on loading a redo step (before)"},
- {(char *)"redo_post", (char *)"on loading a redo step (after)"},
- {(char *)"depsgraph_update_pre", (char *)"on depsgraph update (pre)"},
- {(char *)"depsgraph_update_post", (char *)"on depsgraph update (post)"},
- {(char *)"version_update", (char *)"on ending the versioning code"},
- {(char *)"load_factory_startup_post", (char *)"on loading factory startup (after)"},
-
- /* sets the permanent tag */
+ {(char *)"frame_change_pre", (char *)"on frame change for playback and rendering (before)"},
+ {(char *)"frame_change_post", (char *)"on frame change for playback and rendering (after)"},
+ {(char *)"render_pre", (char *)"on render (before)"},
+ {(char *)"render_post", (char *)"on render (after)"},
+ {(char *)"render_write",
+ (char *)"on writing a render frame (directly after the frame is written)"},
+ {(char *)"render_stats", (char *)"on printing render statistics"},
+ {(char *)"render_init", (char *)"on initialization of a render job"},
+ {(char *)"render_complete", (char *)"on completion of render job"},
+ {(char *)"render_cancel", (char *)"on canceling a render job"},
+ {(char *)"load_pre", (char *)"on loading a new blend file (before)"},
+ {(char *)"load_post", (char *)"on loading a new blend file (after)"},
+ {(char *)"save_pre", (char *)"on saving a blend file (before)"},
+ {(char *)"save_post", (char *)"on saving a blend file (after)"},
+ {(char *)"undo_pre", (char *)"on loading an undo step (before)"},
+ {(char *)"undo_post", (char *)"on loading an undo step (after)"},
+ {(char *)"redo_pre", (char *)"on loading a redo step (before)"},
+ {(char *)"redo_post", (char *)"on loading a redo step (after)"},
+ {(char *)"depsgraph_update_pre", (char *)"on depsgraph update (pre)"},
+ {(char *)"depsgraph_update_post", (char *)"on depsgraph update (post)"},
+ {(char *)"version_update", (char *)"on ending the versioning code"},
+ {(char *)"load_factory_startup_post", (char *)"on loading factory startup (after)"},
+
+/* sets the permanent tag */
#define APP_CB_OTHER_FIELDS 1
- {(char *)"persistent", (char *)"Function decorator for callback functions not to be removed when loading new files"},
+ {(char *)"persistent",
+ (char *)"Function decorator for callback functions not to be removed when loading new files"},
- {NULL},
+ {NULL},
};
static PyStructSequence_Desc app_cb_info_desc = {
- (char *)"bpy.app.handlers", /* name */
- (char *)"This module contains callback lists", /* doc */
- app_cb_info_fields, /* fields */
- ARRAY_SIZE(app_cb_info_fields) - 1,
+ (char *)"bpy.app.handlers", /* name */
+ (char *)"This module contains callback lists", /* doc */
+ app_cb_info_fields, /* fields */
+ ARRAY_SIZE(app_cb_info_fields) - 1,
};
#if 0
@@ -86,251 +88,250 @@ static PyStructSequence_Desc app_cb_info_desc = {
/* permanent tagging code */
#define PERMINENT_CB_ID "_bpy_persistent"
-static PyObject *bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *UNUSED(kwds))
+static PyObject *bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type),
+ PyObject *args,
+ PyObject *UNUSED(kwds))
{
- PyObject *value;
-
- if (!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value)) {
- return NULL;
- }
-
- if (PyFunction_Check(value)) {
- PyObject **dict_ptr = _PyObject_GetDictPtr(value);
- if (dict_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "bpy.app.handlers.persistent wasn't able to "
- "get the dictionary from the function passed");
- return NULL;
- }
- else {
- /* set id */
- if (*dict_ptr == NULL) {
- *dict_ptr = PyDict_New();
- }
-
- PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
- }
-
- Py_INCREF(value);
- return value;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "bpy.app.handlers.persistent expected a function");
- return NULL;
- }
+ PyObject *value;
+
+ if (!PyArg_ParseTuple(args, "O:bpy.app.handlers.persistent", &value)) {
+ return NULL;
+ }
+
+ if (PyFunction_Check(value)) {
+ PyObject **dict_ptr = _PyObject_GetDictPtr(value);
+ if (dict_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "bpy.app.handlers.persistent wasn't able to "
+ "get the dictionary from the function passed");
+ return NULL;
+ }
+ else {
+ /* set id */
+ if (*dict_ptr == NULL) {
+ *dict_ptr = PyDict_New();
+ }
+
+ PyDict_SetItemString(*dict_ptr, PERMINENT_CB_ID, Py_None);
+ }
+
+ Py_INCREF(value);
+ return value;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "bpy.app.handlers.persistent expected a function");
+ return NULL;
+ }
}
/* dummy type because decorators can't be PyCFunctions */
static PyTypeObject BPyPersistent_Type = {
#if defined(_MSC_VER)
- PyVarObject_HEAD_INIT(NULL, 0)
+ PyVarObject_HEAD_INIT(NULL, 0)
#else
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
#endif
- "persistent", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* 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_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* 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 */
- bpy_app_handlers_persistent_new, /* tp_new */
- 0, /* tp_free */
+ "persistent", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* 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_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* 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 */
+ bpy_app_handlers_persistent_new, /* tp_new */
+ 0, /* tp_free */
};
static PyObject *py_cb_array[BLI_CB_EVT_TOT] = {NULL};
static PyObject *make_app_cb_info(void)
{
- PyObject *app_cb_info;
- int pos;
-
- app_cb_info = PyStructSequence_New(&BlenderAppCbType);
- if (app_cb_info == NULL) {
- return NULL;
- }
-
- for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
- if (app_cb_info_fields[pos].name == NULL) {
- Py_FatalError("invalid callback slots 1");
- }
- PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos] = PyList_New(0)));
- }
- if (app_cb_info_fields[pos + APP_CB_OTHER_FIELDS].name != NULL) {
- Py_FatalError("invalid callback slots 2");
- }
-
- /* custom function */
- PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
-
- return app_cb_info;
+ PyObject *app_cb_info;
+ int pos;
+
+ app_cb_info = PyStructSequence_New(&BlenderAppCbType);
+ if (app_cb_info == NULL) {
+ return NULL;
+ }
+
+ for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
+ if (app_cb_info_fields[pos].name == NULL) {
+ Py_FatalError("invalid callback slots 1");
+ }
+ PyStructSequence_SET_ITEM(app_cb_info, pos, (py_cb_array[pos] = PyList_New(0)));
+ }
+ if (app_cb_info_fields[pos + APP_CB_OTHER_FIELDS].name != NULL) {
+ Py_FatalError("invalid callback slots 2");
+ }
+
+ /* custom function */
+ PyStructSequence_SET_ITEM(app_cb_info, pos++, (PyObject *)&BPyPersistent_Type);
+
+ return app_cb_info;
}
PyObject *BPY_app_handlers_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
#if defined(_MSC_VER)
- BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
+ BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
#endif
- if (PyType_Ready(&BPyPersistent_Type) < 0) {
- BLI_assert(!"error initializing 'bpy.app.handlers.persistent'");
- }
+ if (PyType_Ready(&BPyPersistent_Type) < 0) {
+ BLI_assert(!"error initializing 'bpy.app.handlers.persistent'");
+ }
- PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
+ PyStructSequence_InitType(&BlenderAppCbType, &app_cb_info_desc);
- ret = make_app_cb_info();
+ ret = make_app_cb_info();
- /* prevent user from creating new instances */
- BlenderAppCbType.tp_init = NULL;
- BlenderAppCbType.tp_new = NULL;
- BlenderAppCbType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppCbType.tp_init = NULL;
+ BlenderAppCbType.tp_new = NULL;
+ BlenderAppCbType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- /* assign the C callbacks */
- if (ret) {
- static bCallbackFuncStore funcstore_array[BLI_CB_EVT_TOT] = {{NULL}};
- bCallbackFuncStore *funcstore;
- int pos = 0;
+ /* assign the C callbacks */
+ if (ret) {
+ static bCallbackFuncStore funcstore_array[BLI_CB_EVT_TOT] = {{NULL}};
+ bCallbackFuncStore *funcstore;
+ int pos = 0;
- for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
- funcstore = &funcstore_array[pos];
- funcstore->func = bpy_app_generic_callback;
- funcstore->alloc = 0;
- funcstore->arg = POINTER_FROM_INT(pos);
- BLI_callback_add(funcstore, pos);
- }
- }
+ for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
+ funcstore = &funcstore_array[pos];
+ funcstore->func = bpy_app_generic_callback;
+ funcstore->alloc = 0;
+ funcstore->arg = POINTER_FROM_INT(pos);
+ BLI_callback_add(funcstore, pos);
+ }
+ }
- return ret;
+ return ret;
}
void BPY_app_handlers_reset(const short do_all)
{
- PyGILState_STATE gilstate;
- int pos = 0;
-
- gilstate = PyGILState_Ensure();
-
- if (do_all) {
- for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
- /* clear list */
- PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, NULL);
- }
- }
- else {
- /* save string conversion thrashing */
- PyObject *perm_id_str = PyUnicode_FromString(PERMINENT_CB_ID);
-
- for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
- /* clear only items without PERMINENT_CB_ID */
- PyObject *ls = py_cb_array[pos];
- Py_ssize_t i;
-
- PyObject *item;
- PyObject **dict_ptr;
-
- for (i = PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
-
- if ((PyFunction_Check((item = PyList_GET_ITEM(ls, i)))) &&
- (dict_ptr = _PyObject_GetDictPtr(item)) &&
- (*dict_ptr) &&
- (PyDict_GetItem(*dict_ptr, perm_id_str) != NULL))
- {
- /* keep */
- }
- else {
- /* remove */
- /* PySequence_DelItem(ls, i); */ /* more obvious buw slower */
- PyList_SetSlice(ls, i, i + 1, NULL);
- }
- }
- }
-
- Py_DECREF(perm_id_str);
- }
-
- PyGILState_Release(gilstate);
+ PyGILState_STATE gilstate;
+ int pos = 0;
+
+ gilstate = PyGILState_Ensure();
+
+ if (do_all) {
+ for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
+ /* clear list */
+ PyList_SetSlice(py_cb_array[pos], 0, PY_SSIZE_T_MAX, NULL);
+ }
+ }
+ else {
+ /* save string conversion thrashing */
+ PyObject *perm_id_str = PyUnicode_FromString(PERMINENT_CB_ID);
+
+ for (pos = 0; pos < BLI_CB_EVT_TOT; pos++) {
+ /* clear only items without PERMINENT_CB_ID */
+ PyObject *ls = py_cb_array[pos];
+ Py_ssize_t i;
+
+ PyObject *item;
+ PyObject **dict_ptr;
+
+ for (i = PyList_GET_SIZE(ls) - 1; i >= 0; i--) {
+
+ if ((PyFunction_Check((item = PyList_GET_ITEM(ls, i)))) &&
+ (dict_ptr = _PyObject_GetDictPtr(item)) && (*dict_ptr) &&
+ (PyDict_GetItem(*dict_ptr, perm_id_str) != NULL)) {
+ /* keep */
+ }
+ else {
+ /* remove */
+ /* PySequence_DelItem(ls, i); */ /* more obvious buw slower */
+ PyList_SetSlice(ls, i, i + 1, NULL);
+ }
+ }
+ }
+
+ Py_DECREF(perm_id_str);
+ }
+
+ PyGILState_Release(gilstate);
}
/* the actual callback - not necessarily called from py */
void bpy_app_generic_callback(struct Main *UNUSED(main), struct ID *id, void *arg)
{
- PyObject *cb_list = py_cb_array[POINTER_AS_INT(arg)];
- if (PyList_GET_SIZE(cb_list) > 0) {
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- PyObject *args = PyTuple_New(1); /* save python creating each call */
- PyObject *func;
- PyObject *ret;
- Py_ssize_t pos;
-
- /* setup arguments */
- if (id) {
- PointerRNA id_ptr;
- RNA_id_pointer_create(id, &id_ptr);
- PyTuple_SET_ITEM(args, 0, pyrna_struct_CreatePyObject(&id_ptr));
- }
- else {
- PyTuple_SET_ITEM(args, 0, Py_INCREF_RET(Py_None));
- }
-
- /* Iterate the list and run the callbacks
- * note: don't store the list size since the scripts may remove themselves */
- for (pos = 0; pos < PyList_GET_SIZE(cb_list); pos++) {
- func = PyList_GET_ITEM(cb_list, pos);
- ret = PyObject_Call(func, args, NULL);
- if (ret == NULL) {
- /* Don't set last system variables because they might cause some
- * dangling pointers to external render engines (when exception
- * happens during rendering) which will break logic of render pipeline
- * which expects to be the only user of render engine when rendering
- * is finished.
- */
- PyErr_PrintEx(0);
- PyErr_Clear();
- }
- else {
- Py_DECREF(ret);
- }
- }
-
- Py_DECREF(args);
-
- PyGILState_Release(gilstate);
- }
+ PyObject *cb_list = py_cb_array[POINTER_AS_INT(arg)];
+ if (PyList_GET_SIZE(cb_list) > 0) {
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ PyObject *args = PyTuple_New(1); /* save python creating each call */
+ PyObject *func;
+ PyObject *ret;
+ Py_ssize_t pos;
+
+ /* setup arguments */
+ if (id) {
+ PointerRNA id_ptr;
+ RNA_id_pointer_create(id, &id_ptr);
+ PyTuple_SET_ITEM(args, 0, pyrna_struct_CreatePyObject(&id_ptr));
+ }
+ else {
+ PyTuple_SET_ITEM(args, 0, Py_INCREF_RET(Py_None));
+ }
+
+ /* Iterate the list and run the callbacks
+ * note: don't store the list size since the scripts may remove themselves */
+ for (pos = 0; pos < PyList_GET_SIZE(cb_list); pos++) {
+ func = PyList_GET_ITEM(cb_list, pos);
+ ret = PyObject_Call(func, args, NULL);
+ if (ret == NULL) {
+ /* Don't set last system variables because they might cause some
+ * dangling pointers to external render engines (when exception
+ * happens during rendering) which will break logic of render pipeline
+ * which expects to be the only user of render engine when rendering
+ * is finished.
+ */
+ PyErr_PrintEx(0);
+ PyErr_Clear();
+ }
+ else {
+ Py_DECREF(ret);
+ }
+ }
+
+ Py_DECREF(args);
+
+ PyGILState_Release(gilstate);
+ }
}
diff --git a/source/blender/python/intern/bpy_app_icons.c b/source/blender/python/intern/bpy_app_icons.c
index 863d11ff84d..2e688609961 100644
--- a/source/blender/python/intern/bpy_app_icons.c
+++ b/source/blender/python/intern/bpy_app_icons.c
@@ -33,151 +33,149 @@
#include "bpy_app_icons.h"
/* We may want to load direct from file. */
-PyDoc_STRVAR(bpy_app_icons_new_triangles_doc,
-".. function:: new_triangles(range, coords, colors)"
-"\n"
-" Create a new icon from triangle geometry.\n"
-"\n"
-" :arg range: Pair of ints.\n"
-" :type range: tuple.\n"
-" :arg coords: Sequence of bytes (6 floats for one triangle) for (X, Y) coordinates.\n"
-" :type coords: byte sequence.\n"
-" :arg colors: Sequence of ints (12 for one triangles) for RGBA.\n"
-" :type colors: byte sequence.\n"
-" :return: Unique icon value (pass to interface ``icon_value`` argument).\n"
-" :rtype: int\n"
-);
+PyDoc_STRVAR(
+ bpy_app_icons_new_triangles_doc,
+ ".. function:: new_triangles(range, coords, colors)"
+ "\n"
+ " Create a new icon from triangle geometry.\n"
+ "\n"
+ " :arg range: Pair of ints.\n"
+ " :type range: tuple.\n"
+ " :arg coords: Sequence of bytes (6 floats for one triangle) for (X, Y) coordinates.\n"
+ " :type coords: byte sequence.\n"
+ " :arg colors: Sequence of ints (12 for one triangles) for RGBA.\n"
+ " :type colors: byte sequence.\n"
+ " :return: Unique icon value (pass to interface ``icon_value`` argument).\n"
+ " :rtype: int\n");
static PyObject *bpy_app_icons_new_triangles(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- /* bytes */
- uchar coords_range[2];
- PyObject *py_coords, *py_colors;
-
- static const char *_keywords[] = {"range", "coords", "colors", NULL};
- static _PyArg_Parser _parser = {"(BB)SS:new_triangles", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &coords_range[0], &coords_range[1], &py_coords, &py_colors))
- {
- return NULL;
- }
-
- const int coords_len = PyBytes_GET_SIZE(py_coords);
- const int tris_len = coords_len / 6;
- if (tris_len * 6 != coords_len) {
- PyErr_SetString(PyExc_ValueError, "coords must be multiple of 6");
- return NULL;
- }
- if (PyBytes_GET_SIZE(py_colors) != 2 * coords_len) {
- PyErr_SetString(PyExc_ValueError, "colors must be twice size of coords");
- return NULL;
- }
-
- int coords_size = sizeof(uchar[2]) * tris_len * 3;
- int colors_size = sizeof(uchar[4]) * tris_len * 3;
- uchar (*coords)[2] = MEM_mallocN(coords_size, __func__);
- uchar (*colors)[4] = MEM_mallocN(colors_size, __func__);
-
- memcpy(coords, PyBytes_AS_STRING(py_coords), coords_size);
- memcpy(colors, PyBytes_AS_STRING(py_colors), colors_size);
-
- struct Icon_Geom *geom = MEM_mallocN(sizeof(*geom), __func__);
- geom->coords_len = tris_len;
- geom->coords_range[0] = coords_range[0];
- geom->coords_range[1] = coords_range[1];
- geom->coords = coords;
- geom->colors = colors;
- geom->icon_id = 0;
- int icon_id = BKE_icon_geom_ensure(geom);
- return PyLong_FromLong(icon_id);
+ /* bytes */
+ uchar coords_range[2];
+ PyObject *py_coords, *py_colors;
+
+ static const char *_keywords[] = {"range", "coords", "colors", NULL};
+ static _PyArg_Parser _parser = {"(BB)SS:new_triangles", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &coords_range[0], &coords_range[1], &py_coords, &py_colors)) {
+ return NULL;
+ }
+
+ const int coords_len = PyBytes_GET_SIZE(py_coords);
+ const int tris_len = coords_len / 6;
+ if (tris_len * 6 != coords_len) {
+ PyErr_SetString(PyExc_ValueError, "coords must be multiple of 6");
+ return NULL;
+ }
+ if (PyBytes_GET_SIZE(py_colors) != 2 * coords_len) {
+ PyErr_SetString(PyExc_ValueError, "colors must be twice size of coords");
+ return NULL;
+ }
+
+ int coords_size = sizeof(uchar[2]) * tris_len * 3;
+ int colors_size = sizeof(uchar[4]) * tris_len * 3;
+ uchar(*coords)[2] = MEM_mallocN(coords_size, __func__);
+ uchar(*colors)[4] = MEM_mallocN(colors_size, __func__);
+
+ memcpy(coords, PyBytes_AS_STRING(py_coords), coords_size);
+ memcpy(colors, PyBytes_AS_STRING(py_colors), colors_size);
+
+ struct Icon_Geom *geom = MEM_mallocN(sizeof(*geom), __func__);
+ geom->coords_len = tris_len;
+ geom->coords_range[0] = coords_range[0];
+ geom->coords_range[1] = coords_range[1];
+ geom->coords = coords;
+ geom->colors = colors;
+ geom->icon_id = 0;
+ int icon_id = BKE_icon_geom_ensure(geom);
+ return PyLong_FromLong(icon_id);
}
PyDoc_STRVAR(bpy_app_icons_new_triangles_from_file_doc,
-".. function:: new_triangles_from_file(filename)"
-"\n"
-" Create a new icon from triangle geometry.\n"
-"\n"
-" :arg filename: File path.\n"
-" :type filename: string.\n"
-" :return: Unique icon value (pass to interface ``icon_value`` argument).\n"
-" :rtype: int\n"
-);
-static PyObject *bpy_app_icons_new_triangles_from_file(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
+ ".. function:: new_triangles_from_file(filename)"
+ "\n"
+ " Create a new icon from triangle geometry.\n"
+ "\n"
+ " :arg filename: File path.\n"
+ " :type filename: string.\n"
+ " :return: Unique icon value (pass to interface ``icon_value`` argument).\n"
+ " :rtype: int\n");
+static PyObject *bpy_app_icons_new_triangles_from_file(PyObject *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- /* bytes */
- char *filename;
-
- static const char *_keywords[] = {"filename", NULL};
- static _PyArg_Parser _parser = {"s:new_triangles_from_file", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &filename))
- {
- return NULL;
- }
-
- struct Icon_Geom *geom = BKE_icon_geom_from_file(filename);
- if (geom == NULL) {
- PyErr_SetString(PyExc_ValueError, "Unable to load from file");
- return NULL;
- }
- int icon_id = BKE_icon_geom_ensure(geom);
- return PyLong_FromLong(icon_id);
+ /* bytes */
+ char *filename;
+
+ static const char *_keywords[] = {"filename", NULL};
+ static _PyArg_Parser _parser = {"s:new_triangles_from_file", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &filename)) {
+ return NULL;
+ }
+
+ struct Icon_Geom *geom = BKE_icon_geom_from_file(filename);
+ if (geom == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Unable to load from file");
+ return NULL;
+ }
+ int icon_id = BKE_icon_geom_ensure(geom);
+ return PyLong_FromLong(icon_id);
}
PyDoc_STRVAR(bpy_app_icons_release_doc,
-".. function:: release(icon_id)"
-"\n"
-" Release the icon.\n"
-);
+ ".. function:: release(icon_id)"
+ "\n"
+ " Release the icon.\n");
static PyObject *bpy_app_icons_release(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- int icon_id;
- static const char *_keywords[] = {"icon_id", NULL};
- static _PyArg_Parser _parser = {"i:release", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &icon_id))
- {
- return NULL;
- }
-
- if (!BKE_icon_delete_unmanaged(icon_id)) {
- PyErr_SetString(PyExc_ValueError, "invalid icon_id");
- return NULL;
- }
- Py_RETURN_NONE;
+ int icon_id;
+ static const char *_keywords[] = {"icon_id", NULL};
+ static _PyArg_Parser _parser = {"i:release", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &icon_id)) {
+ return NULL;
+ }
+
+ if (!BKE_icon_delete_unmanaged(icon_id)) {
+ PyErr_SetString(PyExc_ValueError, "invalid icon_id");
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static struct PyMethodDef M_AppIcons_methods[] = {
- {"new_triangles", (PyCFunction)bpy_app_icons_new_triangles,
- METH_VARARGS | METH_KEYWORDS, bpy_app_icons_new_triangles_doc},
- {"new_triangles_from_file", (PyCFunction)bpy_app_icons_new_triangles_from_file,
- METH_VARARGS | METH_KEYWORDS, bpy_app_icons_new_triangles_from_file_doc},
- {"release", (PyCFunction)bpy_app_icons_release,
- METH_VARARGS | METH_KEYWORDS, bpy_app_icons_release_doc},
- {NULL, NULL, 0, NULL},
+ {"new_triangles",
+ (PyCFunction)bpy_app_icons_new_triangles,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_app_icons_new_triangles_doc},
+ {"new_triangles_from_file",
+ (PyCFunction)bpy_app_icons_new_triangles_from_file,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_app_icons_new_triangles_from_file_doc},
+ {"release",
+ (PyCFunction)bpy_app_icons_release,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_app_icons_release_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_AppIcons_module_def = {
- PyModuleDef_HEAD_INIT,
- "bpy.app.icons", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- M_AppIcons_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bpy.app.icons", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ M_AppIcons_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPY_app_icons_module(void)
{
- PyObject *sys_modules = PyImport_GetModuleDict();
+ PyObject *sys_modules = PyImport_GetModuleDict();
- PyObject *mod = PyModule_Create(&M_AppIcons_module_def);
+ PyObject *mod = PyModule_Create(&M_AppIcons_module_def);
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(mod), mod);
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(mod), mod);
- return mod;
+ return mod;
}
diff --git a/source/blender/python/intern/bpy_app_ocio.c b/source/blender/python/intern/bpy_app_ocio.c
index deb025e0e33..2a56075e00e 100644
--- a/source/blender/python/intern/bpy_app_ocio.c
+++ b/source/blender/python/intern/bpy_app_ocio.c
@@ -32,76 +32,78 @@
static PyTypeObject BlenderAppOCIOType;
static PyStructSequence_Field app_ocio_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenColorIO support")},
- {(char *)("version"), (char *)("The OpenColorIO version as a tuple of 3 numbers")},
- {(char *)("version_string"), (char *)("The OpenColorIO version formatted as a string")},
- {NULL},
+ {(char *)"supported",
+ (char *)("Boolean, True when Blender is built with OpenColorIO support")},
+ {(char *)("version"), (char *)("The OpenColorIO version as a tuple of 3 numbers")},
+ {(char *)("version_string"), (char *)("The OpenColorIO version formatted as a string")},
+ {NULL},
};
static PyStructSequence_Desc app_ocio_info_desc = {
- (char *)"bpy.app.ocio", /* name */
- (char *)"This module contains information about OpenColorIO blender is linked against", /* doc */
- app_ocio_info_fields, /* fields */
- ARRAY_SIZE(app_ocio_info_fields) - 1,
+ (char *)"bpy.app.ocio", /* name */
+ (char
+ *)"This module contains information about OpenColorIO blender is linked against", /* doc */
+ app_ocio_info_fields, /* fields */
+ ARRAY_SIZE(app_ocio_info_fields) - 1,
};
static PyObject *make_ocio_info(void)
{
- PyObject *ocio_info;
- int pos = 0;
+ PyObject *ocio_info;
+ int pos = 0;
#ifdef WITH_OCIO
- int curversion;
+ int curversion;
#endif
- ocio_info = PyStructSequence_New(&BlenderAppOCIOType);
- if (ocio_info == NULL) {
- return NULL;
- }
+ ocio_info = PyStructSequence_New(&BlenderAppOCIOType);
+ if (ocio_info == NULL) {
+ return NULL;
+ }
#ifndef WITH_OCIO
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(ocio_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) PyStructSequence_SET_ITEM(ocio_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(ocio_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(ocio_info, pos++, obj)
#ifdef WITH_OCIO
- curversion = OCIO_getVersionHex();
- SetObjItem(PyBool_FromLong(1));
- SetObjItem(PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
- curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ curversion = OCIO_getVersionHex();
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(
+ PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ SetObjItem(PyUnicode_FromFormat(
+ "%2d, %2d, %2d", curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
#else
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(ocio_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(ocio_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return ocio_info;
+ return ocio_info;
}
PyObject *BPY_app_ocio_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppOCIOType, &app_ocio_info_desc);
+ PyStructSequence_InitType(&BlenderAppOCIOType, &app_ocio_info_desc);
- ret = make_ocio_info();
+ ret = make_ocio_info();
- /* prevent user from creating new instances */
- BlenderAppOCIOType.tp_init = NULL;
- BlenderAppOCIOType.tp_new = NULL;
- BlenderAppOCIOType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppOCIOType.tp_init = NULL;
+ BlenderAppOCIOType.tp_new = NULL;
+ BlenderAppOCIOType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_ocio.h b/source/blender/python/intern/bpy_app_ocio.h
index 54ecad2c5ed..66fc03657c1 100644
--- a/source/blender/python/intern/bpy_app_ocio.h
+++ b/source/blender/python/intern/bpy_app_ocio.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_ocio_struct(void);
-#endif /* __BPY_APP_OCIO_H__ */
+#endif /* __BPY_APP_OCIO_H__ */
diff --git a/source/blender/python/intern/bpy_app_oiio.c b/source/blender/python/intern/bpy_app_oiio.c
index 5701a8def92..05c192f6e2e 100644
--- a/source/blender/python/intern/bpy_app_oiio.c
+++ b/source/blender/python/intern/bpy_app_oiio.c
@@ -32,76 +32,77 @@
static PyTypeObject BlenderAppOIIOType;
static PyStructSequence_Field app_oiio_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenImageIO support")},
- {(char *)("version"), (char *)("The OpenImageIO version as a tuple of 3 numbers")},
- {(char *)("version_string"), (char *)("The OpenImageIO version formatted as a string")},
- {NULL},
+ {(char *)"supported",
+ (char *)("Boolean, True when Blender is built with OpenImageIO support")},
+ {(char *)("version"), (char *)("The OpenImageIO version as a tuple of 3 numbers")},
+ {(char *)("version_string"), (char *)("The OpenImageIO version formatted as a string")},
+ {NULL},
};
static PyStructSequence_Desc app_oiio_info_desc = {
- (char *)"bpy.app.oiio", /* name */
- (char *)"This module contains information about OpeImageIO blender is linked against", /* doc */
- app_oiio_info_fields, /* fields */
- ARRAY_SIZE(app_oiio_info_fields) - 1,
+ (char *)"bpy.app.oiio", /* name */
+ (char
+ *)"This module contains information about OpeImageIO blender is linked against", /* doc */
+ app_oiio_info_fields, /* fields */
+ ARRAY_SIZE(app_oiio_info_fields) - 1,
};
static PyObject *make_oiio_info(void)
{
- PyObject *oiio_info;
- int pos = 0;
+ PyObject *oiio_info;
+ int pos = 0;
#ifdef WITH_OPENIMAGEIO
- int curversion;
+ int curversion;
#endif
- oiio_info = PyStructSequence_New(&BlenderAppOIIOType);
- if (oiio_info == NULL) {
- return NULL;
- }
+ oiio_info = PyStructSequence_New(&BlenderAppOIIOType);
+ if (oiio_info == NULL) {
+ return NULL;
+ }
#ifndef WITH_OPENIMAGEIO
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(oiio_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) PyStructSequence_SET_ITEM(oiio_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(oiio_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(oiio_info, pos++, obj)
#ifdef WITH_OPENIMAGEIO
- curversion = OIIO_getVersionHex();
- SetObjItem(PyBool_FromLong(1));
- SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
- curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ curversion = OIIO_getVersionHex();
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ SetObjItem(PyUnicode_FromFormat(
+ "%2d, %2d, %2d", curversion / 10000, (curversion / 100) % 100, curversion % 100));
#else
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(oiio_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(oiio_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return oiio_info;
+ return oiio_info;
}
PyObject *BPY_app_oiio_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppOIIOType, &app_oiio_info_desc);
+ PyStructSequence_InitType(&BlenderAppOIIOType, &app_oiio_info_desc);
- ret = make_oiio_info();
+ ret = make_oiio_info();
- /* prevent user from creating new instances */
- BlenderAppOIIOType.tp_init = NULL;
- BlenderAppOIIOType.tp_new = NULL;
- BlenderAppOIIOType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppOIIOType.tp_init = NULL;
+ BlenderAppOIIOType.tp_new = NULL;
+ BlenderAppOIIOType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_oiio.h b/source/blender/python/intern/bpy_app_oiio.h
index f2832b23936..4b08652dff5 100644
--- a/source/blender/python/intern/bpy_app_oiio.h
+++ b/source/blender/python/intern/bpy_app_oiio.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_oiio_struct(void);
-#endif /* __BPY_APP_OIIO_H__ */
+#endif /* __BPY_APP_OIIO_H__ */
diff --git a/source/blender/python/intern/bpy_app_opensubdiv.c b/source/blender/python/intern/bpy_app_opensubdiv.c
index 7c084605fd3..e6e84ac30c0 100644
--- a/source/blender/python/intern/bpy_app_opensubdiv.c
+++ b/source/blender/python/intern/bpy_app_opensubdiv.c
@@ -32,73 +32,73 @@
static PyTypeObject BlenderAppOpenSubdivType;
static PyStructSequence_Field app_opensubdiv_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenSubdiv support")},
- {(char *)("version"), (char *)("The OpenSubdiv version as a tuple of 3 numbers")},
- {(char *)("version_string"), (char *)("The OpenSubdiv version formatted as a string")},
- {NULL},
+ {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenSubdiv support")},
+ {(char *)("version"), (char *)("The OpenSubdiv version as a tuple of 3 numbers")},
+ {(char *)("version_string"), (char *)("The OpenSubdiv version formatted as a string")},
+ {NULL},
};
static PyStructSequence_Desc app_opensubdiv_info_desc = {
- (char *)"bpy.app.opensubdiv", /* name */
- (char *)"This module contains information about OpenSubdiv blender is linked against", /* doc */
- app_opensubdiv_info_fields, /* fields */
- ARRAY_SIZE(app_opensubdiv_info_fields) - 1,
+ (char *)"bpy.app.opensubdiv", /* name */
+ (char
+ *)"This module contains information about OpenSubdiv blender is linked against", /* doc */
+ app_opensubdiv_info_fields, /* fields */
+ ARRAY_SIZE(app_opensubdiv_info_fields) - 1,
};
static PyObject *make_opensubdiv_info(void)
{
- PyObject *opensubdiv_info;
- int pos = 0;
+ PyObject *opensubdiv_info;
+ int pos = 0;
- opensubdiv_info = PyStructSequence_New(&BlenderAppOpenSubdivType);
- if (opensubdiv_info == NULL) {
- return NULL;
- }
+ opensubdiv_info = PyStructSequence_New(&BlenderAppOpenSubdivType);
+ if (opensubdiv_info == NULL) {
+ return NULL;
+ }
#ifndef WITH_OPENSUBDIV
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(opensubdiv_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) \
+ PyStructSequence_SET_ITEM(opensubdiv_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(opensubdiv_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(opensubdiv_info, pos++, obj)
#ifdef WITH_OPENSUBDIV
- int curversion = openSubdiv_getVersionHex();
- SetObjItem(PyBool_FromLong(1));
- SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
- curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ int curversion = openSubdiv_getVersionHex();
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ SetObjItem(PyUnicode_FromFormat(
+ "%2d, %2d, %2d", curversion / 10000, (curversion / 100) % 100, curversion % 100));
#else
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(opensubdiv_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(opensubdiv_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return opensubdiv_info;
+ return opensubdiv_info;
}
PyObject *BPY_app_opensubdiv_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppOpenSubdivType, &app_opensubdiv_info_desc);
+ PyStructSequence_InitType(&BlenderAppOpenSubdivType, &app_opensubdiv_info_desc);
- ret = make_opensubdiv_info();
+ ret = make_opensubdiv_info();
- /* prevent user from creating new instances */
- BlenderAppOpenSubdivType.tp_init = NULL;
- BlenderAppOpenSubdivType.tp_new = NULL;
- /* without this we can't do set(sys.modules) [#29635] */
- BlenderAppOpenSubdivType.tp_hash = (hashfunc)_Py_HashPointer;
+ /* prevent user from creating new instances */
+ BlenderAppOpenSubdivType.tp_init = NULL;
+ BlenderAppOpenSubdivType.tp_new = NULL;
+ /* without this we can't do set(sys.modules) [#29635] */
+ BlenderAppOpenSubdivType.tp_hash = (hashfunc)_Py_HashPointer;
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_opensubdiv.h b/source/blender/python/intern/bpy_app_opensubdiv.h
index 6f349c66794..f04fa6fb44d 100644
--- a/source/blender/python/intern/bpy_app_opensubdiv.h
+++ b/source/blender/python/intern/bpy_app_opensubdiv.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_opensubdiv_struct(void);
-#endif /* __BPY_APP_OPENSUBDIV_H__ */
+#endif /* __BPY_APP_OPENSUBDIV_H__ */
diff --git a/source/blender/python/intern/bpy_app_openvdb.c b/source/blender/python/intern/bpy_app_openvdb.c
index 049cfba8bba..a3d02294c07 100644
--- a/source/blender/python/intern/bpy_app_openvdb.c
+++ b/source/blender/python/intern/bpy_app_openvdb.c
@@ -35,76 +35,76 @@
static PyTypeObject BlenderAppOVDBType;
static PyStructSequence_Field app_openvdb_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenVDB support")},
- {(char *)("version"), (char *)("The OpenVDB version as a tuple of 3 numbers")},
- {(char *)("version_string"), (char *)("The OpenVDB version formatted as a string")},
- {NULL},
+ {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenVDB support")},
+ {(char *)("version"), (char *)("The OpenVDB version as a tuple of 3 numbers")},
+ {(char *)("version_string"), (char *)("The OpenVDB version formatted as a string")},
+ {NULL},
};
static PyStructSequence_Desc app_openvdb_info_desc = {
- (char *)"bpy.app.openvdb", /* name */
- (char *)"This module contains information about OpenVDB blender is linked against", /* doc */
- app_openvdb_info_fields, /* fields */
- ARRAY_SIZE(app_openvdb_info_fields) - 1,
+ (char *)"bpy.app.openvdb", /* name */
+ (char *)"This module contains information about OpenVDB blender is linked against", /* doc */
+ app_openvdb_info_fields, /* fields */
+ ARRAY_SIZE(app_openvdb_info_fields) - 1,
};
static PyObject *make_openvdb_info(void)
{
- PyObject *openvdb_info;
- int pos = 0;
+ PyObject *openvdb_info;
+ int pos = 0;
#ifdef WITH_OPENVDB
- int curversion;
+ int curversion;
#endif
- openvdb_info = PyStructSequence_New(&BlenderAppOVDBType);
- if (openvdb_info == NULL) {
- return NULL;
- }
+ openvdb_info = PyStructSequence_New(&BlenderAppOVDBType);
+ if (openvdb_info == NULL) {
+ return NULL;
+ }
#ifndef WITH_OPENVDB
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(openvdb_info, pos++, PyUnicode_FromString(str))
+# define SetStrItem(str) PyStructSequence_SET_ITEM(openvdb_info, pos++, PyUnicode_FromString(str))
#endif
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(openvdb_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(openvdb_info, pos++, obj)
#ifdef WITH_OPENVDB
- curversion = OpenVDB_getVersionHex();
- SetObjItem(PyBool_FromLong(1));
- SetObjItem(PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
- SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
- curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ curversion = OpenVDB_getVersionHex();
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(
+ PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ SetObjItem(PyUnicode_FromFormat(
+ "%2d, %2d, %2d", curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
#else
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(openvdb_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(openvdb_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return openvdb_info;
+ return openvdb_info;
}
PyObject *BPY_app_openvdb_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppOVDBType, &app_openvdb_info_desc);
+ PyStructSequence_InitType(&BlenderAppOVDBType, &app_openvdb_info_desc);
- ret = make_openvdb_info();
+ ret = make_openvdb_info();
- /* prevent user from creating new instances */
- BlenderAppOVDBType.tp_init = NULL;
- BlenderAppOVDBType.tp_new = NULL;
- BlenderAppOVDBType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppOVDBType.tp_init = NULL;
+ BlenderAppOVDBType.tp_new = NULL;
+ BlenderAppOVDBType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_openvdb.h b/source/blender/python/intern/bpy_app_openvdb.h
index b002e5e04a6..333d79142f7 100644
--- a/source/blender/python/intern/bpy_app_openvdb.h
+++ b/source/blender/python/intern/bpy_app_openvdb.h
@@ -26,4 +26,4 @@
PyObject *BPY_app_openvdb_struct(void);
-#endif /* __BPY_APP_OPENVDB_H__ */
+#endif /* __BPY_APP_OPENVDB_H__ */
diff --git a/source/blender/python/intern/bpy_app_sdl.c b/source/blender/python/intern/bpy_app_sdl.c
index 09e13e4a116..7e3d02076f2 100644
--- a/source/blender/python/intern/bpy_app_sdl.c
+++ b/source/blender/python/intern/bpy_app_sdl.c
@@ -46,98 +46,98 @@
static PyTypeObject BlenderAppSDLType;
static PyStructSequence_Field app_sdl_info_fields[] = {
- {(char *)"supported", (char *)("Boolean, True when Blender is built with SDL support")},
- {(char *)"version", (char *)("The SDL version as a tuple of 3 numbers")},
- {(char *)"version_string", (char *)("The SDL version formatted as a string")},
- {(char *)"available", (char *)("Boolean, True when SDL is available. This is False when "
- "either *supported* is False, or *dynload* is True and "
- "Blender cannot find the correct library.")},
- {NULL},
+ {(char *)"supported", (char *)("Boolean, True when Blender is built with SDL support")},
+ {(char *)"version", (char *)("The SDL version as a tuple of 3 numbers")},
+ {(char *)"version_string", (char *)("The SDL version formatted as a string")},
+ {(char *)"available",
+ (char *)("Boolean, True when SDL is available. This is False when "
+ "either *supported* is False, or *dynload* is True and "
+ "Blender cannot find the correct library.")},
+ {NULL},
};
static PyStructSequence_Desc app_sdl_info_desc = {
- (char *)"bpy.app.sdl", /* name */
- (char *)"This module contains information about SDL blender is linked against", /* doc */
- app_sdl_info_fields, /* fields */
- ARRAY_SIZE(app_sdl_info_fields) - 1,
+ (char *)"bpy.app.sdl", /* name */
+ (char *)"This module contains information about SDL blender is linked against", /* doc */
+ app_sdl_info_fields, /* fields */
+ ARRAY_SIZE(app_sdl_info_fields) - 1,
};
static PyObject *make_sdl_info(void)
{
- PyObject *sdl_info;
- int pos = 0;
+ PyObject *sdl_info;
+ int pos = 0;
#ifdef WITH_SDL
- bool sdl_available = false;
- SDL_version version = {0, 0, 0};
+ bool sdl_available = false;
+ SDL_version version = {0, 0, 0};
#endif
- sdl_info = PyStructSequence_New(&BlenderAppSDLType);
- if (sdl_info == NULL) {
- return NULL;
- }
+ sdl_info = PyStructSequence_New(&BlenderAppSDLType);
+ if (sdl_info == NULL) {
+ return NULL;
+ }
-#define SetStrItem(str) \
- PyStructSequence_SET_ITEM(sdl_info, pos++, PyUnicode_FromString(str))
+#define SetStrItem(str) PyStructSequence_SET_ITEM(sdl_info, pos++, PyUnicode_FromString(str))
-#define SetObjItem(obj) \
- PyStructSequence_SET_ITEM(sdl_info, pos++, obj)
+#define SetObjItem(obj) PyStructSequence_SET_ITEM(sdl_info, pos++, obj)
#ifdef WITH_SDL
- SetObjItem(PyBool_FromLong(1));
-
-# ifdef WITH_SDL_DYNLOAD
- if (sdlewInit() == SDLEW_SUCCESS) {
- SDL_GetVersion(&version);
- sdl_available = true;
- }
-# else // WITH_SDL_DYNLOAD=OFF
- sdl_available = true;
-# if SDL_MAJOR_VERSION >= 2
- SDL_GetVersion(&version);
-# else
- SDL_VERSION(&version);
+ SetObjItem(PyBool_FromLong(1));
+
+# ifdef WITH_SDL_DYNLOAD
+ if (sdlewInit() == SDLEW_SUCCESS) {
+ SDL_GetVersion(&version);
+ sdl_available = true;
+ }
+# else // WITH_SDL_DYNLOAD=OFF
+ sdl_available = true;
+# if SDL_MAJOR_VERSION >= 2
+ SDL_GetVersion(&version);
+# else
+ SDL_VERSION(&version);
+# endif
# endif
-# endif
-
- SetObjItem(PyC_Tuple_Pack_I32(version.major, version.minor, version.patch));
- if (sdl_available) {
- SetObjItem(PyUnicode_FromFormat("%d.%d.%d", version.major, version.minor, version.patch));
- }
- else {
- SetStrItem("Unknown");
- }
- SetObjItem(PyBool_FromLong(sdl_available));
-
-#else // WITH_SDL=OFF
- SetObjItem(PyBool_FromLong(0));
- SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
- SetStrItem("Unknown");
- SetObjItem(PyBool_FromLong(0));
+
+ SetObjItem(PyC_Tuple_Pack_I32(version.major, version.minor, version.patch));
+ if (sdl_available) {
+ SetObjItem(PyUnicode_FromFormat("%d.%d.%d", version.major, version.minor, version.patch));
+ }
+ else {
+ SetStrItem("Unknown");
+ }
+ SetObjItem(PyBool_FromLong(sdl_available));
+
+#else // WITH_SDL=OFF
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
+ SetObjItem(PyBool_FromLong(0));
#endif
- if (PyErr_Occurred()) {
- Py_CLEAR(sdl_info);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_CLEAR(sdl_info);
+ return NULL;
+ }
#undef SetStrItem
#undef SetObjItem
- return sdl_info;
+ return sdl_info;
}
PyObject *BPY_app_sdl_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- PyStructSequence_InitType(&BlenderAppSDLType, &app_sdl_info_desc);
+ PyStructSequence_InitType(&BlenderAppSDLType, &app_sdl_info_desc);
- ret = make_sdl_info();
+ ret = make_sdl_info();
- /* prevent user from creating new instances */
- BlenderAppSDLType.tp_init = NULL;
- BlenderAppSDLType.tp_new = NULL;
- BlenderAppSDLType.tp_hash = (hashfunc)_Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
+ /* prevent user from creating new instances */
+ BlenderAppSDLType.tp_init = NULL;
+ BlenderAppSDLType.tp_new = NULL;
+ BlenderAppSDLType.tp_hash = (hashfunc)
+ _Py_HashPointer; /* without this we can't do set(sys.modules) [#29635] */
- return ret;
+ return ret;
}
diff --git a/source/blender/python/intern/bpy_app_sdl.h b/source/blender/python/intern/bpy_app_sdl.h
index 7df0dd4b686..453c1c0c1a3 100644
--- a/source/blender/python/intern/bpy_app_sdl.h
+++ b/source/blender/python/intern/bpy_app_sdl.h
@@ -23,4 +23,4 @@
PyObject *BPY_app_sdl_struct(void);
-#endif /* __BPY_APP_SDL_H__ */
+#endif /* __BPY_APP_SDL_H__ */
diff --git a/source/blender/python/intern/bpy_app_timers.c b/source/blender/python/intern/bpy_app_timers.c
index 38a785d0d82..c3c56e4fb66 100644
--- a/source/blender/python/intern/bpy_app_timers.c
+++ b/source/blender/python/intern/bpy_app_timers.c
@@ -29,167 +29,161 @@
#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
-
static double handle_returned_value(PyObject *function, PyObject *ret)
{
- if (ret == NULL) {
- PyErr_PrintEx(0);
- PyErr_Clear();
- return -1;
- }
-
- if (ret == Py_None) {
- return -1;
- }
-
- double value = PyFloat_AsDouble(ret);
- if (value == -1.0f && PyErr_Occurred()) {
- PyErr_Clear();
- printf("Error: 'bpy.app.timers' callback ");
- PyObject_Print(function, stdout, Py_PRINT_RAW);
- printf(" did not return None or float.\n");
- return -1;
- }
-
- if (value < 0.0) {
- value = 0.0;
- }
-
- return value;
+ if (ret == NULL) {
+ PyErr_PrintEx(0);
+ PyErr_Clear();
+ return -1;
+ }
+
+ if (ret == Py_None) {
+ return -1;
+ }
+
+ double value = PyFloat_AsDouble(ret);
+ if (value == -1.0f && PyErr_Occurred()) {
+ PyErr_Clear();
+ printf("Error: 'bpy.app.timers' callback ");
+ PyObject_Print(function, stdout, Py_PRINT_RAW);
+ printf(" did not return None or float.\n");
+ return -1;
+ }
+
+ if (value < 0.0) {
+ value = 0.0;
+ }
+
+ return value;
}
static double py_timer_execute(uintptr_t UNUSED(uuid), void *user_data)
{
- PyObject *function = user_data;
+ PyObject *function = user_data;
- PyGILState_STATE gilstate;
- gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate;
+ gilstate = PyGILState_Ensure();
- PyObject *py_ret = PyObject_CallObject(function, NULL);
- double ret = handle_returned_value(function, py_ret);
+ PyObject *py_ret = PyObject_CallObject(function, NULL);
+ double ret = handle_returned_value(function, py_ret);
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
- return ret;
+ return ret;
}
static void py_timer_free(uintptr_t UNUSED(uuid), void *user_data)
{
- PyObject *function = user_data;
+ PyObject *function = user_data;
- PyGILState_STATE gilstate;
- gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate;
+ gilstate = PyGILState_Ensure();
- Py_DECREF(function);
+ Py_DECREF(function);
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
}
-
-PyDoc_STRVAR(bpy_app_timers_register_doc,
-".. function:: register(function, first_interval=0, persistent=False)\n"
-"\n"
-" Add a new function that will be called after the specified amount of seconds.\n"
-" The function gets no arguments and is expected to return either None or a float.\n"
-" If ``None`` is returned, the timer will be unregistered.\n"
-" A returned number specifies the delay until the function is called again.\n"
-" ``functools.partial`` can be used to assign some parameters.\n"
-"\n"
-" :arg function: The function that should called.\n"
-" :type function: Callable[[], Union[float, None]]\n"
-" :arg first_interval: Seconds until the callback should be called the first time.\n"
-" :type first_interval: float\n"
-" :arg persistent: Don't remove timer when a new file is loaded.\n"
-" :type persistent: bool\n"
-);
+PyDoc_STRVAR(
+ bpy_app_timers_register_doc,
+ ".. function:: register(function, first_interval=0, persistent=False)\n"
+ "\n"
+ " Add a new function that will be called after the specified amount of seconds.\n"
+ " The function gets no arguments and is expected to return either None or a float.\n"
+ " If ``None`` is returned, the timer will be unregistered.\n"
+ " A returned number specifies the delay until the function is called again.\n"
+ " ``functools.partial`` can be used to assign some parameters.\n"
+ "\n"
+ " :arg function: The function that should called.\n"
+ " :type function: Callable[[], Union[float, None]]\n"
+ " :arg first_interval: Seconds until the callback should be called the first time.\n"
+ " :type first_interval: float\n"
+ " :arg persistent: Don't remove timer when a new file is loaded.\n"
+ " :type persistent: bool\n");
static PyObject *bpy_app_timers_register(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- PyObject *function;
- double first_interval = 0;
- int persistent = false;
-
- static const char *_keywords[] = {"function", "first_interval", "persistent", NULL};
- static _PyArg_Parser _parser = {"O|$dp:register", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &function, &first_interval, &persistent))
- {
- return NULL;
- }
-
- if (!PyCallable_Check(function)) {
- PyErr_SetString(PyExc_TypeError, "function is not callable");
- return NULL;
- }
-
- Py_INCREF(function);
- BLI_timer_register(
- (intptr_t)function,
- py_timer_execute, function, py_timer_free,
- first_interval, persistent);
- Py_RETURN_NONE;
+ PyObject *function;
+ double first_interval = 0;
+ int persistent = false;
+
+ static const char *_keywords[] = {"function", "first_interval", "persistent", NULL};
+ static _PyArg_Parser _parser = {"O|$dp:register", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &function, &first_interval, &persistent)) {
+ return NULL;
+ }
+
+ if (!PyCallable_Check(function)) {
+ PyErr_SetString(PyExc_TypeError, "function is not callable");
+ return NULL;
+ }
+
+ Py_INCREF(function);
+ BLI_timer_register(
+ (intptr_t)function, py_timer_execute, function, py_timer_free, first_interval, persistent);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_app_timers_unregister_doc,
-".. function:: unregister(function)\n"
-"\n"
-" Unregister timer.\n"
-"\n"
-" :arg function: Function to unregister.\n"
-" :type function: function\n"
-);
+ ".. function:: unregister(function)\n"
+ "\n"
+ " Unregister timer.\n"
+ "\n"
+ " :arg function: Function to unregister.\n"
+ " :type function: function\n");
static PyObject *bpy_app_timers_unregister(PyObject *UNUSED(self), PyObject *function)
{
- if (!BLI_timer_unregister((intptr_t)function)) {
- PyErr_SetString(PyExc_ValueError, "Error: function is not registered");
- return NULL;
- }
- Py_RETURN_NONE;
+ if (!BLI_timer_unregister((intptr_t)function)) {
+ PyErr_SetString(PyExc_ValueError, "Error: function is not registered");
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_app_timers_is_registered_doc,
-".. function:: is_registered(function)\n"
-"\n"
-" Check if this function is registered as a timer.\n"
-"\n"
-" :arg function: Function to check.\n"
-" :type function: int\n"
-" :return: True when this function is registered, otherwise False.\n"
-" :rtype: bool\n"
-);
+ ".. function:: is_registered(function)\n"
+ "\n"
+ " Check if this function is registered as a timer.\n"
+ "\n"
+ " :arg function: Function to check.\n"
+ " :type function: int\n"
+ " :return: True when this function is registered, otherwise False.\n"
+ " :rtype: bool\n");
static PyObject *bpy_app_timers_is_registered(PyObject *UNUSED(self), PyObject *function)
{
- bool ret = BLI_timer_is_registered((intptr_t)function);
- return PyBool_FromLong(ret);
+ bool ret = BLI_timer_is_registered((intptr_t)function);
+ return PyBool_FromLong(ret);
}
-
static struct PyMethodDef M_AppTimers_methods[] = {
- {"register", (PyCFunction)bpy_app_timers_register,
- METH_VARARGS | METH_KEYWORDS, bpy_app_timers_register_doc},
- {"unregister", (PyCFunction)bpy_app_timers_unregister,
- METH_O, bpy_app_timers_unregister_doc},
- {"is_registered", (PyCFunction)bpy_app_timers_is_registered,
- METH_O, bpy_app_timers_is_registered_doc},
- {NULL, NULL, 0, NULL},
+ {"register",
+ (PyCFunction)bpy_app_timers_register,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_app_timers_register_doc},
+ {"unregister", (PyCFunction)bpy_app_timers_unregister, METH_O, bpy_app_timers_unregister_doc},
+ {"is_registered",
+ (PyCFunction)bpy_app_timers_is_registered,
+ METH_O,
+ bpy_app_timers_is_registered_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_AppTimers_module_def = {
- PyModuleDef_HEAD_INIT,
- "bpy.app.timers", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- M_AppTimers_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bpy.app.timers", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ M_AppTimers_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPY_app_timers_module(void)
{
- PyObject *sys_modules = PyImport_GetModuleDict();
- PyObject *mod = PyModule_Create(&M_AppTimers_module_def);
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(mod), mod);
- return mod;
+ PyObject *sys_modules = PyImport_GetModuleDict();
+ PyObject *mod = PyModule_Create(&M_AppTimers_module_def);
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(mod), mod);
+ return mod;
}
diff --git a/source/blender/python/intern/bpy_app_translations.c b/source/blender/python/intern/bpy_app_translations.c
index f571caee8ec..56de6dd1405 100644
--- a/source/blender/python/intern/bpy_app_translations.c
+++ b/source/blender/python/intern/bpy_app_translations.c
@@ -46,15 +46,15 @@
#endif
typedef struct {
- PyObject_HEAD
- /* The string used to separate context from actual message in PY_TRANSLATE RNA props. */
- const char *context_separator;
- /* A "named tuple" (StructSequence actually...) containing all C-defined contexts. */
- PyObject *contexts;
- /* A readonly mapping {C context id: python id} (actually, a MappingProxy). */
- PyObject *contexts_C_to_py;
- /* A py dict containing all registered py dicts (order is more or less random, first match wins!). */
- PyObject *py_messages;
+ PyObject_HEAD
+ /* The string used to separate context from actual message in PY_TRANSLATE RNA props. */
+ const char *context_separator;
+ /* A "named tuple" (StructSequence actually...) containing all C-defined contexts. */
+ PyObject *contexts;
+ /* A readonly mapping {C context id: python id} (actually, a MappingProxy). */
+ PyObject *contexts_C_to_py;
+ /* A py dict containing all registered py dicts (order is more or less random, first match wins!). */
+ PyObject *py_messages;
} BlenderAppTranslations;
/* Our singleton instance pointer */
@@ -64,48 +64,49 @@ static BlenderAppTranslations *_translations = NULL;
/***** Helpers for ghash *****/
typedef struct GHashKey {
- const char *msgctxt;
- const char *msgid;
+ const char *msgctxt;
+ const char *msgid;
} GHashKey;
static GHashKey *_ghashutil_keyalloc(const void *msgctxt, const void *msgid)
{
- GHashKey *key = MEM_mallocN(sizeof(GHashKey), "Py i18n GHashKey");
- key->msgctxt = BLI_strdup(BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA : msgctxt);
- key->msgid = BLI_strdup(msgid);
- return key;
+ GHashKey *key = MEM_mallocN(sizeof(GHashKey), "Py i18n GHashKey");
+ key->msgctxt = BLI_strdup(BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA :
+ msgctxt);
+ key->msgid = BLI_strdup(msgid);
+ return key;
}
static unsigned int _ghashutil_keyhash(const void *ptr)
{
- const GHashKey *key = ptr;
- unsigned int hash = BLI_ghashutil_strhash(key->msgctxt);
- return hash ^ BLI_ghashutil_strhash(key->msgid);
+ const GHashKey *key = ptr;
+ unsigned int hash = BLI_ghashutil_strhash(key->msgctxt);
+ return hash ^ BLI_ghashutil_strhash(key->msgid);
}
static bool _ghashutil_keycmp(const void *a, const void *b)
{
- const GHashKey *A = a;
- const GHashKey *B = b;
-
- /* Note: comparing msgid first, most of the time it will be enough! */
- if (BLI_ghashutil_strcmp(A->msgid, B->msgid) == false) {
- return BLI_ghashutil_strcmp(A->msgctxt, B->msgctxt);
- }
- return true; /* true means they are not equal! */
+ const GHashKey *A = a;
+ const GHashKey *B = b;
+
+ /* Note: comparing msgid first, most of the time it will be enough! */
+ if (BLI_ghashutil_strcmp(A->msgid, B->msgid) == false) {
+ return BLI_ghashutil_strcmp(A->msgctxt, B->msgctxt);
+ }
+ return true; /* true means they are not equal! */
}
static void _ghashutil_keyfree(void *ptr)
{
- const GHashKey *key = ptr;
+ const GHashKey *key = ptr;
- /* We assume both msgctxt and msgid were BLI_strdup'ed! */
- MEM_freeN((void *)key->msgctxt);
- MEM_freeN((void *)key->msgid);
- MEM_freeN((void *)key);
+ /* We assume both msgctxt and msgid were BLI_strdup'ed! */
+ MEM_freeN((void *)key->msgctxt);
+ MEM_freeN((void *)key->msgid);
+ MEM_freeN((void *)key);
}
-#define _ghashutil_valfree MEM_freeN
+# define _ghashutil_valfree MEM_freeN
/***** Python's messages cache *****/
@@ -118,255 +119,270 @@ static GHash *_translations_cache = NULL;
static void _clear_translations_cache(void)
{
- if (_translations_cache) {
- BLI_ghash_free(_translations_cache, _ghashutil_keyfree, _ghashutil_valfree);
- }
- _translations_cache = NULL;
+ if (_translations_cache) {
+ BLI_ghash_free(_translations_cache, _ghashutil_keyfree, _ghashutil_valfree);
+ }
+ _translations_cache = NULL;
}
static void _build_translations_cache(PyObject *py_messages, const char *locale)
{
- PyObject *uuid, *uuid_dict;
- Py_ssize_t pos = 0;
- char *language = NULL, *language_country = NULL, *language_variant = NULL;
-
- /* For each py dict, we'll search for full locale, then language+country, then language+variant,
- * then only language keys... */
- BLT_lang_locale_explode(locale, &language, NULL, NULL, &language_country, &language_variant);
-
- /* Clear the cached ghash if needed, and create a new one. */
- _clear_translations_cache();
- _translations_cache = BLI_ghash_new(_ghashutil_keyhash, _ghashutil_keycmp, __func__);
-
- /* Iterate over all py dicts. */
- while (PyDict_Next(py_messages, &pos, &uuid, &uuid_dict)) {
- PyObject *lang_dict;
-
-#if 0
- PyObject_Print(uuid_dict, stdout, 0);
- printf("\n");
-#endif
-
- /* Try to get first complete locale, then language+country, then language+variant, then only language */
- lang_dict = PyDict_GetItemString(uuid_dict, locale);
- if (!lang_dict && language_country) {
- lang_dict = PyDict_GetItemString(uuid_dict, language_country);
- locale = language_country;
- }
- if (!lang_dict && language_variant) {
- lang_dict = PyDict_GetItemString(uuid_dict, language_variant);
- locale = language_variant;
- }
- if (!lang_dict && language) {
- lang_dict = PyDict_GetItemString(uuid_dict, language);
- locale = language;
- }
-
- if (lang_dict) {
- PyObject *pykey, *trans;
- Py_ssize_t ppos = 0;
-
- if (!PyDict_Check(lang_dict)) {
- printf("WARNING! In translations' dict of \"");
- PyObject_Print(uuid, stdout, Py_PRINT_RAW);
- printf("\":\n");
- printf(" Each language key must have a dictionary as value, \"%s\" is not valid, skipping: ",
- locale);
- PyObject_Print(lang_dict, stdout, Py_PRINT_RAW);
- printf("\n");
- continue;
- }
-
- /* Iterate over all translations of the found language dict, and populate our ghash cache. */
- while (PyDict_Next(lang_dict, &ppos, &pykey, &trans)) {
- const char *msgctxt = NULL, *msgid = NULL;
- bool invalid_key = false;
-
- if ((PyTuple_CheckExact(pykey) == false) || (PyTuple_GET_SIZE(pykey) != 2)) {
- invalid_key = true;
- }
- else {
- PyObject *tmp = PyTuple_GET_ITEM(pykey, 0);
- if (tmp == Py_None) {
- msgctxt = BLT_I18NCONTEXT_DEFAULT_BPYRNA;
- }
- else if (PyUnicode_Check(tmp)) {
- msgctxt = _PyUnicode_AsString(tmp);
- }
- else {
- invalid_key = true;
- }
-
- tmp = PyTuple_GET_ITEM(pykey, 1);
- if (PyUnicode_Check(tmp)) {
- msgid = _PyUnicode_AsString(tmp);
- }
- else {
- invalid_key = true;
- }
- }
-
- if (invalid_key) {
- printf("WARNING! In translations' dict of \"");
- PyObject_Print(uuid, stdout, Py_PRINT_RAW);
- printf("\", %s language:\n", locale);
- printf(" Keys must be tuples of (msgctxt [string or None], msgid [string]), "
- "this one is not valid, skipping: ");
- PyObject_Print(pykey, stdout, Py_PRINT_RAW);
- printf("\n");
- continue;
- }
- if (PyUnicode_Check(trans) == false) {
- printf("WARNING! In translations' dict of \"");
- PyObject_Print(uuid, stdout, Py_PRINT_RAW);
- printf("\":\n");
- printf(" Values must be strings, this one is not valid, skipping: ");
- PyObject_Print(trans, stdout, Py_PRINT_RAW);
- printf("\n");
- continue;
- }
-
- /* Do not overwrite existing keys! */
- if (BPY_app_translations_py_pgettext(msgctxt, msgid) == msgid) {
- GHashKey *key = _ghashutil_keyalloc(msgctxt, msgid);
- BLI_ghash_insert(_translations_cache, key, BLI_strdup(_PyUnicode_AsString(trans)));
- }
- }
- }
- }
-
- /* Clean up! */
- MEM_SAFE_FREE(language);
- MEM_SAFE_FREE(language_country);
- MEM_SAFE_FREE(language_variant);
+ PyObject *uuid, *uuid_dict;
+ Py_ssize_t pos = 0;
+ char *language = NULL, *language_country = NULL, *language_variant = NULL;
+
+ /* For each py dict, we'll search for full locale, then language+country, then language+variant,
+ * then only language keys... */
+ BLT_lang_locale_explode(locale, &language, NULL, NULL, &language_country, &language_variant);
+
+ /* Clear the cached ghash if needed, and create a new one. */
+ _clear_translations_cache();
+ _translations_cache = BLI_ghash_new(_ghashutil_keyhash, _ghashutil_keycmp, __func__);
+
+ /* Iterate over all py dicts. */
+ while (PyDict_Next(py_messages, &pos, &uuid, &uuid_dict)) {
+ PyObject *lang_dict;
+
+# if 0
+ PyObject_Print(uuid_dict, stdout, 0);
+ printf("\n");
+# endif
+
+ /* Try to get first complete locale, then language+country, then language+variant, then only language */
+ lang_dict = PyDict_GetItemString(uuid_dict, locale);
+ if (!lang_dict && language_country) {
+ lang_dict = PyDict_GetItemString(uuid_dict, language_country);
+ locale = language_country;
+ }
+ if (!lang_dict && language_variant) {
+ lang_dict = PyDict_GetItemString(uuid_dict, language_variant);
+ locale = language_variant;
+ }
+ if (!lang_dict && language) {
+ lang_dict = PyDict_GetItemString(uuid_dict, language);
+ locale = language;
+ }
+
+ if (lang_dict) {
+ PyObject *pykey, *trans;
+ Py_ssize_t ppos = 0;
+
+ if (!PyDict_Check(lang_dict)) {
+ printf("WARNING! In translations' dict of \"");
+ PyObject_Print(uuid, stdout, Py_PRINT_RAW);
+ printf("\":\n");
+ printf(
+ " Each language key must have a dictionary as value, \"%s\" is not valid, "
+ "skipping: ",
+ locale);
+ PyObject_Print(lang_dict, stdout, Py_PRINT_RAW);
+ printf("\n");
+ continue;
+ }
+
+ /* Iterate over all translations of the found language dict, and populate our ghash cache. */
+ while (PyDict_Next(lang_dict, &ppos, &pykey, &trans)) {
+ const char *msgctxt = NULL, *msgid = NULL;
+ bool invalid_key = false;
+
+ if ((PyTuple_CheckExact(pykey) == false) || (PyTuple_GET_SIZE(pykey) != 2)) {
+ invalid_key = true;
+ }
+ else {
+ PyObject *tmp = PyTuple_GET_ITEM(pykey, 0);
+ if (tmp == Py_None) {
+ msgctxt = BLT_I18NCONTEXT_DEFAULT_BPYRNA;
+ }
+ else if (PyUnicode_Check(tmp)) {
+ msgctxt = _PyUnicode_AsString(tmp);
+ }
+ else {
+ invalid_key = true;
+ }
+
+ tmp = PyTuple_GET_ITEM(pykey, 1);
+ if (PyUnicode_Check(tmp)) {
+ msgid = _PyUnicode_AsString(tmp);
+ }
+ else {
+ invalid_key = true;
+ }
+ }
+
+ if (invalid_key) {
+ printf("WARNING! In translations' dict of \"");
+ PyObject_Print(uuid, stdout, Py_PRINT_RAW);
+ printf("\", %s language:\n", locale);
+ printf(
+ " Keys must be tuples of (msgctxt [string or None], msgid [string]), "
+ "this one is not valid, skipping: ");
+ PyObject_Print(pykey, stdout, Py_PRINT_RAW);
+ printf("\n");
+ continue;
+ }
+ if (PyUnicode_Check(trans) == false) {
+ printf("WARNING! In translations' dict of \"");
+ PyObject_Print(uuid, stdout, Py_PRINT_RAW);
+ printf("\":\n");
+ printf(" Values must be strings, this one is not valid, skipping: ");
+ PyObject_Print(trans, stdout, Py_PRINT_RAW);
+ printf("\n");
+ continue;
+ }
+
+ /* Do not overwrite existing keys! */
+ if (BPY_app_translations_py_pgettext(msgctxt, msgid) == msgid) {
+ GHashKey *key = _ghashutil_keyalloc(msgctxt, msgid);
+ BLI_ghash_insert(_translations_cache, key, BLI_strdup(_PyUnicode_AsString(trans)));
+ }
+ }
+ }
+ }
+
+ /* Clean up! */
+ MEM_SAFE_FREE(language);
+ MEM_SAFE_FREE(language_country);
+ MEM_SAFE_FREE(language_variant);
}
const char *BPY_app_translations_py_pgettext(const char *msgctxt, const char *msgid)
{
-#define STATIC_LOCALE_SIZE 32 /* Should be more than enough! */
+# define STATIC_LOCALE_SIZE 32 /* Should be more than enough! */
- GHashKey key;
- static char locale[STATIC_LOCALE_SIZE] = "";
- const char *tmp;
+ GHashKey key;
+ static char locale[STATIC_LOCALE_SIZE] = "";
+ const char *tmp;
- /* Just in case, should never happen! */
- if (!_translations) {
- return msgid;
- }
+ /* Just in case, should never happen! */
+ if (!_translations) {
+ return msgid;
+ }
- tmp = BLT_lang_get();
- if (!STREQ(tmp, locale) || !_translations_cache) {
- PyGILState_STATE _py_state;
+ tmp = BLT_lang_get();
+ if (!STREQ(tmp, locale) || !_translations_cache) {
+ PyGILState_STATE _py_state;
- BLI_strncpy(locale, tmp, STATIC_LOCALE_SIZE);
+ BLI_strncpy(locale, tmp, STATIC_LOCALE_SIZE);
- /* Locale changed or cache does not exist, refresh the whole cache! */
- /* This func may be called from C (i.e. outside of python interpreter 'context'). */
- _py_state = PyGILState_Ensure();
+ /* Locale changed or cache does not exist, refresh the whole cache! */
+ /* This func may be called from C (i.e. outside of python interpreter 'context'). */
+ _py_state = PyGILState_Ensure();
- _build_translations_cache(_translations->py_messages, locale);
+ _build_translations_cache(_translations->py_messages, locale);
- PyGILState_Release(_py_state);
- }
+ PyGILState_Release(_py_state);
+ }
- /* And now, simply create the key (context, messageid) and find it in the cached dict! */
- key.msgctxt = BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA : msgctxt;
- key.msgid = msgid;
+ /* And now, simply create the key (context, messageid) and find it in the cached dict! */
+ key.msgctxt = BLT_is_default_context(msgctxt) ? BLT_I18NCONTEXT_DEFAULT_BPYRNA : msgctxt;
+ key.msgid = msgid;
- tmp = BLI_ghash_lookup(_translations_cache, &key);
+ tmp = BLI_ghash_lookup(_translations_cache, &key);
- return tmp ? tmp : msgid;
+ return tmp ? tmp : msgid;
-#undef STATIC_LOCALE_SIZE
+# undef STATIC_LOCALE_SIZE
}
-#endif /* WITH_INTERNATIONAL */
+#endif /* WITH_INTERNATIONAL */
PyDoc_STRVAR(app_translations_py_messages_register_doc,
-".. method:: register(module_name, translations_dict)\n"
-"\n"
-" Registers an addon's UI translations.\n"
-"\n"
-" .. note::\n"
-" Does nothing when Blender is built without internationalization support.\n"
-"\n"
-" :arg module_name: The name identifying the addon.\n"
-" :type module_name: string\n"
-" :arg translations_dict: A dictionary built like that:\n"
-" ``{locale: {msg_key: msg_translation, ...}, ...}``\n"
-" :type translations_dict: dict\n"
-"\n"
-);
-static PyObject *app_translations_py_messages_register(BlenderAppTranslations *self, PyObject *args, PyObject *kw)
+ ".. method:: register(module_name, translations_dict)\n"
+ "\n"
+ " Registers an addon's UI translations.\n"
+ "\n"
+ " .. note::\n"
+ " Does nothing when Blender is built without internationalization support.\n"
+ "\n"
+ " :arg module_name: The name identifying the addon.\n"
+ " :type module_name: string\n"
+ " :arg translations_dict: A dictionary built like that:\n"
+ " ``{locale: {msg_key: msg_translation, ...}, ...}``\n"
+ " :type translations_dict: dict\n"
+ "\n");
+static PyObject *app_translations_py_messages_register(BlenderAppTranslations *self,
+ PyObject *args,
+ PyObject *kw)
{
#ifdef WITH_INTERNATIONAL
- static const char *kwlist[] = {"module_name", "translations_dict", NULL};
- PyObject *module_name, *uuid_dict;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!:bpy.app.translations.register", (char **)kwlist, &PyUnicode_Type,
- &module_name, &PyDict_Type, &uuid_dict))
- {
- return NULL;
- }
-
- if (PyDict_Contains(self->py_messages, module_name)) {
- PyErr_Format(PyExc_ValueError,
- "bpy.app.translations.register: translations message cache already contains some data for "
- "addon '%s'", (const char *)_PyUnicode_AsString(module_name));
- return NULL;
- }
-
- PyDict_SetItem(self->py_messages, module_name, uuid_dict);
-
- /* Clear cached messages dict! */
- _clear_translations_cache();
+ static const char *kwlist[] = {"module_name", "translations_dict", NULL};
+ PyObject *module_name, *uuid_dict;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O!O!:bpy.app.translations.register",
+ (char **)kwlist,
+ &PyUnicode_Type,
+ &module_name,
+ &PyDict_Type,
+ &uuid_dict)) {
+ return NULL;
+ }
+
+ if (PyDict_Contains(self->py_messages, module_name)) {
+ PyErr_Format(
+ PyExc_ValueError,
+ "bpy.app.translations.register: translations message cache already contains some data for "
+ "addon '%s'",
+ (const char *)_PyUnicode_AsString(module_name));
+ return NULL;
+ }
+
+ PyDict_SetItem(self->py_messages, module_name, uuid_dict);
+
+ /* Clear cached messages dict! */
+ _clear_translations_cache();
#else
- (void)self;
- (void)args;
- (void)kw;
+ (void)self;
+ (void)args;
+ (void)kw;
#endif
- /* And we are done! */
- Py_RETURN_NONE;
+ /* And we are done! */
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(app_translations_py_messages_unregister_doc,
-".. method:: unregister(module_name)\n"
-"\n"
-" Unregisters an addon's UI translations.\n"
-"\n"
-" .. note::\n"
-" Does nothing when Blender is built without internationalization support.\n"
-"\n"
-" :arg module_name: The name identifying the addon.\n"
-" :type module_name: string\n"
-"\n"
-);
-static PyObject *app_translations_py_messages_unregister(BlenderAppTranslations *self, PyObject *args, PyObject *kw)
+ ".. method:: unregister(module_name)\n"
+ "\n"
+ " Unregisters an addon's UI translations.\n"
+ "\n"
+ " .. note::\n"
+ " Does nothing when Blender is built without internationalization support.\n"
+ "\n"
+ " :arg module_name: The name identifying the addon.\n"
+ " :type module_name: string\n"
+ "\n");
+static PyObject *app_translations_py_messages_unregister(BlenderAppTranslations *self,
+ PyObject *args,
+ PyObject *kw)
{
#ifdef WITH_INTERNATIONAL
- static const char *kwlist[] = {"module_name", NULL};
- PyObject *module_name;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "O!:bpy.app.translations.unregister", (char **)kwlist, &PyUnicode_Type,
- &module_name))
- {
- return NULL;
- }
-
- if (PyDict_Contains(self->py_messages, module_name)) {
- PyDict_DelItem(self->py_messages, module_name);
- /* Clear cached messages ghash! */
- _clear_translations_cache();
- }
+ static const char *kwlist[] = {"module_name", NULL};
+ PyObject *module_name;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "O!:bpy.app.translations.unregister",
+ (char **)kwlist,
+ &PyUnicode_Type,
+ &module_name)) {
+ return NULL;
+ }
+
+ if (PyDict_Contains(self->py_messages, module_name)) {
+ PyDict_DelItem(self->py_messages, module_name);
+ /* Clear cached messages ghash! */
+ _clear_translations_cache();
+ }
#else
- (void)self;
- (void)args;
- (void)kw;
+ (void)self;
+ (void)args;
+ (void)kw;
#endif
- /* And we are done! */
- Py_RETURN_NONE;
+ /* And we are done! */
+ Py_RETURN_NONE;
}
/***** C-defined contexts *****/
@@ -379,450 +395,499 @@ static BLT_i18n_contexts_descriptor _contexts[] = BLT_I18NCONTEXTS_DESC;
/* These fields are just empty placeholders, actual values get set in app_translations_struct().
* This allows us to avoid many handwriting, and above all, to keep all context definition stuff in BLT_translation.h!
*/
-static PyStructSequence_Field
-app_translations_contexts_fields[ARRAY_SIZE(_contexts)] = {{NULL}};
+static PyStructSequence_Field app_translations_contexts_fields[ARRAY_SIZE(_contexts)] = {{NULL}};
static PyStructSequence_Desc app_translations_contexts_desc = {
- (char *)"bpy.app.translations.contexts", /* name */
- (char *)"This named tuple contains all pre-defined translation contexts", /* doc */
- app_translations_contexts_fields, /* fields */
- ARRAY_SIZE(app_translations_contexts_fields) - 1,
+ (char *)"bpy.app.translations.contexts", /* name */
+ (char *)"This named tuple contains all pre-defined translation contexts", /* doc */
+ app_translations_contexts_fields, /* fields */
+ ARRAY_SIZE(app_translations_contexts_fields) - 1,
};
static PyObject *app_translations_contexts_make(void)
{
- PyObject *translations_contexts;
- BLT_i18n_contexts_descriptor *ctxt;
- int pos = 0;
-
- translations_contexts = PyStructSequence_New(&BlenderAppTranslationsContextsType);
- if (translations_contexts == NULL) {
- return NULL;
- }
-
-#define SetObjString(item) PyStructSequence_SET_ITEM(translations_contexts, pos++, PyUnicode_FromString((item)))
-#define SetObjNone() PyStructSequence_SET_ITEM(translations_contexts, pos++, Py_INCREF_RET(Py_None))
-
- for (ctxt = _contexts; ctxt->c_id; ctxt++) {
- if (ctxt->value) {
- SetObjString(ctxt->value);
- }
- else {
- SetObjNone();
- }
- }
+ PyObject *translations_contexts;
+ BLT_i18n_contexts_descriptor *ctxt;
+ int pos = 0;
+
+ translations_contexts = PyStructSequence_New(&BlenderAppTranslationsContextsType);
+ if (translations_contexts == NULL) {
+ return NULL;
+ }
+
+#define SetObjString(item) \
+ PyStructSequence_SET_ITEM(translations_contexts, pos++, PyUnicode_FromString((item)))
+#define SetObjNone() \
+ PyStructSequence_SET_ITEM(translations_contexts, pos++, Py_INCREF_RET(Py_None))
+
+ for (ctxt = _contexts; ctxt->c_id; ctxt++) {
+ if (ctxt->value) {
+ SetObjString(ctxt->value);
+ }
+ else {
+ SetObjNone();
+ }
+ }
#undef SetObjString
#undef SetObjNone
- return translations_contexts;
+ return translations_contexts;
}
/***** Main BlenderAppTranslations Py object definition *****/
PyDoc_STRVAR(app_translations_contexts_doc,
-"A named tuple containing all pre-defined translation contexts.\n"
-"\n"
-".. warning::\n"
-" Never use a (new) context starting with \"" BLT_I18NCONTEXT_DEFAULT_BPYRNA "\", it would be internally\n"
-" assimilated as the default one!\n"
-);
+ "A named tuple containing all pre-defined translation contexts.\n"
+ "\n"
+ ".. warning::\n"
+ " Never use a (new) context starting with \"" BLT_I18NCONTEXT_DEFAULT_BPYRNA
+ "\", it would be internally\n"
+ " assimilated as the default one!\n");
PyDoc_STRVAR(app_translations_contexts_C_to_py_doc,
- "A readonly dict mapping contexts' C-identifiers to their py-identifiers."
-);
+ "A readonly dict mapping contexts' C-identifiers to their py-identifiers.");
static PyMemberDef app_translations_members[] = {
- {(char *)"contexts", T_OBJECT_EX, offsetof(BlenderAppTranslations, contexts), READONLY,
- app_translations_contexts_doc},
- {(char *)"contexts_C_to_py", T_OBJECT_EX, offsetof(BlenderAppTranslations, contexts_C_to_py), READONLY,
- app_translations_contexts_C_to_py_doc},
- {NULL},
+ {(char *)"contexts",
+ T_OBJECT_EX,
+ offsetof(BlenderAppTranslations, contexts),
+ READONLY,
+ app_translations_contexts_doc},
+ {(char *)"contexts_C_to_py",
+ T_OBJECT_EX,
+ offsetof(BlenderAppTranslations, contexts_C_to_py),
+ READONLY,
+ app_translations_contexts_C_to_py_doc},
+ {NULL},
};
PyDoc_STRVAR(app_translations_locale_doc,
-"The actual locale currently in use (will always return a void string when Blender is built without "
-"internationalization support)."
-);
+ "The actual locale currently in use (will always return a void string when Blender "
+ "is built without "
+ "internationalization support).");
static PyObject *app_translations_locale_get(PyObject *UNUSED(self), void *UNUSED(userdata))
{
- return PyUnicode_FromString(BLT_lang_get());
+ return PyUnicode_FromString(BLT_lang_get());
}
/* Note: defining as getter, as (even if quite unlikely), this *may* change during runtime... */
-PyDoc_STRVAR(app_translations_locales_doc, "All locales currently known by Blender (i.e. available as translations).");
+PyDoc_STRVAR(app_translations_locales_doc,
+ "All locales currently known by Blender (i.e. available as translations).");
static PyObject *app_translations_locales_get(PyObject *UNUSED(self), void *UNUSED(userdata))
{
- PyObject *ret;
- EnumPropertyItem *it, *items = BLT_lang_RNA_enum_properties();
- int num_locales = 0, pos = 0;
-
- if (items) {
- /* This is not elegant, but simple! */
- for (it = items; it->identifier; it++) {
- if (it->value) {
- num_locales++;
- }
- }
- }
-
- ret = PyTuple_New(num_locales);
-
- if (items) {
- for (it = items; it->identifier; it++) {
- if (it->value) {
- PyTuple_SET_ITEM(ret, pos++, PyUnicode_FromString(it->description));
- }
- }
- }
-
- return ret;
+ PyObject *ret;
+ EnumPropertyItem *it, *items = BLT_lang_RNA_enum_properties();
+ int num_locales = 0, pos = 0;
+
+ if (items) {
+ /* This is not elegant, but simple! */
+ for (it = items; it->identifier; it++) {
+ if (it->value) {
+ num_locales++;
+ }
+ }
+ }
+
+ ret = PyTuple_New(num_locales);
+
+ if (items) {
+ for (it = items; it->identifier; it++) {
+ if (it->value) {
+ PyTuple_SET_ITEM(ret, pos++, PyUnicode_FromString(it->description));
+ }
+ }
+ }
+
+ return ret;
}
static PyGetSetDef app_translations_getseters[] = {
- /* {name, getter, setter, doc, userdata} */
- {(char *)"locale", (getter)app_translations_locale_get, NULL, app_translations_locale_doc, NULL},
- {(char *)"locales", (getter)app_translations_locales_get, NULL, app_translations_locales_doc, NULL},
- {NULL},
+ /* {name, getter, setter, doc, userdata} */
+ {(char *)"locale",
+ (getter)app_translations_locale_get,
+ NULL,
+ app_translations_locale_doc,
+ NULL},
+ {(char *)"locales",
+ (getter)app_translations_locales_get,
+ NULL,
+ app_translations_locales_doc,
+ NULL},
+ {NULL},
};
/* pgettext helper. */
-static PyObject *_py_pgettext(PyObject *args, PyObject *kw, const char *(*_pgettext)(const char *, const char *))
+static PyObject *_py_pgettext(PyObject *args,
+ PyObject *kw,
+ const char *(*_pgettext)(const char *, const char *))
{
- static const char *kwlist[] = {"msgid", "msgctxt", NULL};
+ static const char *kwlist[] = {"msgid", "msgctxt", NULL};
#ifdef WITH_INTERNATIONAL
- char *msgid, *msgctxt = NULL;
+ char *msgid, *msgctxt = NULL;
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s|z:bpy.app.translations.pgettext",
- (char **)kwlist, &msgid, &msgctxt))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "s|z:bpy.app.translations.pgettext", (char **)kwlist, &msgid, &msgctxt)) {
+ return NULL;
+ }
- return PyUnicode_FromString((*_pgettext)(msgctxt ? msgctxt : BLT_I18NCONTEXT_DEFAULT, msgid));
+ return PyUnicode_FromString((*_pgettext)(msgctxt ? msgctxt : BLT_I18NCONTEXT_DEFAULT, msgid));
#else
- PyObject *msgid, *msgctxt;
- (void)_pgettext;
+ PyObject *msgid, *msgctxt;
+ (void)_pgettext;
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "O|O:bpy.app.translations.pgettext",
- (char **)kwlist, &msgid, &msgctxt))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "O|O:bpy.app.translations.pgettext", (char **)kwlist, &msgid, &msgctxt)) {
+ return NULL;
+ }
- return Py_INCREF_RET(msgid);
+ return Py_INCREF_RET(msgid);
#endif
}
-PyDoc_STRVAR(app_translations_pgettext_doc,
-".. method:: pgettext(msgid, msgctxt)\n"
-"\n"
-" Try to translate the given msgid (with optional msgctxt).\n"
-"\n"
-" .. note::\n"
-" The ``(msgid, msgctxt)`` parameters order has been switched compared to gettext function, to allow\n"
-" single-parameter calls (context then defaults to BLT_I18NCONTEXT_DEFAULT).\n"
-"\n"
-" .. note::\n"
-" You should really rarely need to use this function in regular addon code, as all translation should be\n"
-" handled by Blender internal code. The only exception are string containing formatting (like \"File: %r\"),\n"
-" but you should rather use :func:`pgettext_iface`/:func:`pgettext_tip` in those cases!\n"
-"\n"
-" .. note::\n"
-" Does nothing when Blender is built without internationalization support (hence always returns ``msgid``).\n"
-"\n"
-" :arg msgid: The string to translate.\n"
-" :type msgid: string\n"
-" :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
-" :type msgctxt: string or None\n"
-" :return: The translated string (or msgid if no translation was found).\n"
-"\n"
-);
-static PyObject *app_translations_pgettext(BlenderAppTranslations *UNUSED(self), PyObject *args, PyObject *kw)
+PyDoc_STRVAR(
+ app_translations_pgettext_doc,
+ ".. method:: pgettext(msgid, msgctxt)\n"
+ "\n"
+ " Try to translate the given msgid (with optional msgctxt).\n"
+ "\n"
+ " .. note::\n"
+ " The ``(msgid, msgctxt)`` parameters order has been switched compared to gettext "
+ "function, to allow\n"
+ " single-parameter calls (context then defaults to BLT_I18NCONTEXT_DEFAULT).\n"
+ "\n"
+ " .. note::\n"
+ " You should really rarely need to use this function in regular addon code, as all "
+ "translation should be\n"
+ " handled by Blender internal code. The only exception are string containing formatting "
+ "(like \"File: %r\"),\n"
+ " but you should rather use :func:`pgettext_iface`/:func:`pgettext_tip` in those cases!\n"
+ "\n"
+ " .. note::\n"
+ " Does nothing when Blender is built without internationalization support (hence always "
+ "returns ``msgid``).\n"
+ "\n"
+ " :arg msgid: The string to translate.\n"
+ " :type msgid: string\n"
+ " :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
+ " :type msgctxt: string or None\n"
+ " :return: The translated string (or msgid if no translation was found).\n"
+ "\n");
+static PyObject *app_translations_pgettext(BlenderAppTranslations *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- return _py_pgettext(args, kw, BLT_pgettext);
+ return _py_pgettext(args, kw, BLT_pgettext);
}
PyDoc_STRVAR(app_translations_pgettext_iface_doc,
-".. method:: pgettext_iface(msgid, msgctxt)\n"
-"\n"
-" Try to translate the given msgid (with optional msgctxt), if labels' translation is enabled.\n"
-"\n"
-" .. note::\n"
-" See :func:`pgettext` notes.\n"
-"\n"
-" :arg msgid: The string to translate.\n"
-" :type msgid: string\n"
-" :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
-" :type msgctxt: string or None\n"
-" :return: The translated string (or msgid if no translation was found).\n"
-"\n"
-);
-static PyObject *app_translations_pgettext_iface(BlenderAppTranslations *UNUSED(self), PyObject *args, PyObject *kw)
+ ".. method:: pgettext_iface(msgid, msgctxt)\n"
+ "\n"
+ " Try to translate the given msgid (with optional msgctxt), if labels' translation "
+ "is enabled.\n"
+ "\n"
+ " .. note::\n"
+ " See :func:`pgettext` notes.\n"
+ "\n"
+ " :arg msgid: The string to translate.\n"
+ " :type msgid: string\n"
+ " :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
+ " :type msgctxt: string or None\n"
+ " :return: The translated string (or msgid if no translation was found).\n"
+ "\n");
+static PyObject *app_translations_pgettext_iface(BlenderAppTranslations *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- return _py_pgettext(args, kw, BLT_translate_do_iface);
+ return _py_pgettext(args, kw, BLT_translate_do_iface);
}
PyDoc_STRVAR(app_translations_pgettext_tip_doc,
-".. method:: pgettext_tip(msgid, msgctxt)\n"
-"\n"
-" Try to translate the given msgid (with optional msgctxt), if tooltips' translation is enabled.\n"
-"\n"
-" .. note::\n"
-" See :func:`pgettext` notes.\n"
-"\n"
-" :arg msgid: The string to translate.\n"
-" :type msgid: string\n"
-" :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
-" :type msgctxt: string or None\n"
-" :return: The translated string (or msgid if no translation was found).\n"
-"\n"
-);
-static PyObject *app_translations_pgettext_tip(BlenderAppTranslations *UNUSED(self), PyObject *args, PyObject *kw)
+ ".. method:: pgettext_tip(msgid, msgctxt)\n"
+ "\n"
+ " Try to translate the given msgid (with optional msgctxt), if tooltips' "
+ "translation is enabled.\n"
+ "\n"
+ " .. note::\n"
+ " See :func:`pgettext` notes.\n"
+ "\n"
+ " :arg msgid: The string to translate.\n"
+ " :type msgid: string\n"
+ " :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
+ " :type msgctxt: string or None\n"
+ " :return: The translated string (or msgid if no translation was found).\n"
+ "\n");
+static PyObject *app_translations_pgettext_tip(BlenderAppTranslations *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- return _py_pgettext(args, kw, BLT_translate_do_tooltip);
+ return _py_pgettext(args, kw, BLT_translate_do_tooltip);
}
PyDoc_STRVAR(app_translations_pgettext_data_doc,
-".. method:: pgettext_data(msgid, msgctxt)\n"
-"\n"
-" Try to translate the given msgid (with optional msgctxt), if new data name's translation is enabled.\n"
-"\n"
-" .. note::\n"
-" See :func:`pgettext` notes.\n"
-"\n"
-" :arg msgid: The string to translate.\n"
-" :type msgid: string\n"
-" :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
-" :type msgctxt: string or None\n"
-" :return: The translated string (or ``msgid`` if no translation was found).\n"
-"\n"
-);
-static PyObject *app_translations_pgettext_data(BlenderAppTranslations *UNUSED(self), PyObject *args, PyObject *kw)
+ ".. method:: pgettext_data(msgid, msgctxt)\n"
+ "\n"
+ " Try to translate the given msgid (with optional msgctxt), if new data name's "
+ "translation is enabled.\n"
+ "\n"
+ " .. note::\n"
+ " See :func:`pgettext` notes.\n"
+ "\n"
+ " :arg msgid: The string to translate.\n"
+ " :type msgid: string\n"
+ " :arg msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).\n"
+ " :type msgctxt: string or None\n"
+ " :return: The translated string (or ``msgid`` if no translation was found).\n"
+ "\n");
+static PyObject *app_translations_pgettext_data(BlenderAppTranslations *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- return _py_pgettext(args, kw, BLT_translate_do_new_dataname);
+ return _py_pgettext(args, kw, BLT_translate_do_new_dataname);
}
-PyDoc_STRVAR(app_translations_locale_explode_doc,
-".. method:: locale_explode(locale)\n"
-"\n"
-" Return all components and their combinations of the given ISO locale string.\n"
-"\n"
-" >>> bpy.app.translations.locale_explode(\"sr_RS@latin\")\n"
-" (\"sr\", \"RS\", \"latin\", \"sr_RS\", \"sr@latin\")\n"
-"\n"
-" For non-complete locales, missing elements will be None.\n"
-"\n"
-" :arg locale: The ISO locale string to explode.\n"
-" :type msgid: string\n"
-" :return: A tuple ``(language, country, variant, language_country, language@variant)``.\n"
-"\n"
-);
-static PyObject *app_translations_locale_explode(BlenderAppTranslations *UNUSED(self), PyObject *args, PyObject *kw)
+PyDoc_STRVAR(
+ app_translations_locale_explode_doc,
+ ".. method:: locale_explode(locale)\n"
+ "\n"
+ " Return all components and their combinations of the given ISO locale string.\n"
+ "\n"
+ " >>> bpy.app.translations.locale_explode(\"sr_RS@latin\")\n"
+ " (\"sr\", \"RS\", \"latin\", \"sr_RS\", \"sr@latin\")\n"
+ "\n"
+ " For non-complete locales, missing elements will be None.\n"
+ "\n"
+ " :arg locale: The ISO locale string to explode.\n"
+ " :type msgid: string\n"
+ " :return: A tuple ``(language, country, variant, language_country, language@variant)``.\n"
+ "\n");
+static PyObject *app_translations_locale_explode(BlenderAppTranslations *UNUSED(self),
+ PyObject *args,
+ PyObject *kw)
{
- PyObject *ret_tuple;
- static const char *kwlist[] = {"locale", NULL};
- const char *locale;
- char *language, *country, *variant, *language_country, *language_variant;
+ PyObject *ret_tuple;
+ static const char *kwlist[] = {"locale", NULL};
+ const char *locale;
+ char *language, *country, *variant, *language_country, *language_variant;
- if (!PyArg_ParseTupleAndKeywords(args, kw, "s:bpy.app.translations.locale_explode", (char **)kwlist, &locale)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "s:bpy.app.translations.locale_explode", (char **)kwlist, &locale)) {
+ return NULL;
+ }
- BLT_lang_locale_explode(locale, &language, &country, &variant, &language_country, &language_variant);
+ BLT_lang_locale_explode(
+ locale, &language, &country, &variant, &language_country, &language_variant);
- ret_tuple = Py_BuildValue("sssss", language, country, variant, language_country, language_variant);
+ ret_tuple = Py_BuildValue(
+ "sssss", language, country, variant, language_country, language_variant);
- MEM_SAFE_FREE(language);
- MEM_SAFE_FREE(country);
- MEM_SAFE_FREE(variant);
- MEM_SAFE_FREE(language_country);
- MEM_SAFE_FREE(language_variant);
+ MEM_SAFE_FREE(language);
+ MEM_SAFE_FREE(country);
+ MEM_SAFE_FREE(variant);
+ MEM_SAFE_FREE(language_country);
+ MEM_SAFE_FREE(language_variant);
- return ret_tuple;
+ return ret_tuple;
}
static PyMethodDef app_translations_methods[] = {
- /* Can't use METH_KEYWORDS alone, see http://bugs.python.org/issue11587 */
- {"register", (PyCFunction)app_translations_py_messages_register, METH_VARARGS | METH_KEYWORDS,
- app_translations_py_messages_register_doc},
- {"unregister", (PyCFunction)app_translations_py_messages_unregister, METH_VARARGS | METH_KEYWORDS,
- app_translations_py_messages_unregister_doc},
- {"pgettext", (PyCFunction)app_translations_pgettext, METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- app_translations_pgettext_doc},
- {"pgettext_iface", (PyCFunction)app_translations_pgettext_iface, METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- app_translations_pgettext_iface_doc},
- {"pgettext_tip", (PyCFunction)app_translations_pgettext_tip, METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- app_translations_pgettext_tip_doc},
- {"pgettext_data", (PyCFunction)app_translations_pgettext_data, METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- app_translations_pgettext_data_doc},
- {"locale_explode", (PyCFunction)app_translations_locale_explode, METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- app_translations_locale_explode_doc},
- {NULL},
+ /* Can't use METH_KEYWORDS alone, see http://bugs.python.org/issue11587 */
+ {"register",
+ (PyCFunction)app_translations_py_messages_register,
+ METH_VARARGS | METH_KEYWORDS,
+ app_translations_py_messages_register_doc},
+ {"unregister",
+ (PyCFunction)app_translations_py_messages_unregister,
+ METH_VARARGS | METH_KEYWORDS,
+ app_translations_py_messages_unregister_doc},
+ {"pgettext",
+ (PyCFunction)app_translations_pgettext,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ app_translations_pgettext_doc},
+ {"pgettext_iface",
+ (PyCFunction)app_translations_pgettext_iface,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ app_translations_pgettext_iface_doc},
+ {"pgettext_tip",
+ (PyCFunction)app_translations_pgettext_tip,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ app_translations_pgettext_tip_doc},
+ {"pgettext_data",
+ (PyCFunction)app_translations_pgettext_data,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ app_translations_pgettext_data_doc},
+ {"locale_explode",
+ (PyCFunction)app_translations_locale_explode,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ app_translations_locale_explode_doc},
+ {NULL},
};
-static PyObject *app_translations_new(PyTypeObject *type, PyObject *UNUSED(args), PyObject *UNUSED(kw))
+static PyObject *app_translations_new(PyTypeObject *type,
+ PyObject *UNUSED(args),
+ PyObject *UNUSED(kw))
{
-/* printf("%s (%p)\n", __func__, _translations); */
-
- if (!_translations) {
- _translations = (BlenderAppTranslations *)type->tp_alloc(type, 0);
- if (_translations) {
- PyObject *py_ctxts;
- BLT_i18n_contexts_descriptor *ctxt;
-
- _translations->contexts = app_translations_contexts_make();
-
- py_ctxts = _PyDict_NewPresized(ARRAY_SIZE(_contexts));
- for (ctxt = _contexts; ctxt->c_id; ctxt++) {
- PyObject *val = PyUnicode_FromString(ctxt->py_id);
- PyDict_SetItemString(py_ctxts, ctxt->c_id, val);
- Py_DECREF(val);
- }
- _translations->contexts_C_to_py = PyDictProxy_New(py_ctxts);
- Py_DECREF(py_ctxts); /* The actual dict is only owned by its proxy */
-
- _translations->py_messages = PyDict_New();
- }
- }
-
- return (PyObject *)_translations;
+ /* printf("%s (%p)\n", __func__, _translations); */
+
+ if (!_translations) {
+ _translations = (BlenderAppTranslations *)type->tp_alloc(type, 0);
+ if (_translations) {
+ PyObject *py_ctxts;
+ BLT_i18n_contexts_descriptor *ctxt;
+
+ _translations->contexts = app_translations_contexts_make();
+
+ py_ctxts = _PyDict_NewPresized(ARRAY_SIZE(_contexts));
+ for (ctxt = _contexts; ctxt->c_id; ctxt++) {
+ PyObject *val = PyUnicode_FromString(ctxt->py_id);
+ PyDict_SetItemString(py_ctxts, ctxt->c_id, val);
+ Py_DECREF(val);
+ }
+ _translations->contexts_C_to_py = PyDictProxy_New(py_ctxts);
+ Py_DECREF(py_ctxts); /* The actual dict is only owned by its proxy */
+
+ _translations->py_messages = PyDict_New();
+ }
+ }
+
+ return (PyObject *)_translations;
}
static void app_translations_free(void *obj)
{
- PyObject_Del(obj);
+ PyObject_Del(obj);
#ifdef WITH_INTERNATIONAL
- _clear_translations_cache();
+ _clear_translations_cache();
#endif
}
PyDoc_STRVAR(app_translations_doc,
-"This object contains some data/methods regarding internationalization in Blender, and allows every py script\n"
-"to feature translations for its own UI messages.\n"
-"\n"
-);
+ "This object contains some data/methods regarding internationalization in Blender, "
+ "and allows every py script\n"
+ "to feature translations for its own UI messages.\n"
+ "\n");
static PyTypeObject BlenderAppTranslationsType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* tp_name */
- "bpy.app._translations_type",
- /* tp_basicsize */
- sizeof(BlenderAppTranslations),
- 0, /* tp_itemsize */
- /* methods */
- /* No destructor, this is a singleton! */
- NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* tp_repr */
-
- /* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- app_translations_doc, /* char *tp_doc; Documentation string */
-
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- app_translations_methods, /* struct PyMethodDef *tp_methods; */
- app_translations_members, /* struct PyMemberDef *tp_members; */
- app_translations_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- /* newfunc tp_new; */
- (newfunc)app_translations_new,
- /* Low-level free-memory routine */
- app_translations_free, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* tp_name */
+ "bpy.app._translations_type",
+ /* tp_basicsize */
+ sizeof(BlenderAppTranslations),
+ 0, /* tp_itemsize */
+ /* methods */
+ /* No destructor, this is a singleton! */
+ NULL, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL, /* tp_repr */
+
+ /* Method suites for standard classes */
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ app_translations_doc, /* char *tp_doc; Documentation string */
+
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ app_translations_methods, /* struct PyMethodDef *tp_methods; */
+ app_translations_members, /* struct PyMemberDef *tp_members; */
+ app_translations_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ /* newfunc tp_new; */
+ (newfunc)app_translations_new,
+ /* Low-level free-memory routine */
+ app_translations_free, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
PyObject *BPY_app_translations_struct(void)
{
- PyObject *ret;
+ PyObject *ret;
- /* Let's finalize our contexts structseq definition! */
- {
- BLT_i18n_contexts_descriptor *ctxt;
- PyStructSequence_Field *desc;
+ /* Let's finalize our contexts structseq definition! */
+ {
+ BLT_i18n_contexts_descriptor *ctxt;
+ PyStructSequence_Field *desc;
- /* We really populate the contexts' fields here! */
- for (ctxt = _contexts, desc = app_translations_contexts_desc.fields; ctxt->c_id; ctxt++, desc++) {
- desc->name = (char *)ctxt->py_id;
- desc->doc = NULL;
- }
- desc->name = desc->doc = NULL; /* End sentinel! */
+ /* We really populate the contexts' fields here! */
+ for (ctxt = _contexts, desc = app_translations_contexts_desc.fields; ctxt->c_id;
+ ctxt++, desc++) {
+ desc->name = (char *)ctxt->py_id;
+ desc->doc = NULL;
+ }
+ desc->name = desc->doc = NULL; /* End sentinel! */
- PyStructSequence_InitType(&BlenderAppTranslationsContextsType, &app_translations_contexts_desc);
- }
+ PyStructSequence_InitType(&BlenderAppTranslationsContextsType,
+ &app_translations_contexts_desc);
+ }
- if (PyType_Ready(&BlenderAppTranslationsType) < 0) {
- return NULL;
- }
+ if (PyType_Ready(&BlenderAppTranslationsType) < 0) {
+ return NULL;
+ }
- ret = PyObject_CallObject((PyObject *)&BlenderAppTranslationsType, NULL);
+ ret = PyObject_CallObject((PyObject *)&BlenderAppTranslationsType, NULL);
- /* prevent user from creating new instances */
- BlenderAppTranslationsType.tp_new = NULL;
- /* without this we can't do set(sys.modules) [#29635] */
- BlenderAppTranslationsType.tp_hash = (hashfunc)_Py_HashPointer;
+ /* prevent user from creating new instances */
+ BlenderAppTranslationsType.tp_new = NULL;
+ /* without this we can't do set(sys.modules) [#29635] */
+ BlenderAppTranslationsType.tp_hash = (hashfunc)_Py_HashPointer;
- return ret;
+ return ret;
}
void BPY_app_translations_end(void)
{
- /* Incase the object remains in a module's namespace, see T44127. */
+ /* Incase the object remains in a module's namespace, see T44127. */
#ifdef WITH_INTERNATIONAL
- _clear_translations_cache();
+ _clear_translations_cache();
#endif
}
diff --git a/source/blender/python/intern/bpy_app_translations.h b/source/blender/python/intern/bpy_app_translations.h
index a8eca079f37..e1e82480b49 100644
--- a/source/blender/python/intern/bpy_app_translations.h
+++ b/source/blender/python/intern/bpy_app_translations.h
@@ -22,6 +22,6 @@
#define __BPY_APP_TRANSLATIONS_H__
PyObject *BPY_app_translations_struct(void);
-void BPY_app_translations_end(void);
+void BPY_app_translations_end(void);
#endif /* __BPY_APP_TRANSLATIONS_H__ */
diff --git a/source/blender/python/intern/bpy_capi_utils.c b/source/blender/python/intern/bpy_capi_utils.c
index 549a06f5b28..db1684a7bca 100644
--- a/source/blender/python/intern/bpy_capi_utils.c
+++ b/source/blender/python/intern/bpy_capi_utils.c
@@ -38,42 +38,48 @@
#include "../generic/py_capi_utils.h"
static bContext *__py_context = NULL;
-bContext *BPy_GetContext(void) { return __py_context; }
-void BPy_SetContext(bContext *C) { __py_context = C; }
+bContext *BPy_GetContext(void)
+{
+ return __py_context;
+}
+void BPy_SetContext(bContext *C)
+{
+ __py_context = C;
+}
char *BPy_enum_as_string(const EnumPropertyItem *item)
{
- DynStr *dynstr = BLI_dynstr_new();
- const EnumPropertyItem *e;
- char *cstring;
-
- for (e = item; item->identifier; item++) {
- if (item->identifier[0]) {
- BLI_dynstr_appendf(dynstr, (e == item) ? "'%s'" : ", '%s'", item->identifier);
- }
- }
-
- cstring = BLI_dynstr_get_cstring(dynstr);
- BLI_dynstr_free(dynstr);
- return cstring;
+ DynStr *dynstr = BLI_dynstr_new();
+ const EnumPropertyItem *e;
+ char *cstring;
+
+ for (e = item; item->identifier; item++) {
+ if (item->identifier[0]) {
+ BLI_dynstr_appendf(dynstr, (e == item) ? "'%s'" : ", '%s'", item->identifier);
+ }
+ }
+
+ cstring = BLI_dynstr_get_cstring(dynstr);
+ BLI_dynstr_free(dynstr);
+ return cstring;
}
short BPy_reports_to_error(ReportList *reports, PyObject *exception, const bool clear)
{
- char *report_str;
+ char *report_str;
- report_str = BKE_reports_string(reports, RPT_ERROR);
+ report_str = BKE_reports_string(reports, RPT_ERROR);
- if (clear == true) {
- BKE_reports_clear(reports);
- }
+ if (clear == true) {
+ BKE_reports_clear(reports);
+ }
- if (report_str) {
- PyErr_SetString(exception, report_str);
- MEM_freeN(report_str);
- }
+ if (report_str) {
+ PyErr_SetString(exception, report_str);
+ MEM_freeN(report_str);
+ }
- return (report_str == NULL) ? 0 : -1;
+ return (report_str == NULL) ? 0 : -1;
}
/**
@@ -81,80 +87,78 @@ short BPy_reports_to_error(ReportList *reports, PyObject *exception, const bool
*/
void BPy_reports_write_stdout(const ReportList *reports, const char *header)
{
- if (header) {
- PySys_WriteStdout("%s\n", header);
- }
+ if (header) {
+ PySys_WriteStdout("%s\n", header);
+ }
- for (const Report *report = reports->list.first; report; report = report->next) {
- PySys_WriteStdout("%s: %s\n", report->typestr, report->message);
- }
+ for (const Report *report = reports->list.first; report; report = report->next) {
+ PySys_WriteStdout("%s: %s\n", report->typestr, report->message);
+ }
}
bool BPy_errors_to_report_ex(ReportList *reports, const bool use_full, const bool use_location)
{
- PyObject *pystring;
-
- if (!PyErr_Occurred()) {
- return 1;
- }
-
- /* less hassle if we allow NULL */
- if (reports == NULL) {
- PyErr_Print();
- PyErr_Clear();
- return 1;
- }
-
- if (use_full) {
- pystring = PyC_ExceptionBuffer();
- }
- else {
- pystring = PyC_ExceptionBuffer_Simple();
- }
-
- if (pystring == NULL) {
- BKE_report(reports, RPT_ERROR, "Unknown py-exception, could not convert");
- return 0;
- }
-
- if (use_location) {
- const char *filename;
- int lineno;
-
- PyObject *pystring_format; /* workaround, see below */
- const char *cstring;
-
- PyC_FileAndNum(&filename, &lineno);
- if (filename == NULL) {
- filename = "<unknown location>";
- }
+ PyObject *pystring;
+
+ if (!PyErr_Occurred()) {
+ return 1;
+ }
+
+ /* less hassle if we allow NULL */
+ if (reports == NULL) {
+ PyErr_Print();
+ PyErr_Clear();
+ return 1;
+ }
+
+ if (use_full) {
+ pystring = PyC_ExceptionBuffer();
+ }
+ else {
+ pystring = PyC_ExceptionBuffer_Simple();
+ }
+
+ if (pystring == NULL) {
+ BKE_report(reports, RPT_ERROR, "Unknown py-exception, could not convert");
+ return 0;
+ }
+
+ if (use_location) {
+ const char *filename;
+ int lineno;
+
+ PyObject *pystring_format; /* workaround, see below */
+ const char *cstring;
+
+ PyC_FileAndNum(&filename, &lineno);
+ if (filename == NULL) {
+ filename = "<unknown location>";
+ }
#if 0 /* ARG!. workaround for a bug in blenders use of vsnprintf */
- BKE_reportf(reports, RPT_ERROR, "%s\nlocation: %s:%d\n", _PyUnicode_AsString(pystring), filename, lineno);
+ BKE_reportf(reports, RPT_ERROR, "%s\nlocation: %s:%d\n", _PyUnicode_AsString(pystring), filename, lineno);
#else
- pystring_format = PyUnicode_FromFormat(
- TIP_("%s\nlocation: %s:%d\n"),
- _PyUnicode_AsString(pystring), filename, lineno);
+ pystring_format = PyUnicode_FromFormat(
+ TIP_("%s\nlocation: %s:%d\n"), _PyUnicode_AsString(pystring), filename, lineno);
- cstring = _PyUnicode_AsString(pystring_format);
- BKE_report(reports, RPT_ERROR, cstring);
+ cstring = _PyUnicode_AsString(pystring_format);
+ BKE_report(reports, RPT_ERROR, cstring);
- /* not exactly needed. just for testing */
- fprintf(stderr, TIP_("%s\nlocation: %s:%d\n"), cstring, filename, lineno);
+ /* not exactly needed. just for testing */
+ fprintf(stderr, TIP_("%s\nlocation: %s:%d\n"), cstring, filename, lineno);
- Py_DECREF(pystring_format); /* workaround */
+ Py_DECREF(pystring_format); /* workaround */
#endif
- }
- else {
- BKE_report(reports, RPT_ERROR, _PyUnicode_AsString(pystring));
- }
-
+ }
+ else {
+ BKE_report(reports, RPT_ERROR, _PyUnicode_AsString(pystring));
+ }
- Py_DECREF(pystring);
- return 1;
+ Py_DECREF(pystring);
+ return 1;
}
bool BPy_errors_to_report(ReportList *reports)
{
- return BPy_errors_to_report_ex(reports, true, true);
+ return BPy_errors_to_report_ex(reports, true, true);
}
diff --git a/source/blender/python/intern/bpy_capi_utils.h b/source/blender/python/intern/bpy_capi_utils.h
index f8d42b463ac..fe086b61097 100644
--- a/source/blender/python/intern/bpy_capi_utils.h
+++ b/source/blender/python/intern/bpy_capi_utils.h
@@ -30,12 +30,17 @@ struct ReportList;
char *BPy_enum_as_string(const struct EnumPropertyItem *item);
-#define BLANK_PYTHON_TYPE {PyVarObject_HEAD_INIT(NULL, 0) NULL}
+#define BLANK_PYTHON_TYPE \
+ { \
+ PyVarObject_HEAD_INIT(NULL, 0) NULL \
+ }
/* error reporting */
short BPy_reports_to_error(struct ReportList *reports, PyObject *exception, const bool clear);
void BPy_reports_write_stdout(const struct ReportList *reports, const char *header);
-bool BPy_errors_to_report_ex(struct ReportList *reports, const bool use_full, const bool use_location);
+bool BPy_errors_to_report_ex(struct ReportList *reports,
+ const bool use_full,
+ const bool use_location);
bool BPy_errors_to_report(struct ReportList *reports);
/* TODO - find a better solution! */
@@ -45,4 +50,4 @@ void BPy_SetContext(struct bContext *C);
extern void bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate);
extern void bpy_context_clear(struct bContext *C, PyGILState_STATE *gilstate);
-#endif /* __BPY_CAPI_UTILS_H__ */
+#endif /* __BPY_CAPI_UTILS_H__ */
diff --git a/source/blender/python/intern/bpy_driver.c b/source/blender/python/intern/bpy_driver.c
index cb23739ca33..3457e614708 100644
--- a/source/blender/python/intern/bpy_driver.c
+++ b/source/blender/python/intern/bpy_driver.c
@@ -36,7 +36,7 @@
#include "BKE_fcurve.h"
#include "BKE_global.h"
-#include "bpy_rna_driver.h" /* for pyrna_driver_get_variable_value */
+#include "bpy_rna_driver.h" /* for pyrna_driver_get_variable_value */
#include "bpy_intern_string.h"
@@ -66,137 +66,136 @@ static PyObject *bpy_pydriver_Dict__whitelist = NULL;
*/
int bpy_pydriver_create_dict(void)
{
- PyObject *d, *mod;
-
- /* validate namespace for driver evaluation */
- if (bpy_pydriver_Dict) {
- return -1;
- }
-
- d = PyDict_New();
- if (d == NULL) {
- return -1;
- }
- else {
- bpy_pydriver_Dict = d;
- }
-
- /* import some modules: builtins, bpy, math, (Blender.noise)*/
- PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
-
- mod = PyImport_ImportModule("math");
- if (mod) {
- PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
- Py_DECREF(mod);
- }
+ PyObject *d, *mod;
+
+ /* validate namespace for driver evaluation */
+ if (bpy_pydriver_Dict) {
+ return -1;
+ }
+
+ d = PyDict_New();
+ if (d == NULL) {
+ return -1;
+ }
+ else {
+ bpy_pydriver_Dict = d;
+ }
+
+ /* import some modules: builtins, bpy, math, (Blender.noise)*/
+ PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
+
+ mod = PyImport_ImportModule("math");
+ if (mod) {
+ PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
+ Py_DECREF(mod);
+ }
#ifdef USE_BYTECODE_WHITELIST
- PyObject *mod_math = mod;
+ PyObject *mod_math = mod;
#endif
- /* add bpy to global namespace */
- mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
- if (mod) {
- PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
- Py_DECREF(mod);
- }
-
- /* add noise to global namespace */
- mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
- if (mod) {
- PyObject *modsub = PyDict_GetItemString(PyModule_GetDict(mod), "noise");
- PyDict_SetItemString(bpy_pydriver_Dict, "noise", modsub);
- Py_DECREF(mod);
- }
+ /* add bpy to global namespace */
+ mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
+ if (mod) {
+ PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
+ Py_DECREF(mod);
+ }
+
+ /* add noise to global namespace */
+ mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
+ if (mod) {
+ PyObject *modsub = PyDict_GetItemString(PyModule_GetDict(mod), "noise");
+ PyDict_SetItemString(bpy_pydriver_Dict, "noise", modsub);
+ Py_DECREF(mod);
+ }
#ifdef USE_BYTECODE_WHITELIST
- /* setup the whitelist */
- {
- bpy_pydriver_Dict__whitelist = PyDict_New();
- const char *whitelist[] = {
- /* builtins (basic) */
- "all",
- "any",
- "len",
- /* builtins (numeric) */
- "max",
- "min",
- "pow",
- "round",
- "sum",
- /* types */
- "bool",
- "float",
- "int",
-
- NULL,
- };
-
- for (int i = 0; whitelist[i]; i++) {
- PyDict_SetItemString(bpy_pydriver_Dict__whitelist, whitelist[i], Py_None);
- }
-
- /* Add all of 'math' functions. */
- if (mod_math != NULL) {
- PyObject *mod_math_dict = PyModule_GetDict(mod_math);
- PyObject *arg_key, *arg_value;
- Py_ssize_t arg_pos = 0;
- while (PyDict_Next(mod_math_dict, &arg_pos, &arg_key, &arg_value)) {
- const char *arg_str = _PyUnicode_AsString(arg_key);
- if (arg_str[0] && arg_str[1] != '_') {
- PyDict_SetItem(bpy_pydriver_Dict__whitelist, arg_key, Py_None);
- }
- }
- }
- }
-#endif /* USE_BYTECODE_WHITELIST */
-
- return 0;
+ /* setup the whitelist */
+ {
+ bpy_pydriver_Dict__whitelist = PyDict_New();
+ const char *whitelist[] = {
+ /* builtins (basic) */
+ "all",
+ "any",
+ "len",
+ /* builtins (numeric) */
+ "max",
+ "min",
+ "pow",
+ "round",
+ "sum",
+ /* types */
+ "bool",
+ "float",
+ "int",
+
+ NULL,
+ };
+
+ for (int i = 0; whitelist[i]; i++) {
+ PyDict_SetItemString(bpy_pydriver_Dict__whitelist, whitelist[i], Py_None);
+ }
+
+ /* Add all of 'math' functions. */
+ if (mod_math != NULL) {
+ PyObject *mod_math_dict = PyModule_GetDict(mod_math);
+ PyObject *arg_key, *arg_value;
+ Py_ssize_t arg_pos = 0;
+ while (PyDict_Next(mod_math_dict, &arg_pos, &arg_key, &arg_value)) {
+ const char *arg_str = _PyUnicode_AsString(arg_key);
+ if (arg_str[0] && arg_str[1] != '_') {
+ PyDict_SetItem(bpy_pydriver_Dict__whitelist, arg_key, Py_None);
+ }
+ }
+ }
+ }
+#endif /* USE_BYTECODE_WHITELIST */
+
+ return 0;
}
/* note, this function should do nothing most runs, only when changing frame */
/* not thread safe but neither is python */
static struct {
- float evaltime;
+ float evaltime;
- /* borrowed reference to the 'self' in 'bpy_pydriver_Dict'
- * keep for as long as the same self is used. */
- PyObject *self;
+ /* borrowed reference to the 'self' in 'bpy_pydriver_Dict'
+ * keep for as long as the same self is used. */
+ PyObject *self;
} g_pydriver_state_prev = {
- .evaltime = FLT_MAX,
- .self = NULL,
+ .evaltime = FLT_MAX,
+ .self = NULL,
};
static void bpy_pydriver_namespace_update_frame(const float evaltime)
{
- if (g_pydriver_state_prev.evaltime != evaltime) {
- PyObject *item = PyFloat_FromDouble(evaltime);
- PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_frame, item);
- Py_DECREF(item);
+ if (g_pydriver_state_prev.evaltime != evaltime) {
+ PyObject *item = PyFloat_FromDouble(evaltime);
+ PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_frame, item);
+ Py_DECREF(item);
- g_pydriver_state_prev.evaltime = evaltime;
- }
+ g_pydriver_state_prev.evaltime = evaltime;
+ }
}
static void bpy_pydriver_namespace_update_self(struct PathResolvedRNA *anim_rna)
{
- if ((g_pydriver_state_prev.self == NULL) ||
- (pyrna_driver_is_equal_anim_rna(anim_rna, g_pydriver_state_prev.self) == false))
- {
- PyObject *item = pyrna_driver_self_from_anim_rna(anim_rna);
- PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_self, item);
- Py_DECREF(item);
-
- g_pydriver_state_prev.self = item;
- }
+ if ((g_pydriver_state_prev.self == NULL) ||
+ (pyrna_driver_is_equal_anim_rna(anim_rna, g_pydriver_state_prev.self) == false)) {
+ PyObject *item = pyrna_driver_self_from_anim_rna(anim_rna);
+ PyDict_SetItem(bpy_pydriver_Dict, bpy_intern_str_self, item);
+ Py_DECREF(item);
+
+ g_pydriver_state_prev.self = item;
+ }
}
static void bpy_pydriver_namespace_clear_self(void)
{
- if (g_pydriver_state_prev.self) {
- PyDict_DelItem(bpy_pydriver_Dict, bpy_intern_str_self);
+ if (g_pydriver_state_prev.self) {
+ PyDict_DelItem(bpy_pydriver_Dict, bpy_intern_str_self);
- g_pydriver_state_prev.self = NULL;
- }
+ g_pydriver_state_prev.self = NULL;
+ }
}
/* Update function, it gets rid of pydrivers global dictionary, forcing
@@ -206,171 +205,176 @@ static void bpy_pydriver_namespace_clear_self(void)
*/
void BPY_driver_reset(void)
{
- PyGILState_STATE gilstate;
- bool use_gil = true; /* !PyC_IsInterpreterActive(); */
+ PyGILState_STATE gilstate;
+ bool use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
- PyDict_Clear(bpy_pydriver_Dict);
- Py_DECREF(bpy_pydriver_Dict);
- bpy_pydriver_Dict = NULL;
- }
+ if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
+ PyDict_Clear(bpy_pydriver_Dict);
+ Py_DECREF(bpy_pydriver_Dict);
+ bpy_pydriver_Dict = NULL;
+ }
#ifdef USE_BYTECODE_WHITELIST
- if (bpy_pydriver_Dict__whitelist) {
- PyDict_Clear(bpy_pydriver_Dict__whitelist);
- Py_DECREF(bpy_pydriver_Dict__whitelist);
- bpy_pydriver_Dict__whitelist = NULL;
- }
+ if (bpy_pydriver_Dict__whitelist) {
+ PyDict_Clear(bpy_pydriver_Dict__whitelist);
+ Py_DECREF(bpy_pydriver_Dict__whitelist);
+ bpy_pydriver_Dict__whitelist = NULL;
+ }
#endif
- g_pydriver_state_prev.evaltime = FLT_MAX;
+ g_pydriver_state_prev.evaltime = FLT_MAX;
- /* freed when clearing driver dict */
- g_pydriver_state_prev.self = NULL;
+ /* freed when clearing driver dict */
+ g_pydriver_state_prev.self = NULL;
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- return;
+ return;
}
/* error return function for BPY_eval_pydriver */
static void pydriver_error(ChannelDriver *driver)
{
- driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
- fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
-
- // BPy_errors_to_report(NULL); // TODO - reports
- PyErr_Print();
- PyErr_Clear();
+ driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
+ fprintf(stderr,
+ "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n",
+ driver->expression);
+
+ // BPy_errors_to_report(NULL); // TODO - reports
+ PyErr_Print();
+ PyErr_Clear();
}
#ifdef USE_BYTECODE_WHITELIST
-#define OK_OP(op) [op] = 1
+# define OK_OP(op) [op] = 1
static const char secure_opcodes[255] = {
- OK_OP(POP_TOP),
- OK_OP(ROT_TWO),
- OK_OP(ROT_THREE),
- OK_OP(DUP_TOP),
- OK_OP(DUP_TOP_TWO),
- OK_OP(NOP),
- OK_OP(UNARY_POSITIVE),
- OK_OP(UNARY_NEGATIVE),
- OK_OP(UNARY_NOT),
- OK_OP(UNARY_INVERT),
- OK_OP(BINARY_MATRIX_MULTIPLY),
- OK_OP(INPLACE_MATRIX_MULTIPLY),
- OK_OP(BINARY_POWER),
- OK_OP(BINARY_MULTIPLY),
- OK_OP(BINARY_MODULO),
- OK_OP(BINARY_ADD),
- OK_OP(BINARY_SUBTRACT),
- OK_OP(BINARY_SUBSCR),
- OK_OP(BINARY_FLOOR_DIVIDE),
- OK_OP(BINARY_TRUE_DIVIDE),
- OK_OP(INPLACE_FLOOR_DIVIDE),
- OK_OP(INPLACE_TRUE_DIVIDE),
- OK_OP(INPLACE_ADD),
- OK_OP(INPLACE_SUBTRACT),
- OK_OP(INPLACE_MULTIPLY),
- OK_OP(INPLACE_MODULO),
- OK_OP(BINARY_LSHIFT),
- OK_OP(BINARY_RSHIFT),
- OK_OP(BINARY_AND),
- OK_OP(BINARY_XOR),
- OK_OP(BINARY_OR),
- OK_OP(INPLACE_POWER),
- OK_OP(INPLACE_LSHIFT),
- OK_OP(INPLACE_RSHIFT),
- OK_OP(INPLACE_AND),
- OK_OP(INPLACE_XOR),
- OK_OP(INPLACE_OR),
- OK_OP(RETURN_VALUE),
- OK_OP(BUILD_TUPLE),
- OK_OP(BUILD_LIST),
- OK_OP(BUILD_SET),
- OK_OP(BUILD_MAP),
- OK_OP(COMPARE_OP),
- OK_OP(JUMP_FORWARD),
- OK_OP(JUMP_IF_FALSE_OR_POP),
- OK_OP(JUMP_IF_TRUE_OR_POP),
- OK_OP(JUMP_ABSOLUTE),
- OK_OP(POP_JUMP_IF_FALSE),
- OK_OP(POP_JUMP_IF_TRUE),
- OK_OP(LOAD_GLOBAL),
- OK_OP(LOAD_FAST),
- OK_OP(STORE_FAST),
- OK_OP(DELETE_FAST),
- OK_OP(LOAD_DEREF),
- OK_OP(STORE_DEREF),
-
- /* special cases */
- OK_OP(LOAD_CONST), /* ok because constants are accepted */
- OK_OP(LOAD_NAME), /* ok, because PyCodeObject.names is checked */
- OK_OP(CALL_FUNCTION), /* ok, because we check its 'name' before calling */
- OK_OP(CALL_FUNCTION_KW),
- OK_OP(CALL_FUNCTION_EX),
+ OK_OP(POP_TOP),
+ OK_OP(ROT_TWO),
+ OK_OP(ROT_THREE),
+ OK_OP(DUP_TOP),
+ OK_OP(DUP_TOP_TWO),
+ OK_OP(NOP),
+ OK_OP(UNARY_POSITIVE),
+ OK_OP(UNARY_NEGATIVE),
+ OK_OP(UNARY_NOT),
+ OK_OP(UNARY_INVERT),
+ OK_OP(BINARY_MATRIX_MULTIPLY),
+ OK_OP(INPLACE_MATRIX_MULTIPLY),
+ OK_OP(BINARY_POWER),
+ OK_OP(BINARY_MULTIPLY),
+ OK_OP(BINARY_MODULO),
+ OK_OP(BINARY_ADD),
+ OK_OP(BINARY_SUBTRACT),
+ OK_OP(BINARY_SUBSCR),
+ OK_OP(BINARY_FLOOR_DIVIDE),
+ OK_OP(BINARY_TRUE_DIVIDE),
+ OK_OP(INPLACE_FLOOR_DIVIDE),
+ OK_OP(INPLACE_TRUE_DIVIDE),
+ OK_OP(INPLACE_ADD),
+ OK_OP(INPLACE_SUBTRACT),
+ OK_OP(INPLACE_MULTIPLY),
+ OK_OP(INPLACE_MODULO),
+ OK_OP(BINARY_LSHIFT),
+ OK_OP(BINARY_RSHIFT),
+ OK_OP(BINARY_AND),
+ OK_OP(BINARY_XOR),
+ OK_OP(BINARY_OR),
+ OK_OP(INPLACE_POWER),
+ OK_OP(INPLACE_LSHIFT),
+ OK_OP(INPLACE_RSHIFT),
+ OK_OP(INPLACE_AND),
+ OK_OP(INPLACE_XOR),
+ OK_OP(INPLACE_OR),
+ OK_OP(RETURN_VALUE),
+ OK_OP(BUILD_TUPLE),
+ OK_OP(BUILD_LIST),
+ OK_OP(BUILD_SET),
+ OK_OP(BUILD_MAP),
+ OK_OP(COMPARE_OP),
+ OK_OP(JUMP_FORWARD),
+ OK_OP(JUMP_IF_FALSE_OR_POP),
+ OK_OP(JUMP_IF_TRUE_OR_POP),
+ OK_OP(JUMP_ABSOLUTE),
+ OK_OP(POP_JUMP_IF_FALSE),
+ OK_OP(POP_JUMP_IF_TRUE),
+ OK_OP(LOAD_GLOBAL),
+ OK_OP(LOAD_FAST),
+ OK_OP(STORE_FAST),
+ OK_OP(DELETE_FAST),
+ OK_OP(LOAD_DEREF),
+ OK_OP(STORE_DEREF),
+
+ /* special cases */
+ OK_OP(LOAD_CONST), /* ok because constants are accepted */
+ OK_OP(LOAD_NAME), /* ok, because PyCodeObject.names is checked */
+ OK_OP(CALL_FUNCTION), /* ok, because we check its 'name' before calling */
+ OK_OP(CALL_FUNCTION_KW),
+ OK_OP(CALL_FUNCTION_EX),
};
-#undef OK_OP
+# undef OK_OP
static bool bpy_driver_secure_bytecode_validate(PyObject *expr_code, PyObject *dict_arr[])
{
- PyCodeObject *py_code = (PyCodeObject *)expr_code;
-
- /* Check names. */
- {
- for (int i = 0; i < PyTuple_GET_SIZE(py_code->co_names); i++) {
- PyObject *name = PyTuple_GET_ITEM(py_code->co_names, i);
-
- bool contains_name = false;
- for (int j = 0; dict_arr[j]; j++) {
- if (PyDict_Contains(dict_arr[j], name)) {
- contains_name = true;
- break;
- }
- }
-
- if (contains_name == false) {
- fprintf(stderr, "\tBPY_driver_eval() - restricted access disallows name '%s', "
- "enable auto-execution to support\n", _PyUnicode_AsString(name));
- return false;
- }
- }
- }
-
- /* Check opcodes. */
- {
- const _Py_CODEUNIT *codestr;
- Py_ssize_t code_len;
-
- PyBytes_AsStringAndSize(py_code->co_code, (char **)&codestr, &code_len);
- code_len /= sizeof(*codestr);
-
- for (Py_ssize_t i = 0; i < code_len; i++) {
- const int opcode = _Py_OPCODE(codestr[i]);
- if (secure_opcodes[opcode] == 0) {
- fprintf(stderr, "\tBPY_driver_eval() - restricted access disallows opcode '%d', "
- "enable auto-execution to support\n", opcode);
- return false;
- }
- }
-
-#undef CODESIZE
- }
-
- return true;
+ PyCodeObject *py_code = (PyCodeObject *)expr_code;
+
+ /* Check names. */
+ {
+ for (int i = 0; i < PyTuple_GET_SIZE(py_code->co_names); i++) {
+ PyObject *name = PyTuple_GET_ITEM(py_code->co_names, i);
+
+ bool contains_name = false;
+ for (int j = 0; dict_arr[j]; j++) {
+ if (PyDict_Contains(dict_arr[j], name)) {
+ contains_name = true;
+ break;
+ }
+ }
+
+ if (contains_name == false) {
+ fprintf(stderr,
+ "\tBPY_driver_eval() - restricted access disallows name '%s', "
+ "enable auto-execution to support\n",
+ _PyUnicode_AsString(name));
+ return false;
+ }
+ }
+ }
+
+ /* Check opcodes. */
+ {
+ const _Py_CODEUNIT *codestr;
+ Py_ssize_t code_len;
+
+ PyBytes_AsStringAndSize(py_code->co_code, (char **)&codestr, &code_len);
+ code_len /= sizeof(*codestr);
+
+ for (Py_ssize_t i = 0; i < code_len; i++) {
+ const int opcode = _Py_OPCODE(codestr[i]);
+ if (secure_opcodes[opcode] == 0) {
+ fprintf(stderr,
+ "\tBPY_driver_eval() - restricted access disallows opcode '%d', "
+ "enable auto-execution to support\n",
+ opcode);
+ return false;
+ }
+ }
+
+# undef CODESIZE
+ }
+
+ return true;
}
-#endif /* USE_BYTECODE_WHITELIST */
-
+#endif /* USE_BYTECODE_WHITELIST */
/* This evals py driver expressions, 'expr' is a Python expression that
* should evaluate to a float number, which is returned.
@@ -388,231 +392,239 @@ static bool bpy_driver_secure_bytecode_validate(PyObject *expr_code, PyObject *d
* original driver, otherwise these would get freed while editing. Due to
* the GIL this is thread-safe.
*/
-float BPY_driver_exec(struct PathResolvedRNA *anim_rna, ChannelDriver *driver, ChannelDriver *driver_orig, const float evaltime)
+float BPY_driver_exec(struct PathResolvedRNA *anim_rna,
+ ChannelDriver *driver,
+ ChannelDriver *driver_orig,
+ const float evaltime)
{
- PyObject *driver_vars = NULL;
- PyObject *retval = NULL;
- PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
- PyObject *expr_code;
- PyGILState_STATE gilstate;
- bool use_gil;
-
- DriverVar *dvar;
- double result = 0.0; /* default return */
- const char *expr;
- short targets_ok = 1;
- int i;
-
- /* get the py expression to be evaluated */
- expr = driver_orig->expression;
- if (expr[0] == '\0') {
- return 0.0f;
- }
+ PyObject *driver_vars = NULL;
+ PyObject *retval = NULL;
+ PyObject *
+ expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
+ PyObject *expr_code;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+
+ DriverVar *dvar;
+ double result = 0.0; /* default return */
+ const char *expr;
+ short targets_ok = 1;
+ int i;
+
+ /* get the py expression to be evaluated */
+ expr = driver_orig->expression;
+ if (expr[0] == '\0') {
+ return 0.0f;
+ }
#ifndef USE_BYTECODE_WHITELIST
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
- G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
- BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
-
- printf("skipping driver '%s', automatic scripts are disabled\n", expr);
- }
- return 0.0f;
- }
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
+ G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
+ BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
+
+ printf("skipping driver '%s', automatic scripts are disabled\n", expr);
+ }
+ return 0.0f;
+ }
#else
- bool is_recompile = false;
+ bool is_recompile = false;
#endif
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- /* needed since drivers are updated directly after undo where 'main' is
- * re-allocated [#28807] */
- BPY_update_rna_module();
-
- /* init global dictionary for py-driver evaluation settings */
- if (!bpy_pydriver_Dict) {
- if (bpy_pydriver_create_dict() != 0) {
- fprintf(stderr, "PyDriver error: couldn't create Python dictionary\n");
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
- return 0.0f;
- }
- }
-
- /* update global namespace */
- bpy_pydriver_namespace_update_frame(evaltime);
-
- if (driver_orig->flag & DRIVER_FLAG_USE_SELF) {
- bpy_pydriver_namespace_update_self(anim_rna);
- }
- else {
- bpy_pydriver_namespace_clear_self();
- }
-
- if (driver_orig->expr_comp == NULL) {
- driver_orig->flag |= DRIVER_FLAG_RECOMPILE;
- }
-
- /* compile the expression first if it hasn't been compiled or needs to be rebuilt */
- if (driver_orig->flag & DRIVER_FLAG_RECOMPILE) {
- Py_XDECREF(driver_orig->expr_comp);
- driver_orig->expr_comp = PyTuple_New(2);
-
- expr_code = Py_CompileString(expr, "<bpy driver>", Py_eval_input);
- PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, expr_code);
-
- driver_orig->flag &= ~DRIVER_FLAG_RECOMPILE;
- driver_orig->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ /* needed since drivers are updated directly after undo where 'main' is
+ * re-allocated [#28807] */
+ BPY_update_rna_module();
+
+ /* init global dictionary for py-driver evaluation settings */
+ if (!bpy_pydriver_Dict) {
+ if (bpy_pydriver_create_dict() != 0) {
+ fprintf(stderr, "PyDriver error: couldn't create Python dictionary\n");
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+ return 0.0f;
+ }
+ }
+
+ /* update global namespace */
+ bpy_pydriver_namespace_update_frame(evaltime);
+
+ if (driver_orig->flag & DRIVER_FLAG_USE_SELF) {
+ bpy_pydriver_namespace_update_self(anim_rna);
+ }
+ else {
+ bpy_pydriver_namespace_clear_self();
+ }
+
+ if (driver_orig->expr_comp == NULL) {
+ driver_orig->flag |= DRIVER_FLAG_RECOMPILE;
+ }
+
+ /* compile the expression first if it hasn't been compiled or needs to be rebuilt */
+ if (driver_orig->flag & DRIVER_FLAG_RECOMPILE) {
+ Py_XDECREF(driver_orig->expr_comp);
+ driver_orig->expr_comp = PyTuple_New(2);
+
+ expr_code = Py_CompileString(expr, "<bpy driver>", Py_eval_input);
+ PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, expr_code);
+
+ driver_orig->flag &= ~DRIVER_FLAG_RECOMPILE;
+ driver_orig->flag |=
+ DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
#ifdef USE_BYTECODE_WHITELIST
- is_recompile = true;
+ is_recompile = true;
#endif
- }
- else {
- expr_code = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 0);
- }
-
- if (driver_orig->flag & DRIVER_FLAG_RENAMEVAR) {
- /* may not be set */
- expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
- Py_XDECREF(expr_vars);
-
- expr_vars = PyTuple_New(BLI_listbase_count(&driver_orig->variables));
- PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 1, expr_vars);
-
- for (dvar = driver_orig->variables.first, i = 0; dvar; dvar = dvar->next) {
- PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name));
- }
-
- driver_orig->flag &= ~DRIVER_FLAG_RENAMEVAR;
- }
- else {
- expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
- }
-
- /* add target values to a dict that will be used as '__locals__' dict */
- driver_vars = _PyDict_NewPresized(PyTuple_GET_SIZE(expr_vars));
- for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) {
- PyObject *driver_arg = NULL;
-
- /* support for any RNA data */
+ }
+ else {
+ expr_code = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 0);
+ }
+
+ if (driver_orig->flag & DRIVER_FLAG_RENAMEVAR) {
+ /* may not be set */
+ expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
+ Py_XDECREF(expr_vars);
+
+ expr_vars = PyTuple_New(BLI_listbase_count(&driver_orig->variables));
+ PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 1, expr_vars);
+
+ for (dvar = driver_orig->variables.first, i = 0; dvar; dvar = dvar->next) {
+ PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name));
+ }
+
+ driver_orig->flag &= ~DRIVER_FLAG_RENAMEVAR;
+ }
+ else {
+ expr_vars = PyTuple_GET_ITEM(((PyObject *)driver_orig->expr_comp), 1);
+ }
+
+ /* add target values to a dict that will be used as '__locals__' dict */
+ driver_vars = _PyDict_NewPresized(PyTuple_GET_SIZE(expr_vars));
+ for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) {
+ PyObject *driver_arg = NULL;
+
+ /* support for any RNA data */
#ifdef USE_RNA_AS_PYOBJECT
- if (dvar->type == DVAR_TYPE_SINGLE_PROP) {
- driver_arg = pyrna_driver_get_variable_value(driver, &dvar->targets[0]);
-
- if (driver_arg == NULL) {
- driver_arg = PyFloat_FromDouble(0.0);
- dvar->curval = 0.0f;
- }
- else {
- /* no need to worry about overflow here, values from RNA are within limits. */
- if (PyFloat_CheckExact(driver_arg)) {
- dvar->curval = (float)PyFloat_AsDouble(driver_arg);
- }
- else if (PyLong_CheckExact(driver_arg)) {
- dvar->curval = (float)PyLong_AsLong(driver_arg);
- }
- else if (PyBool_Check(driver_arg)) {
- dvar->curval = (driver_arg == Py_True);
- }
- else {
- dvar->curval = 0.0f;
- }
- }
- }
- else
+ if (dvar->type == DVAR_TYPE_SINGLE_PROP) {
+ driver_arg = pyrna_driver_get_variable_value(driver, &dvar->targets[0]);
+
+ if (driver_arg == NULL) {
+ driver_arg = PyFloat_FromDouble(0.0);
+ dvar->curval = 0.0f;
+ }
+ else {
+ /* no need to worry about overflow here, values from RNA are within limits. */
+ if (PyFloat_CheckExact(driver_arg)) {
+ dvar->curval = (float)PyFloat_AsDouble(driver_arg);
+ }
+ else if (PyLong_CheckExact(driver_arg)) {
+ dvar->curval = (float)PyLong_AsLong(driver_arg);
+ }
+ else if (PyBool_Check(driver_arg)) {
+ dvar->curval = (driver_arg == Py_True);
+ }
+ else {
+ dvar->curval = 0.0f;
+ }
+ }
+ }
+ else
#endif
- {
- /* try to get variable value */
- float tval = driver_get_variable_value(driver, dvar);
- driver_arg = PyFloat_FromDouble((double)tval);
- }
-
- /* try to add to dictionary */
- /* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
- if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) != -1) {
- Py_DECREF(driver_arg);
- }
- else {
- /* this target failed - bad name */
- if (targets_ok) {
- /* first one - print some extra info for easier identification */
- fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
- targets_ok = 0;
- }
-
- fprintf(stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
- // BPy_errors_to_report(NULL); // TODO - reports
- PyErr_Print();
- PyErr_Clear();
- }
- }
+ {
+ /* try to get variable value */
+ float tval = driver_get_variable_value(driver, dvar);
+ driver_arg = PyFloat_FromDouble((double)tval);
+ }
+
+ /* try to add to dictionary */
+ /* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
+ if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) != -1) {
+ Py_DECREF(driver_arg);
+ }
+ else {
+ /* this target failed - bad name */
+ if (targets_ok) {
+ /* first one - print some extra info for easier identification */
+ fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
+ targets_ok = 0;
+ }
+
+ fprintf(
+ stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
+ // BPy_errors_to_report(NULL); // TODO - reports
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
#ifdef USE_BYTECODE_WHITELIST
- if (is_recompile && expr_code) {
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
- if (!bpy_driver_secure_bytecode_validate(
- expr_code, (PyObject *[]){
- bpy_pydriver_Dict,
- bpy_pydriver_Dict__whitelist,
- driver_vars,
- NULL,}
- ))
- {
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
- G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
- BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
- }
-
- Py_DECREF(expr_code);
- expr_code = NULL;
- PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, NULL);
- }
- }
- }
-#endif /* USE_BYTECODE_WHITELIST */
-
-#if 0 /* slow, with this can avoid all Py_CompileString above. */
- /* execute expression to get a value */
- retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
+ if (is_recompile && expr_code) {
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
+ if (!bpy_driver_secure_bytecode_validate(expr_code,
+ (PyObject *[]){
+ bpy_pydriver_Dict,
+ bpy_pydriver_Dict__whitelist,
+ driver_vars,
+ NULL,
+ })) {
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
+ G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
+ BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
+ }
+
+ Py_DECREF(expr_code);
+ expr_code = NULL;
+ PyTuple_SET_ITEM(((PyObject *)driver_orig->expr_comp), 0, NULL);
+ }
+ }
+ }
+#endif /* USE_BYTECODE_WHITELIST */
+
+#if 0 /* slow, with this can avoid all Py_CompileString above. */
+ /* execute expression to get a value */
+ retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
#else
- /* evaluate the compiled expression */
- if (expr_code) {
- retval = PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
- }
+ /* evaluate the compiled expression */
+ if (expr_code) {
+ retval = PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
+ }
#endif
- /* decref the driver vars first... */
- Py_DECREF(driver_vars);
-
- /* process the result */
- if (retval == NULL) {
- pydriver_error(driver);
- }
- else if ((result = PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
- pydriver_error(driver);
- Py_DECREF(retval);
- result = 0.0;
- }
- else {
- /* all fine, make sure the "invalid expression" flag is cleared */
- driver->flag &= ~DRIVER_FLAG_INVALID;
- Py_DECREF(retval);
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (isfinite(result)) {
- return (float)result;
- }
- else {
- fprintf(stderr, "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n", driver->expression, result);
- return 0.0f;
- }
+ /* decref the driver vars first... */
+ Py_DECREF(driver_vars);
+
+ /* process the result */
+ if (retval == NULL) {
+ pydriver_error(driver);
+ }
+ else if ((result = PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
+ pydriver_error(driver);
+ Py_DECREF(retval);
+ result = 0.0;
+ }
+ else {
+ /* all fine, make sure the "invalid expression" flag is cleared */
+ driver->flag &= ~DRIVER_FLAG_INVALID;
+ Py_DECREF(retval);
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (isfinite(result)) {
+ return (float)result;
+ }
+ else {
+ fprintf(stderr,
+ "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n",
+ driver->expression,
+ result);
+ return 0.0f;
+ }
}
diff --git a/source/blender/python/intern/bpy_driver.h b/source/blender/python/intern/bpy_driver.h
index 4026a9f2abf..c77815c7e0e 100644
--- a/source/blender/python/intern/bpy_driver.h
+++ b/source/blender/python/intern/bpy_driver.h
@@ -24,4 +24,4 @@
int bpy_pydriver_create_dict(void);
extern PyObject *bpy_pydriver_Dict;
-#endif /* __BPY_DRIVER_H__ */
+#endif /* __BPY_DRIVER_H__ */
diff --git a/source/blender/python/intern/bpy_gizmo_wrap.c b/source/blender/python/intern/bpy_gizmo_wrap.c
index f1281344bcf..41ff630753f 100644
--- a/source/blender/python/intern/bpy_gizmo_wrap.c
+++ b/source/blender/python/intern/bpy_gizmo_wrap.c
@@ -39,7 +39,7 @@
#include "bpy_rna.h"
#include "bpy_intern_string.h"
-#include "bpy_gizmo_wrap.h" /* own include */
+#include "bpy_gizmo_wrap.h" /* own include */
/* we may want to add, but not now */
@@ -47,176 +47,168 @@
/** \name Gizmo
* \{ */
-
-static bool bpy_gizmotype_target_property_def(
- wmGizmoType *gzt, PyObject *item)
+static bool bpy_gizmotype_target_property_def(wmGizmoType *gzt, PyObject *item)
{
- /* Note: names based on 'rna_rna.c' */
- PyObject *empty_tuple = PyTuple_New(0);
-
- struct {
- char *id;
- char *type_id; int type;
- int array_length;
- } params = {
- .id = NULL, /* not optional */
- .type = PROP_FLOAT,
- .type_id = NULL,
- .array_length = 1,
- };
-
- static const char * const _keywords[] = {"id", "type", "array_length", NULL};
- static _PyArg_Parser _parser = {"|$ssi:register_class", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- empty_tuple, item,
- &_parser,
- &params.id,
- &params.type_id,
- &params.array_length))
- {
- goto fail;
- }
-
- if (params.id == NULL) {
- PyErr_SetString(PyExc_ValueError, "'id' argument not given");
- goto fail;
- }
-
- if ((params.type_id != NULL) &&
- pyrna_enum_value_from_id(
- rna_enum_property_type_items, params.type_id, &params.type, "'type' enum value") == -1)
- {
- goto fail;
- }
- else {
- params.type = rna_enum_property_type_items[params.type].value;
- }
-
- if ((params.array_length < 1 || params.array_length > RNA_MAX_ARRAY_LENGTH)) {
- PyErr_SetString(PyExc_ValueError, "'array_length' out of range");
- goto fail;
- }
-
- WM_gizmotype_target_property_def(gzt, params.id, params.type, params.array_length);
- Py_DECREF(empty_tuple);
- return true;
+ /* Note: names based on 'rna_rna.c' */
+ PyObject *empty_tuple = PyTuple_New(0);
+
+ struct {
+ char *id;
+ char *type_id;
+ int type;
+ int array_length;
+ } params = {
+ .id = NULL, /* not optional */
+ .type = PROP_FLOAT,
+ .type_id = NULL,
+ .array_length = 1,
+ };
+
+ static const char *const _keywords[] = {"id", "type", "array_length", NULL};
+ static _PyArg_Parser _parser = {"|$ssi:register_class", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ empty_tuple, item, &_parser, &params.id, &params.type_id, &params.array_length)) {
+ goto fail;
+ }
+
+ if (params.id == NULL) {
+ PyErr_SetString(PyExc_ValueError, "'id' argument not given");
+ goto fail;
+ }
+
+ if ((params.type_id != NULL) &&
+ pyrna_enum_value_from_id(
+ rna_enum_property_type_items, params.type_id, &params.type, "'type' enum value") == -1) {
+ goto fail;
+ }
+ else {
+ params.type = rna_enum_property_type_items[params.type].value;
+ }
+
+ if ((params.array_length < 1 || params.array_length > RNA_MAX_ARRAY_LENGTH)) {
+ PyErr_SetString(PyExc_ValueError, "'array_length' out of range");
+ goto fail;
+ }
+
+ WM_gizmotype_target_property_def(gzt, params.id, params.type, params.array_length);
+ Py_DECREF(empty_tuple);
+ return true;
fail:
- Py_DECREF(empty_tuple);
- return false;
+ Py_DECREF(empty_tuple);
+ return false;
}
static void gizmo_properties_init(wmGizmoType *gzt)
{
- PyTypeObject *py_class = gzt->ext.data;
- RNA_struct_blender_type_set(gzt->ext.srna, gzt);
-
- /* only call this so pyrna_deferred_register_class gives a useful error
- * WM_operatortype_append_ptr will call RNA_def_struct_identifier
- * later */
- RNA_def_struct_identifier_no_struct_map(gzt->srna, gzt->idname);
-
- if (pyrna_deferred_register_class(gzt->srna, py_class) != 0) {
- PyErr_Print(); /* failed to register operator props */
- PyErr_Clear();
- }
-
- /* Extract target property definitions from 'bl_target_properties' */
- {
- /* picky developers will notice that 'bl_targets' won't work with inheritance
- * get direct from the dict to avoid raising a load of attribute errors (yes this isnt ideal) - campbell */
- PyObject *py_class_dict = py_class->tp_dict;
- PyObject *bl_target_properties = PyDict_GetItem(py_class_dict, bpy_intern_str_bl_target_properties);
-
- /* Some widgets may only exist to activate operators. */
- if (bl_target_properties != NULL) {
- PyObject *bl_target_properties_fast;
- if (!(bl_target_properties_fast = PySequence_Fast(
- bl_target_properties, "bl_target_properties sequence")))
- {
- /* PySequence_Fast sets the error */
- PyErr_Print();
- PyErr_Clear();
- return;
- }
-
- const uint items_len = PySequence_Fast_GET_SIZE(bl_target_properties_fast);
- PyObject **items = PySequence_Fast_ITEMS(bl_target_properties_fast);
-
- for (uint i = 0; i < items_len; i++) {
- if (!bpy_gizmotype_target_property_def(gzt, items[i])) {
- PyErr_Print();
- PyErr_Clear();
- break;
- }
- }
-
- Py_DECREF(bl_target_properties_fast);
- }
- }
+ PyTypeObject *py_class = gzt->ext.data;
+ RNA_struct_blender_type_set(gzt->ext.srna, gzt);
+
+ /* only call this so pyrna_deferred_register_class gives a useful error
+ * WM_operatortype_append_ptr will call RNA_def_struct_identifier
+ * later */
+ RNA_def_struct_identifier_no_struct_map(gzt->srna, gzt->idname);
+
+ if (pyrna_deferred_register_class(gzt->srna, py_class) != 0) {
+ PyErr_Print(); /* failed to register operator props */
+ PyErr_Clear();
+ }
+
+ /* Extract target property definitions from 'bl_target_properties' */
+ {
+ /* picky developers will notice that 'bl_targets' won't work with inheritance
+ * get direct from the dict to avoid raising a load of attribute errors (yes this isnt ideal) - campbell */
+ PyObject *py_class_dict = py_class->tp_dict;
+ PyObject *bl_target_properties = PyDict_GetItem(py_class_dict,
+ bpy_intern_str_bl_target_properties);
+
+ /* Some widgets may only exist to activate operators. */
+ if (bl_target_properties != NULL) {
+ PyObject *bl_target_properties_fast;
+ if (!(bl_target_properties_fast = PySequence_Fast(bl_target_properties,
+ "bl_target_properties sequence"))) {
+ /* PySequence_Fast sets the error */
+ PyErr_Print();
+ PyErr_Clear();
+ return;
+ }
+
+ const uint items_len = PySequence_Fast_GET_SIZE(bl_target_properties_fast);
+ PyObject **items = PySequence_Fast_ITEMS(bl_target_properties_fast);
+
+ for (uint i = 0; i < items_len; i++) {
+ if (!bpy_gizmotype_target_property_def(gzt, items[i])) {
+ PyErr_Print();
+ PyErr_Clear();
+ break;
+ }
+ }
+
+ Py_DECREF(bl_target_properties_fast);
+ }
+ }
}
void BPY_RNA_gizmo_wrapper(wmGizmoType *gzt, void *userdata)
{
- /* take care not to overwrite anything set in
- * WM_gizmomaptype_group_link_ptr before opfunc() is called */
- StructRNA *srna = gzt->srna;
- *gzt = *((wmGizmoType *)userdata);
- gzt->srna = srna; /* restore */
+ /* take care not to overwrite anything set in
+ * WM_gizmomaptype_group_link_ptr before opfunc() is called */
+ StructRNA *srna = gzt->srna;
+ *gzt = *((wmGizmoType *)userdata);
+ gzt->srna = srna; /* restore */
- /* don't do translations here yet */
+ /* don't do translations here yet */
#if 0
- /* Use i18n context from ext.srna if possible (py gizmogroups). */
- if (gt->ext.srna) {
- RNA_def_struct_translation_context(gt->srna, RNA_struct_translation_context(gt->ext.srna));
- }
+ /* Use i18n context from ext.srna if possible (py gizmogroups). */
+ if (gt->ext.srna) {
+ RNA_def_struct_translation_context(gt->srna, RNA_struct_translation_context(gt->ext.srna));
+ }
#endif
- gzt->struct_size = sizeof(wmGizmo);
+ gzt->struct_size = sizeof(wmGizmo);
- gizmo_properties_init(gzt);
+ gizmo_properties_init(gzt);
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Gizmo Group
* \{ */
static void gizmogroup_properties_init(wmGizmoGroupType *gzgt)
{
- PyTypeObject *py_class = gzgt->ext.data;
- RNA_struct_blender_type_set(gzgt->ext.srna, gzgt);
-
- /* only call this so pyrna_deferred_register_class gives a useful error
- * WM_operatortype_append_ptr will call RNA_def_struct_identifier
- * later */
- RNA_def_struct_identifier_no_struct_map(gzgt->srna, gzgt->idname);
-
- if (pyrna_deferred_register_class(gzgt->srna, py_class) != 0) {
- PyErr_Print(); /* failed to register operator props */
- PyErr_Clear();
- }
+ PyTypeObject *py_class = gzgt->ext.data;
+ RNA_struct_blender_type_set(gzgt->ext.srna, gzgt);
+
+ /* only call this so pyrna_deferred_register_class gives a useful error
+ * WM_operatortype_append_ptr will call RNA_def_struct_identifier
+ * later */
+ RNA_def_struct_identifier_no_struct_map(gzgt->srna, gzgt->idname);
+
+ if (pyrna_deferred_register_class(gzgt->srna, py_class) != 0) {
+ PyErr_Print(); /* failed to register operator props */
+ PyErr_Clear();
+ }
}
void BPY_RNA_gizmogroup_wrapper(wmGizmoGroupType *gzgt, void *userdata)
{
- /* take care not to overwrite anything set in
- * WM_gizmomaptype_group_link_ptr before opfunc() is called */
- StructRNA *srna = gzgt->srna;
- *gzgt = *((wmGizmoGroupType *)userdata);
- gzgt->srna = srna; /* restore */
+ /* take care not to overwrite anything set in
+ * WM_gizmomaptype_group_link_ptr before opfunc() is called */
+ StructRNA *srna = gzgt->srna;
+ *gzgt = *((wmGizmoGroupType *)userdata);
+ gzgt->srna = srna; /* restore */
- /* don't do translations here yet */
+ /* don't do translations here yet */
#if 0
- /* Use i18n context from ext.srna if possible (py gizmogroups). */
- if (gzgt->ext.srna) {
- RNA_def_struct_translation_context(gzgt->srna, RNA_struct_translation_context(gzgt->ext.srna));
- }
+ /* Use i18n context from ext.srna if possible (py gizmogroups). */
+ if (gzgt->ext.srna) {
+ RNA_def_struct_translation_context(gzgt->srna, RNA_struct_translation_context(gzgt->ext.srna));
+ }
#endif
- gizmogroup_properties_init(gzgt);
+ gizmogroup_properties_init(gzgt);
}
/** \} */
diff --git a/source/blender/python/intern/bpy_gizmo_wrap.h b/source/blender/python/intern/bpy_gizmo_wrap.h
index f1e9773e866..d9031282c40 100644
--- a/source/blender/python/intern/bpy_gizmo_wrap.h
+++ b/source/blender/python/intern/bpy_gizmo_wrap.h
@@ -28,4 +28,4 @@ struct wmGizmoType;
void BPY_RNA_gizmo_wrapper(struct wmGizmoType *gzt, void *userdata);
void BPY_RNA_gizmogroup_wrapper(struct wmGizmoGroupType *gzgt, void *userdata);
-#endif /* __BPY_GIZMO_WRAP_H__ */
+#endif /* __BPY_GIZMO_WRAP_H__ */
diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c
index 61ddf46d896..1b36ded884d 100644
--- a/source/blender/python/intern/bpy_interface.c
+++ b/source/blender/python/intern/bpy_interface.c
@@ -63,7 +63,7 @@
#include "BPY_extern.h"
-#include "../generic/bpy_internal_import.h" /* our own imports */
+#include "../generic/bpy_internal_import.h" /* our own imports */
#include "../generic/py_capi_utils.h"
/* inittab initialization functions */
@@ -87,118 +87,116 @@ static int py_call_level = 0;
// #define TIME_PY_RUN // simple python tests. prints on exit.
#ifdef TIME_PY_RUN
-#include "PIL_time.h"
-static int bpy_timer_count = 0;
-static double bpy_timer; /* time since python starts */
-static double bpy_timer_run; /* time for each python script run */
-static double bpy_timer_run_tot; /* accumulate python runs */
+# include "PIL_time.h"
+static int bpy_timer_count = 0;
+static double bpy_timer; /* time since python starts */
+static double bpy_timer_run; /* time for each python script run */
+static double bpy_timer_run_tot; /* accumulate python runs */
#endif
/* use for updating while a python script runs - in case of file load */
void BPY_context_update(bContext *C)
{
- /* don't do this from a non-main (e.g. render) thread, it can cause a race
- * condition on C->data.recursion. ideal solution would be to disable
- * context entirely from non-main threads, but that's more complicated */
- if (!BLI_thread_is_main()) {
- return;
- }
-
- BPy_SetContext(C);
- bpy_import_main_set(CTX_data_main(C));
- BPY_modules_update(C); /* can give really bad results if this isn't here */
+ /* don't do this from a non-main (e.g. render) thread, it can cause a race
+ * condition on C->data.recursion. ideal solution would be to disable
+ * context entirely from non-main threads, but that's more complicated */
+ if (!BLI_thread_is_main()) {
+ return;
+ }
+
+ BPy_SetContext(C);
+ bpy_import_main_set(CTX_data_main(C));
+ BPY_modules_update(C); /* can give really bad results if this isn't here */
}
void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
{
- py_call_level++;
+ py_call_level++;
- if (gilstate) {
- *gilstate = PyGILState_Ensure();
- }
+ if (gilstate) {
+ *gilstate = PyGILState_Ensure();
+ }
- if (py_call_level == 1) {
- BPY_context_update(C);
+ if (py_call_level == 1) {
+ BPY_context_update(C);
#ifdef TIME_PY_RUN
- if (bpy_timer_count == 0) {
- /* record time from the beginning */
- bpy_timer = PIL_check_seconds_timer();
- bpy_timer_run = bpy_timer_run_tot = 0.0;
- }
- bpy_timer_run = PIL_check_seconds_timer();
-
-
- bpy_timer_count++;
+ if (bpy_timer_count == 0) {
+ /* record time from the beginning */
+ bpy_timer = PIL_check_seconds_timer();
+ bpy_timer_run = bpy_timer_run_tot = 0.0;
+ }
+ bpy_timer_run = PIL_check_seconds_timer();
+
+ bpy_timer_count++;
#endif
- }
+ }
}
/* context should be used but not now because it causes some bugs */
void bpy_context_clear(bContext *UNUSED(C), PyGILState_STATE *gilstate)
{
- py_call_level--;
-
- if (gilstate) {
- PyGILState_Release(*gilstate);
- }
-
- if (py_call_level < 0) {
- fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
- }
- else if (py_call_level == 0) {
- /* XXX - Calling classes currently wont store the context :\,
- * cant set NULL because of this. but this is very flakey still. */
+ py_call_level--;
+
+ if (gilstate) {
+ PyGILState_Release(*gilstate);
+ }
+
+ if (py_call_level < 0) {
+ fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
+ }
+ else if (py_call_level == 0) {
+ /* XXX - Calling classes currently wont store the context :\,
+ * cant set NULL because of this. but this is very flakey still. */
#if 0
- BPy_SetContext(NULL);
- bpy_import_main_set(NULL);
+ BPy_SetContext(NULL);
+ bpy_import_main_set(NULL);
#endif
#ifdef TIME_PY_RUN
- bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
- bpy_timer_count++;
+ bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
+ bpy_timer_count++;
#endif
-
- }
+ }
}
void BPY_text_free_code(Text *text)
{
- if (text->compiled) {
- PyGILState_STATE gilstate;
- bool use_gil = !PyC_IsInterpreterActive();
+ if (text->compiled) {
+ PyGILState_STATE gilstate;
+ bool use_gil = !PyC_IsInterpreterActive();
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- Py_DECREF((PyObject *)text->compiled);
- text->compiled = NULL;
+ Py_DECREF((PyObject *)text->compiled);
+ text->compiled = NULL;
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+ }
}
void BPY_modules_update(bContext *C)
{
-#if 0 /* slow, this runs all the time poll, draw etc 100's of time a sec. */
- PyObject *mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
- PyModule_AddObject(mod, "data", BPY_rna_module());
- PyModule_AddObject(mod, "types", BPY_rna_types()); /* atm this does not need updating */
+#if 0 /* slow, this runs all the time poll, draw etc 100's of time a sec. */
+ PyObject *mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
+ PyModule_AddObject(mod, "data", BPY_rna_module());
+ PyModule_AddObject(mod, "types", BPY_rna_types()); /* atm this does not need updating */
#endif
- /* refreshes the main struct */
- BPY_update_rna_module();
- if (bpy_context_module) {
- bpy_context_module->ptr.data = (void *)C;
- }
+ /* refreshes the main struct */
+ BPY_update_rna_module();
+ if (bpy_context_module) {
+ bpy_context_module->ptr.data = (void *)C;
+ }
}
void BPY_context_set(bContext *C)
{
- BPy_SetContext(C);
+ BPy_SetContext(C);
}
/* defined in AUD_C-API.cpp */
@@ -208,214 +206,213 @@ extern PyObject *AUD_initPython(void);
/* defined in cycles module */
static PyObject *CCL_initPython(void)
{
- return (PyObject *)CCL_python_module_init();
+ return (PyObject *)CCL_python_module_init();
}
#endif
static struct _inittab bpy_internal_modules[] = {
- {"mathutils", PyInit_mathutils},
+ {"mathutils", PyInit_mathutils},
#if 0
- {"mathutils.geometry", PyInit_mathutils_geometry},
- {"mathutils.noise", PyInit_mathutils_noise},
- {"mathutils.kdtree", PyInit_mathutils_kdtree},
+ {"mathutils.geometry", PyInit_mathutils_geometry},
+ {"mathutils.noise", PyInit_mathutils_noise},
+ {"mathutils.kdtree", PyInit_mathutils_kdtree},
#endif
- {"_bpy_path", BPyInit__bpy_path},
- {"bgl", BPyInit_bgl},
- {"blf", BPyInit_blf},
- {"imbuf", BPyInit_imbuf},
- {"bmesh", BPyInit_bmesh},
+ {"_bpy_path", BPyInit__bpy_path},
+ {"bgl", BPyInit_bgl},
+ {"blf", BPyInit_blf},
+ {"imbuf", BPyInit_imbuf},
+ {"bmesh", BPyInit_bmesh},
#if 0
- {"bmesh.types", BPyInit_bmesh_types},
- {"bmesh.utils", BPyInit_bmesh_utils},
- {"bmesh.utils", BPyInit_bmesh_geometry},
+ {"bmesh.types", BPyInit_bmesh_types},
+ {"bmesh.utils", BPyInit_bmesh_utils},
+ {"bmesh.utils", BPyInit_bmesh_geometry},
#endif
#ifdef WITH_AUDASPACE
- {"aud", AUD_initPython},
+ {"aud", AUD_initPython},
#endif
#ifdef WITH_CYCLES
- {"_cycles", CCL_initPython},
+ {"_cycles", CCL_initPython},
#endif
- {"gpu", BPyInit_gpu},
- {"idprop", BPyInit_idprop},
- {NULL, NULL},
+ {"gpu", BPyInit_gpu},
+ {"idprop", BPyInit_idprop},
+ {NULL, NULL},
};
/* call BPY_context_set first */
void BPY_python_start(int argc, const char **argv)
{
#ifndef WITH_PYTHON_MODULE
- PyThreadState *py_tstate = NULL;
- const char *py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL);
-
- /* not essential but nice to set our name */
- static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */
- BLI_strncpy_wchar_from_utf8(program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar));
- Py_SetProgramName(program_path_wchar);
-
- /* must run before python initializes */
- PyImport_ExtendInittab(bpy_internal_modules);
-
- /* allow to use our own included python */
- PyC_SetHomePath(py_path_bundle);
-
- /* without this the sys.stdout may be set to 'ascii'
- * (it is on my system at least), where printing unicode values will raise
- * an error, this is highly annoying, another stumbling block for devs,
- * so use a more relaxed error handler and enforce utf-8 since the rest of
- * blender is utf-8 too - campbell */
- Py_SetStandardStreamEncoding("utf-8", "surrogateescape");
-
- /* Update, Py3.3 resolves attempting to parse non-existing header */
-#if 0
- /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to
- * parse from the 'sysconfig' module which is used by 'site',
- * so for now disable site. alternatively we could copy the file. */
- if (py_path_bundle) {
- Py_NoSiteFlag = 1;
- }
-#endif
-
- Py_FrozenFlag = 1;
-
- Py_Initialize();
-
- // PySys_SetArgv(argc, argv); /* broken in py3, not a huge deal */
- /* sigh, why do python guys not have a (char **) version anymore? */
- {
- int i;
- PyObject *py_argv = PyList_New(argc);
- for (i = 0; i < argc; i++) {
- /* should fix bug #20021 - utf path name problems, by replacing
- * PyUnicode_FromString, with this one */
- PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
- }
-
- PySys_SetObject("argv", py_argv);
- Py_DECREF(py_argv);
- }
-
- /* Initialize thread support (also acquires lock) */
- PyEval_InitThreads();
+ PyThreadState *py_tstate = NULL;
+ const char *py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL);
+
+ /* not essential but nice to set our name */
+ static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */
+ BLI_strncpy_wchar_from_utf8(
+ program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar));
+ Py_SetProgramName(program_path_wchar);
+
+ /* must run before python initializes */
+ PyImport_ExtendInittab(bpy_internal_modules);
+
+ /* allow to use our own included python */
+ PyC_SetHomePath(py_path_bundle);
+
+ /* without this the sys.stdout may be set to 'ascii'
+ * (it is on my system at least), where printing unicode values will raise
+ * an error, this is highly annoying, another stumbling block for devs,
+ * so use a more relaxed error handler and enforce utf-8 since the rest of
+ * blender is utf-8 too - campbell */
+ Py_SetStandardStreamEncoding("utf-8", "surrogateescape");
+
+ /* Update, Py3.3 resolves attempting to parse non-existing header */
+# if 0
+ /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to
+ * parse from the 'sysconfig' module which is used by 'site',
+ * so for now disable site. alternatively we could copy the file. */
+ if (py_path_bundle) {
+ Py_NoSiteFlag = 1;
+ }
+# endif
+
+ Py_FrozenFlag = 1;
+
+ Py_Initialize();
+
+ // PySys_SetArgv(argc, argv); /* broken in py3, not a huge deal */
+ /* sigh, why do python guys not have a (char **) version anymore? */
+ {
+ int i;
+ PyObject *py_argv = PyList_New(argc);
+ for (i = 0; i < argc; i++) {
+ /* should fix bug #20021 - utf path name problems, by replacing
+ * PyUnicode_FromString, with this one */
+ PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
+ }
+
+ PySys_SetObject("argv", py_argv);
+ Py_DECREF(py_argv);
+ }
+
+ /* Initialize thread support (also acquires lock) */
+ PyEval_InitThreads();
#else
- (void)argc;
- (void)argv;
+ (void)argc;
+ (void)argv;
- /* must run before python initializes */
- /* broken in py3.3, load explicitly below */
- // PyImport_ExtendInittab(bpy_internal_modules);
+ /* must run before python initializes */
+ /* broken in py3.3, load explicitly below */
+ // PyImport_ExtendInittab(bpy_internal_modules);
#endif
- bpy_intern_string_init();
-
+ bpy_intern_string_init();
#ifdef WITH_PYTHON_MODULE
- {
- /* Manually load all modules */
- struct _inittab *inittab_item;
- PyObject *sys_modules = PyImport_GetModuleDict();
-
- for (inittab_item = bpy_internal_modules; inittab_item->name; inittab_item++) {
- PyObject *mod = inittab_item->initfunc();
- if (mod) {
- PyDict_SetItemString(sys_modules, inittab_item->name, mod);
- }
- else {
- PyErr_Print();
- PyErr_Clear();
- }
- // Py_DECREF(mod); /* ideally would decref, but in this case we never want to free */
- }
- }
+ {
+ /* Manually load all modules */
+ struct _inittab *inittab_item;
+ PyObject *sys_modules = PyImport_GetModuleDict();
+
+ for (inittab_item = bpy_internal_modules; inittab_item->name; inittab_item++) {
+ PyObject *mod = inittab_item->initfunc();
+ if (mod) {
+ PyDict_SetItemString(sys_modules, inittab_item->name, mod);
+ }
+ else {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ // Py_DECREF(mod); /* ideally would decref, but in this case we never want to free */
+ }
+ }
#endif
- /* bpy.* and lets us import it */
- BPy_init_modules();
+ /* bpy.* and lets us import it */
+ BPy_init_modules();
- bpy_import_init(PyEval_GetBuiltins());
+ bpy_import_init(PyEval_GetBuiltins());
- pyrna_alloc_types();
+ pyrna_alloc_types();
#ifndef WITH_PYTHON_MODULE
- /* py module runs atexit when bpy is freed */
- BPY_atexit_register(); /* this can init any time */
+ /* py module runs atexit when bpy is freed */
+ BPY_atexit_register(); /* this can init any time */
- py_tstate = PyGILState_GetThisThreadState();
- PyEval_ReleaseThread(py_tstate);
+ py_tstate = PyGILState_GetThisThreadState();
+ PyEval_ReleaseThread(py_tstate);
#endif
}
void BPY_python_end(void)
{
- // fprintf(stderr, "Ending Python!\n");
- PyGILState_STATE gilstate;
+ // fprintf(stderr, "Ending Python!\n");
+ PyGILState_STATE gilstate;
- /* finalizing, no need to grab the state, except when we are a module */
- gilstate = PyGILState_Ensure();
+ /* finalizing, no need to grab the state, except when we are a module */
+ gilstate = PyGILState_Ensure();
- /* free other python data. */
- pyrna_free_types();
+ /* free other python data. */
+ pyrna_free_types();
- /* clear all python data from structs */
+ /* clear all python data from structs */
- bpy_intern_string_exit();
+ bpy_intern_string_exit();
- /* bpy.app modules that need cleanup */
- BPY_app_translations_end();
+ /* bpy.app modules that need cleanup */
+ BPY_app_translations_end();
#ifndef WITH_PYTHON_MODULE
- BPY_atexit_unregister(); /* without this we get recursive calls to WM_exit */
+ BPY_atexit_unregister(); /* without this we get recursive calls to WM_exit */
- Py_Finalize();
+ Py_Finalize();
- (void)gilstate;
+ (void)gilstate;
#else
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
#ifdef TIME_PY_RUN
- /* measure time since py started */
- bpy_timer = PIL_check_seconds_timer() - bpy_timer;
+ /* measure time since py started */
+ bpy_timer = PIL_check_seconds_timer() - bpy_timer;
- printf("*bpy stats* - ");
- printf("tot exec: %d, ", bpy_timer_count);
- printf("tot run: %.4fsec, ", bpy_timer_run_tot);
- if (bpy_timer_count > 0) {
- printf("average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
- }
+ printf("*bpy stats* - ");
+ printf("tot exec: %d, ", bpy_timer_count);
+ printf("tot run: %.4fsec, ", bpy_timer_run_tot);
+ if (bpy_timer_count > 0) {
+ printf("average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
+ }
- if (bpy_timer > 0.0) {
- printf("tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
- }
+ if (bpy_timer > 0.0) {
+ printf("tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
+ }
- printf("\n");
+ printf("\n");
- // fprintf(stderr, "Ending Python Done!\n");
+ // fprintf(stderr, "Ending Python Done!\n");
#endif
-
}
void BPY_python_reset(bContext *C)
{
- /* unrelated security stuff */
- G.f &= ~(G_FLAG_SCRIPT_AUTOEXEC_FAIL | G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET);
- G.autoexec_fail[0] = '\0';
+ /* unrelated security stuff */
+ G.f &= ~(G_FLAG_SCRIPT_AUTOEXEC_FAIL | G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET);
+ G.autoexec_fail[0] = '\0';
- BPY_driver_reset();
- BPY_app_handlers_reset(false);
- BPY_modules_load_user(C);
+ BPY_driver_reset();
+ BPY_app_handlers_reset(false);
+ BPY_modules_load_user(C);
}
static void python_script_error_jump_text(struct Text *text)
{
- int lineno;
- int offset;
- python_script_error_jump(text->id.name + 2, &lineno, &offset);
- if (lineno != -1) {
- /* select the line with the error */
- txt_move_to(text, lineno - 1, INT_MAX, false);
- txt_move_to(text, lineno - 1, offset, true);
- }
+ int lineno;
+ int offset;
+ python_script_error_jump(text->id.name + 2, &lineno, &offset);
+ if (lineno != -1) {
+ /* select the line with the error */
+ txt_move_to(text, lineno - 1, INT_MAX, false);
+ txt_move_to(text, lineno - 1, offset, true);
+ }
}
/* super annoying, undo _PyModule_Clear(), bug [#23871] */
@@ -425,240 +422,236 @@ static void python_script_error_jump_text(struct Text *text)
/* bad!, we should never do this, but currently only safe way I could find to keep namespace.
* from being cleared. - campbell */
typedef struct {
- PyObject_HEAD
- PyObject *md_dict;
- /* omit other values, we only want the dict. */
+ PyObject_HEAD PyObject *md_dict;
+ /* omit other values, we only want the dict. */
} PyModuleObject;
#endif
static bool python_script_exec(
- bContext *C, const char *fn, struct Text *text,
- struct ReportList *reports, const bool do_jump)
+ bContext *C, const char *fn, struct Text *text, struct ReportList *reports, const bool do_jump)
{
- Main *bmain_old = CTX_data_main(C);
- PyObject *main_mod = NULL;
- PyObject *py_dict = NULL, *py_result = NULL;
- PyGILState_STATE gilstate;
-
- BLI_assert(fn || text);
+ Main *bmain_old = CTX_data_main(C);
+ PyObject *main_mod = NULL;
+ PyObject *py_dict = NULL, *py_result = NULL;
+ PyGILState_STATE gilstate;
- if (fn == NULL && text == NULL) {
- return 0;
- }
+ BLI_assert(fn || text);
- bpy_context_set(C, &gilstate);
+ if (fn == NULL && text == NULL) {
+ return 0;
+ }
- PyC_MainModule_Backup(&main_mod);
+ bpy_context_set(C, &gilstate);
- if (text) {
- char fn_dummy[FILE_MAXDIR];
- bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
+ PyC_MainModule_Backup(&main_mod);
- if (text->compiled == NULL) { /* if it wasn't already compiled, do it now */
- char *buf;
- PyObject *fn_dummy_py;
+ if (text) {
+ char fn_dummy[FILE_MAXDIR];
+ bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
- fn_dummy_py = PyC_UnicodeFromByte(fn_dummy);
+ if (text->compiled == NULL) { /* if it wasn't already compiled, do it now */
+ char *buf;
+ PyObject *fn_dummy_py;
- buf = txt_to_buf(text);
- text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1);
- MEM_freeN(buf);
+ fn_dummy_py = PyC_UnicodeFromByte(fn_dummy);
- Py_DECREF(fn_dummy_py);
+ buf = txt_to_buf(text);
+ text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1);
+ MEM_freeN(buf);
- if (PyErr_Occurred()) {
- if (do_jump) {
- python_script_error_jump_text(text);
- }
- BPY_text_free_code(text);
- }
- }
+ Py_DECREF(fn_dummy_py);
- if (text->compiled) {
- py_dict = PyC_DefaultNameSpace(fn_dummy);
- py_result = PyEval_EvalCode(text->compiled, py_dict, py_dict);
- }
+ if (PyErr_Occurred()) {
+ if (do_jump) {
+ python_script_error_jump_text(text);
+ }
+ BPY_text_free_code(text);
+ }
+ }
- }
- else {
- FILE *fp = BLI_fopen(fn, "r");
+ if (text->compiled) {
+ py_dict = PyC_DefaultNameSpace(fn_dummy);
+ py_result = PyEval_EvalCode(text->compiled, py_dict, py_dict);
+ }
+ }
+ else {
+ FILE *fp = BLI_fopen(fn, "r");
- if (fp) {
- py_dict = PyC_DefaultNameSpace(fn);
+ if (fp) {
+ py_dict = PyC_DefaultNameSpace(fn);
#ifdef _WIN32
- /* Previously we used PyRun_File to run directly the code on a FILE
- * object, but as written in the Python/C API Ref Manual, chapter 2,
- * 'FILE structs for different C libraries can be different and
- * incompatible'.
- * So now we load the script file data to a buffer.
- *
- * Note on use of 'globals()', it's important not copy the dictionary because
- * tools may inspect 'sys.modules["__main__"]' for variables defined in the code
- * where using a copy of 'globals()' causes code execution
- * to leave the main namespace untouched. see: T51444
- *
- * This leaves us with the problem of variables being included,
- * currently this is worked around using 'dict.__del__' it's ugly but works.
- */
- {
- const char *pystring =
- "with open(__file__, 'rb') as f:"
- "exec(compile(f.read(), __file__, 'exec'), globals().__delitem__('f') or globals())";
-
- fclose(fp);
-
- py_result = PyRun_String(pystring, Py_file_input, py_dict, py_dict);
- }
+ /* Previously we used PyRun_File to run directly the code on a FILE
+ * object, but as written in the Python/C API Ref Manual, chapter 2,
+ * 'FILE structs for different C libraries can be different and
+ * incompatible'.
+ * So now we load the script file data to a buffer.
+ *
+ * Note on use of 'globals()', it's important not copy the dictionary because
+ * tools may inspect 'sys.modules["__main__"]' for variables defined in the code
+ * where using a copy of 'globals()' causes code execution
+ * to leave the main namespace untouched. see: T51444
+ *
+ * This leaves us with the problem of variables being included,
+ * currently this is worked around using 'dict.__del__' it's ugly but works.
+ */
+ {
+ const char *pystring =
+ "with open(__file__, 'rb') as f:"
+ "exec(compile(f.read(), __file__, 'exec'), globals().__delitem__('f') or globals())";
+
+ fclose(fp);
+
+ py_result = PyRun_String(pystring, Py_file_input, py_dict, py_dict);
+ }
#else
- py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
- fclose(fp);
+ py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
+ fclose(fp);
#endif
- }
- else {
- PyErr_Format(PyExc_IOError,
- "Python file \"%s\" could not be opened: %s",
- fn, strerror(errno));
- py_result = NULL;
- }
- }
-
- if (!py_result) {
- if (text) {
- if (do_jump) {
- /* ensure text is valid before use, the script may have freed its self */
- Main *bmain_new = CTX_data_main(C);
- if ((bmain_old == bmain_new) && (BLI_findindex(&bmain_new->texts, text) != -1)) {
- python_script_error_jump_text(text);
- }
- }
- }
- BPy_errors_to_report(reports);
- }
- else {
- Py_DECREF(py_result);
- }
-
- if (py_dict) {
+ }
+ else {
+ PyErr_Format(
+ PyExc_IOError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
+ py_result = NULL;
+ }
+ }
+
+ if (!py_result) {
+ if (text) {
+ if (do_jump) {
+ /* ensure text is valid before use, the script may have freed its self */
+ Main *bmain_new = CTX_data_main(C);
+ if ((bmain_old == bmain_new) && (BLI_findindex(&bmain_new->texts, text) != -1)) {
+ python_script_error_jump_text(text);
+ }
+ }
+ }
+ BPy_errors_to_report(reports);
+ }
+ else {
+ Py_DECREF(py_result);
+ }
+
+ if (py_dict) {
#ifdef PYMODULE_CLEAR_WORKAROUND
- PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItem(
- PyImport_GetModuleDict(), bpy_intern_str___main__);
- PyObject *dict_back = mmod->md_dict;
- /* freeing the module will clear the namespace,
- * gives problems running classes defined in this namespace being used later. */
- mmod->md_dict = NULL;
- Py_DECREF(dict_back);
+ PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItem(PyImport_GetModuleDict(),
+ bpy_intern_str___main__);
+ PyObject *dict_back = mmod->md_dict;
+ /* freeing the module will clear the namespace,
+ * gives problems running classes defined in this namespace being used later. */
+ mmod->md_dict = NULL;
+ Py_DECREF(dict_back);
#endif
#undef PYMODULE_CLEAR_WORKAROUND
- }
+ }
- PyC_MainModule_Restore(main_mod);
+ PyC_MainModule_Restore(main_mod);
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- return (py_result != NULL);
+ return (py_result != NULL);
}
/* Can run a file or text block */
bool BPY_execute_filepath(bContext *C, const char *filepath, struct ReportList *reports)
{
- return python_script_exec(C, filepath, NULL, reports, false);
+ return python_script_exec(C, filepath, NULL, reports, false);
}
-
-bool BPY_execute_text(bContext *C, struct Text *text, struct ReportList *reports, const bool do_jump)
+bool BPY_execute_text(bContext *C,
+ struct Text *text,
+ struct ReportList *reports,
+ const bool do_jump)
{
- return python_script_exec(C, NULL, text, reports, do_jump);
+ return python_script_exec(C, NULL, text, reports, do_jump);
}
void BPY_DECREF(void *pyob_ptr)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
- Py_DECREF((PyObject *)pyob_ptr);
- PyGILState_Release(gilstate);
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ Py_DECREF((PyObject *)pyob_ptr);
+ PyGILState_Release(gilstate);
}
void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
- const int do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
- Py_DECREF((PyObject *)pyob_ptr);
- if (do_invalidate) {
- pyrna_invalidate(pyob_ptr);
- }
- PyGILState_Release(gilstate);
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ const int do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
+ Py_DECREF((PyObject *)pyob_ptr);
+ if (do_invalidate) {
+ pyrna_invalidate(pyob_ptr);
+ }
+ PyGILState_Release(gilstate);
}
/**
* \return success
*/
bool BPY_execute_string_as_number(
- bContext *C, const char *imports[],
- const char *expr, const bool verbose, double *r_value)
+ bContext *C, const char *imports[], const char *expr, const bool verbose, double *r_value)
{
- PyGILState_STATE gilstate;
- bool ok = true;
+ PyGILState_STATE gilstate;
+ bool ok = true;
- if (!r_value || !expr) {
- return -1;
- }
+ if (!r_value || !expr) {
+ return -1;
+ }
- if (expr[0] == '\0') {
- *r_value = 0.0;
- return ok;
- }
+ if (expr[0] == '\0') {
+ *r_value = 0.0;
+ return ok;
+ }
- bpy_context_set(C, &gilstate);
+ bpy_context_set(C, &gilstate);
- ok = PyC_RunString_AsNumber(imports, expr, "<expr as number>", r_value);
+ ok = PyC_RunString_AsNumber(imports, expr, "<expr as number>", r_value);
- if (ok == false) {
- if (verbose) {
- BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
- }
- else {
- PyErr_Clear();
- }
- }
+ if (ok == false) {
+ if (verbose) {
+ BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- return ok;
+ return ok;
}
/**
* \return success
*/
bool BPY_execute_string_as_string(
- bContext *C, const char *imports[],
- const char *expr, const bool verbose, char **r_value)
+ bContext *C, const char *imports[], const char *expr, const bool verbose, char **r_value)
{
- BLI_assert(r_value && expr);
- PyGILState_STATE gilstate;
- bool ok = true;
+ BLI_assert(r_value && expr);
+ PyGILState_STATE gilstate;
+ bool ok = true;
- if (expr[0] == '\0') {
- *r_value = NULL;
- return ok;
- }
+ if (expr[0] == '\0') {
+ *r_value = NULL;
+ return ok;
+ }
- bpy_context_set(C, &gilstate);
+ bpy_context_set(C, &gilstate);
- ok = PyC_RunString_AsString(imports, expr, "<expr as str>", r_value);
+ ok = PyC_RunString_AsString(imports, expr, "<expr as str>", r_value);
- if (ok == false) {
- if (verbose) {
- BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
- }
- else {
- PyErr_Clear();
- }
- }
+ if (ok == false) {
+ if (verbose) {
+ BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- return ok;
+ return ok;
}
/**
@@ -667,226 +660,225 @@ bool BPY_execute_string_as_string(
* \return success
*/
bool BPY_execute_string_as_intptr(
- bContext *C, const char *imports[],
- const char *expr, const bool verbose, intptr_t *r_value)
+ bContext *C, const char *imports[], const char *expr, const bool verbose, intptr_t *r_value)
{
- BLI_assert(r_value && expr);
- PyGILState_STATE gilstate;
- bool ok = true;
+ BLI_assert(r_value && expr);
+ PyGILState_STATE gilstate;
+ bool ok = true;
- if (expr[0] == '\0') {
- *r_value = 0;
- return ok;
- }
+ if (expr[0] == '\0') {
+ *r_value = 0;
+ return ok;
+ }
- bpy_context_set(C, &gilstate);
+ bpy_context_set(C, &gilstate);
- ok = PyC_RunString_AsIntPtr(imports, expr, "<expr as intptr>", r_value);
+ ok = PyC_RunString_AsIntPtr(imports, expr, "<expr as intptr>", r_value);
- if (ok == false) {
- if (verbose) {
- BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
- }
- else {
- PyErr_Clear();
- }
- }
+ if (ok == false) {
+ if (verbose) {
+ BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- return ok;
+ return ok;
}
-bool BPY_execute_string_ex(
- bContext *C, const char *imports[],
- const char *expr, bool use_eval)
+bool BPY_execute_string_ex(bContext *C, const char *imports[], const char *expr, bool use_eval)
{
- BLI_assert(expr);
- PyGILState_STATE gilstate;
- PyObject *main_mod = NULL;
- PyObject *py_dict, *retval;
- bool ok = true;
- Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
+ BLI_assert(expr);
+ PyGILState_STATE gilstate;
+ PyObject *main_mod = NULL;
+ PyObject *py_dict, *retval;
+ bool ok = true;
+ Main *
+ bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
- if (expr[0] == '\0') {
- return ok;
- }
+ if (expr[0] == '\0') {
+ return ok;
+ }
- bpy_context_set(C, &gilstate);
+ bpy_context_set(C, &gilstate);
- PyC_MainModule_Backup(&main_mod);
+ PyC_MainModule_Backup(&main_mod);
- py_dict = PyC_DefaultNameSpace("<blender string>");
+ py_dict = PyC_DefaultNameSpace("<blender string>");
- bmain_back = bpy_import_main_get();
- bpy_import_main_set(CTX_data_main(C));
+ bmain_back = bpy_import_main_get();
+ bpy_import_main_set(CTX_data_main(C));
- if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
- Py_DECREF(py_dict);
- retval = NULL;
- }
- else {
- retval = PyRun_String(expr, use_eval ? Py_eval_input : Py_file_input, py_dict, py_dict);
- }
+ if (imports && (!PyC_NameSpace_ImportArray(py_dict, imports))) {
+ Py_DECREF(py_dict);
+ retval = NULL;
+ }
+ else {
+ retval = PyRun_String(expr, use_eval ? Py_eval_input : Py_file_input, py_dict, py_dict);
+ }
- bpy_import_main_set(bmain_back);
+ bpy_import_main_set(bmain_back);
- if (retval == NULL) {
- ok = false;
- BPy_errors_to_report(CTX_wm_reports(C));
- }
- else {
- Py_DECREF(retval);
- }
+ if (retval == NULL) {
+ ok = false;
+ BPy_errors_to_report(CTX_wm_reports(C));
+ }
+ else {
+ Py_DECREF(retval);
+ }
- PyC_MainModule_Restore(main_mod);
+ PyC_MainModule_Restore(main_mod);
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- return ok;
+ return ok;
}
-bool BPY_execute_string(
- bContext *C, const char *imports[],
- const char *expr)
+bool BPY_execute_string(bContext *C, const char *imports[], const char *expr)
{
- return BPY_execute_string_ex(C, imports, expr, true);
+ return BPY_execute_string_ex(C, imports, expr, true);
}
void BPY_modules_load_user(bContext *C)
{
- PyGILState_STATE gilstate;
- Main *bmain = CTX_data_main(C);
- Text *text;
-
- /* can happen on file load */
- if (bmain == NULL) {
- return;
- }
-
- /* update pointers since this can run from a nested script
- * on file load */
- if (py_call_level) {
- BPY_context_update(C);
- }
-
- bpy_context_set(C, &gilstate);
-
- for (text = bmain->texts.first; text; text = text->id.next) {
- if (text->flags & TXT_ISSCRIPT && BLI_path_extension_check(text->id.name + 2, ".py")) {
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
- if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
- G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
- BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Text '%s'", text->id.name + 2);
-
- printf("scripts disabled for \"%s\", skipping '%s'\n", BKE_main_blendfile_path(bmain), text->id.name + 2);
- }
- }
- else {
- PyObject *module = bpy_text_import(text);
-
- if (module == NULL) {
- PyErr_Print();
- PyErr_Clear();
- }
- else {
- Py_DECREF(module);
- }
-
- /* check if the script loaded a new file */
- if (bmain != CTX_data_main(C)) {
- break;
- }
- }
- }
- }
- bpy_context_clear(C, &gilstate);
+ PyGILState_STATE gilstate;
+ Main *bmain = CTX_data_main(C);
+ Text *text;
+
+ /* can happen on file load */
+ if (bmain == NULL) {
+ return;
+ }
+
+ /* update pointers since this can run from a nested script
+ * on file load */
+ if (py_call_level) {
+ BPY_context_update(C);
+ }
+
+ bpy_context_set(C, &gilstate);
+
+ for (text = bmain->texts.first; text; text = text->id.next) {
+ if (text->flags & TXT_ISSCRIPT && BLI_path_extension_check(text->id.name + 2, ".py")) {
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
+ if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
+ G.f |= G_FLAG_SCRIPT_AUTOEXEC_FAIL;
+ BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Text '%s'", text->id.name + 2);
+
+ printf("scripts disabled for \"%s\", skipping '%s'\n",
+ BKE_main_blendfile_path(bmain),
+ text->id.name + 2);
+ }
+ }
+ else {
+ PyObject *module = bpy_text_import(text);
+
+ if (module == NULL) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ else {
+ Py_DECREF(module);
+ }
+
+ /* check if the script loaded a new file */
+ if (bmain != CTX_data_main(C)) {
+ break;
+ }
+ }
+ }
+ }
+ bpy_context_clear(C, &gilstate);
}
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
{
- PyGILState_STATE gilstate;
- bool use_gil = !PyC_IsInterpreterActive();
-
- PyObject *pyctx;
- PyObject *item;
- PointerRNA *ptr = NULL;
- bool done = false;
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- pyctx = (PyObject *)CTX_py_dict_get(C);
- item = PyDict_GetItemString(pyctx, member);
-
- if (item == NULL) {
- /* pass */
- }
- else if (item == Py_None) {
- done = true;
- }
- else if (BPy_StructRNA_Check(item)) {
- ptr = &(((BPy_StructRNA *)item)->ptr);
-
- //result->ptr = ((BPy_StructRNA *)item)->ptr;
- CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
- CTX_data_type_set(result, CTX_DATA_TYPE_POINTER);
- done = true;
- }
- else if (PySequence_Check(item)) {
- PyObject *seq_fast = PySequence_Fast(item, "bpy_context_get sequence conversion");
- if (seq_fast == NULL) {
- PyErr_Print();
- PyErr_Clear();
- }
- else {
- int len = PySequence_Fast_GET_SIZE(seq_fast);
- PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
- int i;
-
- for (i = 0; i < len; i++) {
- PyObject *list_item = seq_fast_items[i];
-
- if (BPy_StructRNA_Check(list_item)) {
+ PyGILState_STATE gilstate;
+ bool use_gil = !PyC_IsInterpreterActive();
+
+ PyObject *pyctx;
+ PyObject *item;
+ PointerRNA *ptr = NULL;
+ bool done = false;
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ pyctx = (PyObject *)CTX_py_dict_get(C);
+ item = PyDict_GetItemString(pyctx, member);
+
+ if (item == NULL) {
+ /* pass */
+ }
+ else if (item == Py_None) {
+ done = true;
+ }
+ else if (BPy_StructRNA_Check(item)) {
+ ptr = &(((BPy_StructRNA *)item)->ptr);
+
+ //result->ptr = ((BPy_StructRNA *)item)->ptr;
+ CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
+ CTX_data_type_set(result, CTX_DATA_TYPE_POINTER);
+ done = true;
+ }
+ else if (PySequence_Check(item)) {
+ PyObject *seq_fast = PySequence_Fast(item, "bpy_context_get sequence conversion");
+ if (seq_fast == NULL) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ else {
+ int len = PySequence_Fast_GET_SIZE(seq_fast);
+ PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
+ int i;
+
+ for (i = 0; i < len; i++) {
+ PyObject *list_item = seq_fast_items[i];
+
+ if (BPy_StructRNA_Check(list_item)) {
#if 0
- CollectionPointerLink *link = MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
- link->ptr = ((BPy_StructRNA *)item)->ptr;
- BLI_addtail(&result->list, link);
+ CollectionPointerLink *link = MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
+ link->ptr = ((BPy_StructRNA *)item)->ptr;
+ BLI_addtail(&result->list, link);
#endif
- ptr = &(((BPy_StructRNA *)list_item)->ptr);
- CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
- }
- else {
- CLOG_INFO(BPY_LOG_CONTEXT, 1,
- "'%s' list item not a valid type in sequence type '%s'",
- member, Py_TYPE(item)->tp_name);
- }
-
- }
- Py_DECREF(seq_fast);
- CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
- done = true;
- }
- }
-
- if (done == false) {
- if (item) {
- CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not a valid type", member);
- }
- else {
- CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not found\n", member);
- }
- }
- else {
- CLOG_INFO(BPY_LOG_CONTEXT, 2, "'%s' found", member);
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- return done;
+ ptr = &(((BPy_StructRNA *)list_item)->ptr);
+ CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
+ }
+ else {
+ CLOG_INFO(BPY_LOG_CONTEXT,
+ 1,
+ "'%s' list item not a valid type in sequence type '%s'",
+ member,
+ Py_TYPE(item)->tp_name);
+ }
+ }
+ Py_DECREF(seq_fast);
+ CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
+ done = true;
+ }
+ }
+
+ if (done == false) {
+ if (item) {
+ CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not a valid type", member);
+ }
+ else {
+ CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not found\n", member);
+ }
+ }
+ else {
+ CLOG_INFO(BPY_LOG_CONTEXT, 2, "'%s' found", member);
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ return done;
}
#ifdef WITH_PYTHON_MODULE
@@ -896,48 +888,48 @@ static void bpy_module_free(void *mod);
extern int main_python_enter(int argc, const char **argv);
extern void main_python_exit(void);
static struct PyModuleDef bpy_proxy_def = {
- PyModuleDef_HEAD_INIT,
- "bpy", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- bpy_module_free, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "bpy", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ bpy_module_free, /* m_free */
};
typedef struct {
- PyObject_HEAD
- /* Type-specific fields go here. */
- PyObject *mod;
+ PyObject_HEAD
+ /* Type-specific fields go here. */
+ PyObject *mod;
} dealloc_obj;
/* call once __file__ is set */
static void bpy_module_delay_init(PyObject *bpy_proxy)
{
- const int argc = 1;
- const char *argv[2];
+ const int argc = 1;
+ const char *argv[2];
- /* updating the module dict below will loose the reference to __file__ */
- PyObject *filename_obj = PyModule_GetFilenameObject(bpy_proxy);
+ /* updating the module dict below will loose the reference to __file__ */
+ PyObject *filename_obj = PyModule_GetFilenameObject(bpy_proxy);
- const char *filename_rel = _PyUnicode_AsString(filename_obj); /* can be relative */
- char filename_abs[1024];
+ const char *filename_rel = _PyUnicode_AsString(filename_obj); /* can be relative */
+ char filename_abs[1024];
- BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
- BLI_path_cwd(filename_abs, sizeof(filename_abs));
- Py_DECREF(filename_obj);
+ BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
+ BLI_path_cwd(filename_abs, sizeof(filename_abs));
+ Py_DECREF(filename_obj);
- argv[0] = filename_abs;
- argv[1] = NULL;
+ argv[0] = filename_abs;
+ argv[1] = NULL;
- // printf("module found %s\n", argv[0]);
+ // printf("module found %s\n", argv[0]);
- main_python_enter(argc, argv);
+ main_python_enter(argc, argv);
- /* initialized in BPy_init_modules() */
- PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
+ /* initialized in BPy_init_modules() */
+ PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
}
static void dealloc_obj_dealloc(PyObject *self);
@@ -947,57 +939,55 @@ static PyTypeObject dealloc_obj_Type;
/* use our own dealloc so we can free a property if we use one */
static void dealloc_obj_dealloc(PyObject *self)
{
- bpy_module_delay_init(((dealloc_obj *)self)->mod);
+ bpy_module_delay_init(((dealloc_obj *)self)->mod);
- /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
- dealloc_obj_Type.tp_free(self);
+ /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
+ dealloc_obj_Type.tp_free(self);
}
-PyMODINIT_FUNC
-PyInit_bpy(void);
+PyMODINIT_FUNC PyInit_bpy(void);
-PyMODINIT_FUNC
-PyInit_bpy(void)
+PyMODINIT_FUNC PyInit_bpy(void)
{
- PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
-
- /* Problem:
- * 1) this init function is expected to have a private member defined - 'md_def'
- * but this is only set for C defined modules (not py packages)
- * so we cant return 'bpy_package_py' as is.
- *
- * 2) there is a 'bpy' C module for python to load which is basically all of blender,
- * and there is scripts/bpy/__init__.py,
- * we may end up having to rename this module so there is no naming conflict here eg:
- * 'from blender import bpy'
- *
- * 3) we don't know the filename at this point, workaround by assigning a dummy value
- * which calls back when its freed so the real loading can take place.
- */
-
- /* assign an object which is freed after __file__ is assigned */
- dealloc_obj *dob;
-
- /* assign dummy type */
- dealloc_obj_Type.tp_name = "dealloc_obj";
- dealloc_obj_Type.tp_basicsize = sizeof(dealloc_obj);
- dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
- dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
-
- if (PyType_Ready(&dealloc_obj_Type) < 0) {
- return NULL;
- }
-
- dob = (dealloc_obj *) dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
- dob->mod = bpy_proxy; /* borrow */
- PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
-
- return bpy_proxy;
+ PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
+
+ /* Problem:
+ * 1) this init function is expected to have a private member defined - 'md_def'
+ * but this is only set for C defined modules (not py packages)
+ * so we cant return 'bpy_package_py' as is.
+ *
+ * 2) there is a 'bpy' C module for python to load which is basically all of blender,
+ * and there is scripts/bpy/__init__.py,
+ * we may end up having to rename this module so there is no naming conflict here eg:
+ * 'from blender import bpy'
+ *
+ * 3) we don't know the filename at this point, workaround by assigning a dummy value
+ * which calls back when its freed so the real loading can take place.
+ */
+
+ /* assign an object which is freed after __file__ is assigned */
+ dealloc_obj *dob;
+
+ /* assign dummy type */
+ dealloc_obj_Type.tp_name = "dealloc_obj";
+ dealloc_obj_Type.tp_basicsize = sizeof(dealloc_obj);
+ dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
+ dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+
+ if (PyType_Ready(&dealloc_obj_Type) < 0) {
+ return NULL;
+ }
+
+ dob = (dealloc_obj *)dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
+ dob->mod = bpy_proxy; /* borrow */
+ PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
+
+ return bpy_proxy;
}
static void bpy_module_free(void *UNUSED(mod))
{
- main_python_exit();
+ main_python_exit();
}
#endif
@@ -1007,36 +997,33 @@ static void bpy_module_free(void *UNUSED(mod))
*/
bool BPY_string_is_keyword(const char *str)
{
- /* list is from...
- * ", ".join(['"%s"' % kw for kw in __import__("keyword").kwlist])
- */
- const char *kwlist[] = {
- "False", "None", "True",
- "and", "as", "assert", "async", "await", "break",
- "class", "continue", "def", "del", "elif", "else", "except",
- "finally", "for", "from", "global", "if", "import", "in",
- "is", "lambda", "nonlocal", "not", "or", "pass", "raise",
- "return", "try", "while", "with", "yield", NULL,
- };
-
- for (int i = 0; kwlist[i]; i++) {
- if (STREQ(str, kwlist[i])) {
- return true;
- }
- }
-
- return false;
+ /* list is from...
+ * ", ".join(['"%s"' % kw for kw in __import__("keyword").kwlist])
+ */
+ const char *kwlist[] = {
+ "False", "None", "True", "and", "as", "assert", "async", "await", "break",
+ "class", "continue", "def", "del", "elif", "else", "except", "finally", "for",
+ "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not",
+ "or", "pass", "raise", "return", "try", "while", "with", "yield", NULL,
+ };
+
+ for (int i = 0; kwlist[i]; i++) {
+ if (STREQ(str, kwlist[i])) {
+ return true;
+ }
+ }
+
+ return false;
}
-
/* EVIL, define text.c functions here... */
/* BKE_text.h */
int text_check_identifier_unicode(const unsigned int ch)
{
- return (ch < 255 && text_check_identifier((char)ch)) || Py_UNICODE_ISALNUM(ch);
+ return (ch < 255 && text_check_identifier((char)ch)) || Py_UNICODE_ISALNUM(ch);
}
int text_check_identifier_nodigit_unicode(const unsigned int ch)
{
- return (ch < 255 && text_check_identifier_nodigit((char)ch)) || Py_UNICODE_ISALPHA(ch);
+ return (ch < 255 && text_check_identifier_nodigit((char)ch)) || Py_UNICODE_ISALPHA(ch);
}
diff --git a/source/blender/python/intern/bpy_interface_atexit.c b/source/blender/python/intern/bpy_interface_atexit.c
index a7aab0e72f4..cb79a1f7f93 100644
--- a/source/blender/python/intern/bpy_interface_atexit.c
+++ b/source/blender/python/intern/bpy_interface_atexit.c
@@ -22,24 +22,23 @@
* resources.
*/
-
#include <Python.h>
#include "BLI_utildefines.h"
#include "bpy_capi_utils.h"
-#include "bpy.h" /* own include */
+#include "bpy.h" /* own include */
#include "WM_api.h"
static PyObject *bpy_atexit(PyObject *UNUSED(self), PyObject *UNUSED(args), PyObject *UNUSED(kw))
{
- /* close down enough of blender at least not to crash */
- struct bContext *C = BPy_GetContext();
+ /* close down enough of blender at least not to crash */
+ struct bContext *C = BPy_GetContext();
- WM_exit_ext(C, 0);
+ WM_exit_ext(C, 0);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyMethodDef meth_bpy_atexit = {"bpy_atexit", (PyCFunction)bpy_atexit, METH_NOARGS, NULL};
@@ -47,45 +46,45 @@ static PyObject *func_bpy_atregister = NULL; /* borrowed referebce, atexit holds
static void atexit_func_call(const char *func_name, PyObject *atexit_func_arg)
{
- /* note - no error checking, if any of these fail we'll get a crash
- * this is intended, but if its problematic it could be changed
- * - campbell */
-
- PyObject *atexit_mod = PyImport_ImportModuleLevel("atexit", NULL, NULL, NULL, 0);
- PyObject *atexit_func = PyObject_GetAttrString(atexit_mod, func_name);
- PyObject *args = PyTuple_New(1);
- PyObject *ret;
-
- PyTuple_SET_ITEM(args, 0, atexit_func_arg);
- Py_INCREF(atexit_func_arg); /* only incref so we don't dec'ref along with 'args' */
-
- ret = PyObject_CallObject(atexit_func, args);
-
- Py_DECREF(atexit_mod);
- Py_DECREF(atexit_func);
- Py_DECREF(args);
-
- if (ret) {
- Py_DECREF(ret);
- }
- else { /* should never happen */
- PyErr_Print();
- }
+ /* note - no error checking, if any of these fail we'll get a crash
+ * this is intended, but if its problematic it could be changed
+ * - campbell */
+
+ PyObject *atexit_mod = PyImport_ImportModuleLevel("atexit", NULL, NULL, NULL, 0);
+ PyObject *atexit_func = PyObject_GetAttrString(atexit_mod, func_name);
+ PyObject *args = PyTuple_New(1);
+ PyObject *ret;
+
+ PyTuple_SET_ITEM(args, 0, atexit_func_arg);
+ Py_INCREF(atexit_func_arg); /* only incref so we don't dec'ref along with 'args' */
+
+ ret = PyObject_CallObject(atexit_func, args);
+
+ Py_DECREF(atexit_mod);
+ Py_DECREF(atexit_func);
+ Py_DECREF(args);
+
+ if (ret) {
+ Py_DECREF(ret);
+ }
+ else { /* should never happen */
+ PyErr_Print();
+ }
}
void BPY_atexit_register(void)
{
- /* atexit module owns this new function reference */
- BLI_assert(func_bpy_atregister == NULL);
+ /* atexit module owns this new function reference */
+ BLI_assert(func_bpy_atregister == NULL);
- func_bpy_atregister = (PyObject *)PyCFunction_New(&meth_bpy_atexit, NULL);
- atexit_func_call("register", func_bpy_atregister);
+ func_bpy_atregister = (PyObject *)PyCFunction_New(&meth_bpy_atexit, NULL);
+ atexit_func_call("register", func_bpy_atregister);
}
void BPY_atexit_unregister(void)
{
- BLI_assert(func_bpy_atregister != NULL);
+ BLI_assert(func_bpy_atregister != NULL);
- atexit_func_call("unregister", func_bpy_atregister);
- func_bpy_atregister = NULL; /* don't really need to set but just in case */
+ atexit_func_call("unregister", func_bpy_atregister);
+ func_bpy_atregister = NULL; /* don't really need to set but just in case */
}
diff --git a/source/blender/python/intern/bpy_intern_string.c b/source/blender/python/intern/bpy_intern_string.c
index 334aa49c0bf..141f03c22aa 100644
--- a/source/blender/python/intern/bpy_intern_string.c
+++ b/source/blender/python/intern/bpy_intern_string.c
@@ -49,37 +49,40 @@ PyObject *bpy_intern_str_unregister;
void bpy_intern_string_init(void)
{
- unsigned int i = 0;
+ unsigned int i = 0;
#define BPY_INTERN_STR(var, str) \
- { var = bpy_intern_str_arr[i++] = PyUnicode_FromString(str); } (void)0
+ { \
+ var = bpy_intern_str_arr[i++] = PyUnicode_FromString(str); \
+ } \
+ (void)0
- BPY_INTERN_STR(bpy_intern_str___annotations__, "__annotations__");
- BPY_INTERN_STR(bpy_intern_str___doc__, "__doc__");
- BPY_INTERN_STR(bpy_intern_str___main__, "__main__");
- BPY_INTERN_STR(bpy_intern_str___module__, "__module__");
- BPY_INTERN_STR(bpy_intern_str___name__, "__name__");
- BPY_INTERN_STR(bpy_intern_str___slots__, "__slots__");
- BPY_INTERN_STR(bpy_intern_str_attr, "attr");
- BPY_INTERN_STR(bpy_intern_str_bl_property, "bl_property");
- BPY_INTERN_STR(bpy_intern_str_bl_rna, "bl_rna");
- BPY_INTERN_STR(bpy_intern_str_bl_target_properties, "bl_target_properties");
- BPY_INTERN_STR(bpy_intern_str_bpy_types, "bpy.types");
- BPY_INTERN_STR(bpy_intern_str_frame, "frame");
- BPY_INTERN_STR(bpy_intern_str_properties, "properties");
- BPY_INTERN_STR(bpy_intern_str_register, "register");
- BPY_INTERN_STR(bpy_intern_str_self, "self");
- BPY_INTERN_STR(bpy_intern_str_unregister, "unregister");
+ BPY_INTERN_STR(bpy_intern_str___annotations__, "__annotations__");
+ BPY_INTERN_STR(bpy_intern_str___doc__, "__doc__");
+ BPY_INTERN_STR(bpy_intern_str___main__, "__main__");
+ BPY_INTERN_STR(bpy_intern_str___module__, "__module__");
+ BPY_INTERN_STR(bpy_intern_str___name__, "__name__");
+ BPY_INTERN_STR(bpy_intern_str___slots__, "__slots__");
+ BPY_INTERN_STR(bpy_intern_str_attr, "attr");
+ BPY_INTERN_STR(bpy_intern_str_bl_property, "bl_property");
+ BPY_INTERN_STR(bpy_intern_str_bl_rna, "bl_rna");
+ BPY_INTERN_STR(bpy_intern_str_bl_target_properties, "bl_target_properties");
+ BPY_INTERN_STR(bpy_intern_str_bpy_types, "bpy.types");
+ BPY_INTERN_STR(bpy_intern_str_frame, "frame");
+ BPY_INTERN_STR(bpy_intern_str_properties, "properties");
+ BPY_INTERN_STR(bpy_intern_str_register, "register");
+ BPY_INTERN_STR(bpy_intern_str_self, "self");
+ BPY_INTERN_STR(bpy_intern_str_unregister, "unregister");
#undef BPY_INTERN_STR
- BLI_assert(i == ARRAY_SIZE(bpy_intern_str_arr));
+ BLI_assert(i == ARRAY_SIZE(bpy_intern_str_arr));
}
void bpy_intern_string_exit(void)
{
- unsigned int i = ARRAY_SIZE(bpy_intern_str_arr);
- while (i--) {
- Py_DECREF(bpy_intern_str_arr[i]);
- }
+ unsigned int i = ARRAY_SIZE(bpy_intern_str_arr);
+ while (i--) {
+ Py_DECREF(bpy_intern_str_arr[i]);
+ }
}
diff --git a/source/blender/python/intern/bpy_intern_string.h b/source/blender/python/intern/bpy_intern_string.h
index 362a07904e0..14f9607f3b4 100644
--- a/source/blender/python/intern/bpy_intern_string.h
+++ b/source/blender/python/intern/bpy_intern_string.h
@@ -41,4 +41,4 @@ extern PyObject *bpy_intern_str_register;
extern PyObject *bpy_intern_str_self;
extern PyObject *bpy_intern_str_unregister;
-#endif /* __BPY_INTERN_STRING_H__ */
+#endif /* __BPY_INTERN_STRING_H__ */
diff --git a/source/blender/python/intern/bpy_library.h b/source/blender/python/intern/bpy_library.h
index 7537eb40d19..3fd116d7028 100644
--- a/source/blender/python/intern/bpy_library.h
+++ b/source/blender/python/intern/bpy_library.h
@@ -24,4 +24,4 @@
int BPY_library_load_module(PyObject *mod_par);
int BPY_library_write_module(PyObject *mod_par);
-#endif /* __BPY_LIBRARY_H__ */
+#endif /* __BPY_LIBRARY_H__ */
diff --git a/source/blender/python/intern/bpy_library_load.c b/source/blender/python/intern/bpy_library_load.c
index 3a4c70c1873..3de8e49dffd 100644
--- a/source/blender/python/intern/bpy_library_load.c
+++ b/source/blender/python/intern/bpy_library_load.c
@@ -59,13 +59,13 @@
#endif
typedef struct {
- PyObject_HEAD /* required python macro */
- /* collection iterator specific parts */
- char relpath[FILE_MAX];
- char abspath[FILE_MAX]; /* absolute path */
- BlendHandle *blo_handle;
- int flag;
- PyObject *dict;
+ PyObject_HEAD /* required python macro */
+ /* collection iterator specific parts */
+ char relpath[FILE_MAX];
+ char abspath[FILE_MAX]; /* absolute path */
+ BlendHandle *blo_handle;
+ int flag;
+ PyObject *dict;
} BPy_Library;
static PyObject *bpy_lib_load(PyObject *self, PyObject *args, PyObject *kwds);
@@ -74,411 +74,407 @@ static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *args);
static PyObject *bpy_lib_dir(BPy_Library *self);
static PyMethodDef bpy_lib_methods[] = {
- {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
- {"__exit__", (PyCFunction)bpy_lib_exit, METH_VARARGS},
- {"__dir__", (PyCFunction)bpy_lib_dir, METH_NOARGS},
- {NULL} /* sentinel */
+ {"__enter__", (PyCFunction)bpy_lib_enter, METH_NOARGS},
+ {"__exit__", (PyCFunction)bpy_lib_exit, METH_VARARGS},
+ {"__dir__", (PyCFunction)bpy_lib_dir, METH_NOARGS},
+ {NULL} /* sentinel */
};
static void bpy_lib_dealloc(BPy_Library *self)
{
- Py_XDECREF(self->dict);
- Py_TYPE(self)->tp_free(self);
+ Py_XDECREF(self->dict);
+ Py_TYPE(self)->tp_free(self);
}
-
static PyTypeObject bpy_lib_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_lib", /* tp_name */
- sizeof(BPy_Library), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)bpy_lib_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
- NULL /*PyObject_GenericGetAttr is assigned later */, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0,
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- bpy_lib_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- offsetof(BPy_Library, dict), /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_lib", /* tp_name */
+ sizeof(BPy_Library), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)bpy_lib_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL, /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+ /* will only use these if this is a subtype of a py class */
+ NULL /*PyObject_GenericGetAttr is assigned later */, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ bpy_lib_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ offsetof(BPy_Library, dict), /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
-PyDoc_STRVAR(bpy_lib_load_doc,
-".. method:: load(filepath, link=False, relative=False)\n"
-"\n"
-" Returns a context manager which exposes 2 library objects on entering.\n"
-" Each object has attributes matching bpy.data which are lists of strings to be linked.\n"
-"\n"
-" :arg filepath: The path to a blend file.\n"
-" :type filepath: string\n"
-" :arg link: When False reference to the original file is lost.\n"
-" :type link: bool\n"
-" :arg relative: When True the path is stored relative to the open blend file.\n"
-" :type relative: bool\n"
-);
+PyDoc_STRVAR(
+ bpy_lib_load_doc,
+ ".. method:: load(filepath, link=False, relative=False)\n"
+ "\n"
+ " Returns a context manager which exposes 2 library objects on entering.\n"
+ " Each object has attributes matching bpy.data which are lists of strings to be linked.\n"
+ "\n"
+ " :arg filepath: The path to a blend file.\n"
+ " :type filepath: string\n"
+ " :arg link: When False reference to the original file is lost.\n"
+ " :type link: bool\n"
+ " :arg relative: When True the path is stored relative to the open blend file.\n"
+ " :type relative: bool\n");
static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- Main *bmain = CTX_data_main(BPy_GetContext());
- BPy_Library *ret;
- const char *filename = NULL;
- bool is_rel = false, is_link = false;
-
- static const char *_keywords[] = {"filepath", "link", "relative", NULL};
- static _PyArg_Parser _parser = {"s|O&O&:load", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &filename,
- PyC_ParseBool, &is_link,
- PyC_ParseBool, &is_rel))
- {
- return NULL;
- }
-
- ret = PyObject_New(BPy_Library, &bpy_lib_Type);
-
- BLI_strncpy(ret->relpath, filename, sizeof(ret->relpath));
- BLI_strncpy(ret->abspath, filename, sizeof(ret->abspath));
- BLI_path_abs(ret->abspath, BKE_main_blendfile_path(bmain));
-
- ret->blo_handle = NULL;
- ret->flag = ((is_link ? FILE_LINK : 0) |
- (is_rel ? FILE_RELPATH : 0));
-
- ret->dict = _PyDict_NewPresized(MAX_LIBARRAY);
-
- return (PyObject *)ret;
+ Main *bmain = CTX_data_main(BPy_GetContext());
+ BPy_Library *ret;
+ const char *filename = NULL;
+ bool is_rel = false, is_link = false;
+
+ static const char *_keywords[] = {"filepath", "link", "relative", NULL};
+ static _PyArg_Parser _parser = {"s|O&O&:load", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &filename, PyC_ParseBool, &is_link, PyC_ParseBool, &is_rel)) {
+ return NULL;
+ }
+
+ ret = PyObject_New(BPy_Library, &bpy_lib_Type);
+
+ BLI_strncpy(ret->relpath, filename, sizeof(ret->relpath));
+ BLI_strncpy(ret->abspath, filename, sizeof(ret->abspath));
+ BLI_path_abs(ret->abspath, BKE_main_blendfile_path(bmain));
+
+ ret->blo_handle = NULL;
+ ret->flag = ((is_link ? FILE_LINK : 0) | (is_rel ? FILE_RELPATH : 0));
+
+ ret->dict = _PyDict_NewPresized(MAX_LIBARRAY);
+
+ return (PyObject *)ret;
}
static PyObject *_bpy_names(BPy_Library *self, int blocktype)
{
- PyObject *list;
- LinkNode *l, *names;
- int totnames;
-
- names = BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
- list = PyList_New(totnames);
-
- if (names) {
- int counter = 0;
- for (l = names; l; l = l->next) {
- PyList_SET_ITEM(list, counter, PyUnicode_FromString((char *)l->link));
- counter++;
- }
- BLI_linklist_free(names, free); /* free linklist *and* each node's data */
- }
-
- return list;
+ PyObject *list;
+ LinkNode *l, *names;
+ int totnames;
+
+ names = BLO_blendhandle_get_datablock_names(self->blo_handle, blocktype, &totnames);
+ list = PyList_New(totnames);
+
+ if (names) {
+ int counter = 0;
+ for (l = names; l; l = l->next) {
+ PyList_SET_ITEM(list, counter, PyUnicode_FromString((char *)l->link));
+ counter++;
+ }
+ BLI_linklist_free(names, free); /* free linklist *and* each node's data */
+ }
+
+ return list;
}
static PyObject *bpy_lib_enter(BPy_Library *self)
{
- PyObject *ret;
- BPy_Library *self_from;
- PyObject *from_dict = _PyDict_NewPresized(MAX_LIBARRAY);
- ReportList reports;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- self->blo_handle = BLO_blendhandle_from_file(self->abspath, &reports);
-
- if (self->blo_handle == NULL) {
- if (BPy_reports_to_error(&reports, PyExc_IOError, true) != -1) {
- PyErr_Format(PyExc_IOError,
- "load: %s failed to open blend file",
- self->abspath);
- }
- return NULL;
- }
- else {
- int i = 0, code;
- while ((code = BKE_idcode_iter_step(&i))) {
- if (BKE_idcode_is_linkable(code)) {
- const char *name_plural = BKE_idcode_to_name_plural(code);
- PyObject *str = PyUnicode_FromString(name_plural);
- PyObject *item;
-
- PyDict_SetItem(self->dict, str, item = PyList_New(0));
- Py_DECREF(item);
- PyDict_SetItem(from_dict, str, item = _bpy_names(self, code));
- Py_DECREF(item);
-
- Py_DECREF(str);
- }
- }
- }
-
- /* create a dummy */
- self_from = PyObject_New(BPy_Library, &bpy_lib_Type);
- BLI_strncpy(self_from->relpath, self->relpath, sizeof(self_from->relpath));
- BLI_strncpy(self_from->abspath, self->abspath, sizeof(self_from->abspath));
-
- self_from->blo_handle = NULL;
- self_from->flag = 0;
- self_from->dict = from_dict; /* owns the dict */
-
- /* return pair */
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- (PyObject *)self_from,
- (PyObject *)self);
- Py_INCREF(self);
-
- BKE_reports_clear(&reports);
-
- return ret;
+ PyObject *ret;
+ BPy_Library *self_from;
+ PyObject *from_dict = _PyDict_NewPresized(MAX_LIBARRAY);
+ ReportList reports;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ self->blo_handle = BLO_blendhandle_from_file(self->abspath, &reports);
+
+ if (self->blo_handle == NULL) {
+ if (BPy_reports_to_error(&reports, PyExc_IOError, true) != -1) {
+ PyErr_Format(PyExc_IOError, "load: %s failed to open blend file", self->abspath);
+ }
+ return NULL;
+ }
+ else {
+ int i = 0, code;
+ while ((code = BKE_idcode_iter_step(&i))) {
+ if (BKE_idcode_is_linkable(code)) {
+ const char *name_plural = BKE_idcode_to_name_plural(code);
+ PyObject *str = PyUnicode_FromString(name_plural);
+ PyObject *item;
+
+ PyDict_SetItem(self->dict, str, item = PyList_New(0));
+ Py_DECREF(item);
+ PyDict_SetItem(from_dict, str, item = _bpy_names(self, code));
+ Py_DECREF(item);
+
+ Py_DECREF(str);
+ }
+ }
+ }
+
+ /* create a dummy */
+ self_from = PyObject_New(BPy_Library, &bpy_lib_Type);
+ BLI_strncpy(self_from->relpath, self->relpath, sizeof(self_from->relpath));
+ BLI_strncpy(self_from->abspath, self->abspath, sizeof(self_from->abspath));
+
+ self_from->blo_handle = NULL;
+ self_from->flag = 0;
+ self_from->dict = from_dict; /* owns the dict */
+
+ /* return pair */
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, (PyObject *)self_from, (PyObject *)self);
+ Py_INCREF(self);
+
+ BKE_reports_clear(&reports);
+
+ return ret;
}
-static void bpy_lib_exit_warn_idname(BPy_Library *self, const char *name_plural, const char *idname)
+static void bpy_lib_exit_warn_idname(BPy_Library *self,
+ const char *name_plural,
+ const char *idname)
{
- PyObject *exc, *val, *tb;
- PyErr_Fetch(&exc, &val, &tb);
- if (PyErr_WarnFormat(PyExc_UserWarning, 1,
- "load: '%s' does not contain %s[\"%s\"]",
- self->abspath, name_plural, idname))
- {
- /* Spurious errors can appear at shutdown */
- if (PyErr_ExceptionMatches(PyExc_Warning)) {
- PyErr_WriteUnraisable((PyObject *)self);
- }
- }
- PyErr_Restore(exc, val, tb);
+ PyObject *exc, *val, *tb;
+ PyErr_Fetch(&exc, &val, &tb);
+ if (PyErr_WarnFormat(PyExc_UserWarning,
+ 1,
+ "load: '%s' does not contain %s[\"%s\"]",
+ self->abspath,
+ name_plural,
+ idname)) {
+ /* Spurious errors can appear at shutdown */
+ if (PyErr_ExceptionMatches(PyExc_Warning)) {
+ PyErr_WriteUnraisable((PyObject *)self);
+ }
+ }
+ PyErr_Restore(exc, val, tb);
}
static void bpy_lib_exit_warn_type(BPy_Library *self, PyObject *item)
{
- PyObject *exc, *val, *tb;
- PyErr_Fetch(&exc, &val, &tb);
- if (PyErr_WarnFormat(PyExc_UserWarning, 1,
- "load: '%s' expected a string type, not a %.200s",
- self->abspath, Py_TYPE(item)->tp_name))
- {
- /* Spurious errors can appear at shutdown */
- if (PyErr_ExceptionMatches(PyExc_Warning)) {
- PyErr_WriteUnraisable((PyObject *)self);
- }
- }
- PyErr_Restore(exc, val, tb);
+ PyObject *exc, *val, *tb;
+ PyErr_Fetch(&exc, &val, &tb);
+ if (PyErr_WarnFormat(PyExc_UserWarning,
+ 1,
+ "load: '%s' expected a string type, not a %.200s",
+ self->abspath,
+ Py_TYPE(item)->tp_name)) {
+ /* Spurious errors can appear at shutdown */
+ if (PyErr_ExceptionMatches(PyExc_Warning)) {
+ PyErr_WriteUnraisable((PyObject *)self);
+ }
+ }
+ PyErr_Restore(exc, val, tb);
}
static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
{
- Main *bmain = CTX_data_main(BPy_GetContext());
- Main *mainl = NULL;
- int err = 0;
- const bool do_append = ((self->flag & FILE_LINK) == 0);
-
- BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
-
- /* here appending/linking starts */
- mainl = BLO_library_link_begin(bmain, &(self->blo_handle), self->relpath);
-
- {
- int idcode_step = 0, idcode;
- while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
- if (BKE_idcode_is_linkable(idcode) && (idcode != ID_WS || do_append)) {
- const char *name_plural = BKE_idcode_to_name_plural(idcode);
- PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
- // printf("lib: %s\n", name_plural);
- if (ls && PyList_Check(ls)) {
- /* loop */
- Py_ssize_t size = PyList_GET_SIZE(ls);
- Py_ssize_t i;
-
- for (i = 0; i < size; i++) {
- PyObject *item_src = PyList_GET_ITEM(ls, i);
- PyObject *item_dst; /* must be set below */
- const char *item_idname = _PyUnicode_AsString(item_src);
-
- // printf(" %s\n", item_idname);
-
- if (item_idname) {
- ID *id = BLO_library_link_named_part(mainl, &(self->blo_handle), idcode, item_idname);
- if (id) {
+ Main *bmain = CTX_data_main(BPy_GetContext());
+ Main *mainl = NULL;
+ int err = 0;
+ const bool do_append = ((self->flag & FILE_LINK) == 0);
+
+ BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
+
+ /* here appending/linking starts */
+ mainl = BLO_library_link_begin(bmain, &(self->blo_handle), self->relpath);
+
+ {
+ int idcode_step = 0, idcode;
+ while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
+ if (BKE_idcode_is_linkable(idcode) && (idcode != ID_WS || do_append)) {
+ const char *name_plural = BKE_idcode_to_name_plural(idcode);
+ PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
+ // printf("lib: %s\n", name_plural);
+ if (ls && PyList_Check(ls)) {
+ /* loop */
+ Py_ssize_t size = PyList_GET_SIZE(ls);
+ Py_ssize_t i;
+
+ for (i = 0; i < size; i++) {
+ PyObject *item_src = PyList_GET_ITEM(ls, i);
+ PyObject *item_dst; /* must be set below */
+ const char *item_idname = _PyUnicode_AsString(item_src);
+
+ // printf(" %s\n", item_idname);
+
+ if (item_idname) {
+ ID *id = BLO_library_link_named_part(
+ mainl, &(self->blo_handle), idcode, item_idname);
+ if (id) {
#ifdef USE_RNA_DATABLOCKS
- /* swap name for pointer to the id */
- item_dst = PyCapsule_New((void *)id, NULL, NULL);
+ /* swap name for pointer to the id */
+ item_dst = PyCapsule_New((void *)id, NULL, NULL);
#else
- /* leave as is */
- continue;
+ /* leave as is */
+ continue;
#endif
- }
- else {
- bpy_lib_exit_warn_idname(self, name_plural, item_idname);
- /* just warn for now */
- /* err = -1; */
- item_dst = Py_INCREF_RET(Py_None);
- }
-
- /* ID or None */
- }
- else {
- /* XXX, could complain about this */
- bpy_lib_exit_warn_type(self, item_src);
- PyErr_Clear();
- item_dst = Py_INCREF_RET(Py_None);
- }
-
- /* item_dst must be new or already incref'd */
- Py_DECREF(item_src);
- PyList_SET_ITEM(ls, i, item_dst);
- }
- }
- }
- }
- }
-
- if (err == -1) {
- /* exception raised above, XXX, this leaks some memory */
- BLO_blendhandle_close(self->blo_handle);
- self->blo_handle = NULL;
- BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
- return NULL;
- }
- else {
- Library *lib = mainl->curlib; /* newly added lib, assign before append end */
- BLO_library_link_end(mainl, &(self->blo_handle), self->flag, NULL, NULL, NULL, NULL);
- BLO_blendhandle_close(self->blo_handle);
- self->blo_handle = NULL;
-
- GHash *old_to_new_ids = BLI_ghash_ptr_new(__func__);
-
- /* copied from wm_operator.c */
- {
- /* mark all library linked objects to be updated */
- BKE_main_lib_objects_recalc_all(bmain);
-
- /* append, rather than linking */
- if (do_append) {
- BKE_library_make_local(bmain, lib, old_to_new_ids, true, false);
- }
- }
-
- BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
-
- /* finally swap the capsules for real bpy objects
- * important since BLO_library_append_end initializes NodeTree types used by srna->refine */
+ }
+ else {
+ bpy_lib_exit_warn_idname(self, name_plural, item_idname);
+ /* just warn for now */
+ /* err = -1; */
+ item_dst = Py_INCREF_RET(Py_None);
+ }
+
+ /* ID or None */
+ }
+ else {
+ /* XXX, could complain about this */
+ bpy_lib_exit_warn_type(self, item_src);
+ PyErr_Clear();
+ item_dst = Py_INCREF_RET(Py_None);
+ }
+
+ /* item_dst must be new or already incref'd */
+ Py_DECREF(item_src);
+ PyList_SET_ITEM(ls, i, item_dst);
+ }
+ }
+ }
+ }
+ }
+
+ if (err == -1) {
+ /* exception raised above, XXX, this leaks some memory */
+ BLO_blendhandle_close(self->blo_handle);
+ self->blo_handle = NULL;
+ BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
+ return NULL;
+ }
+ else {
+ Library *lib = mainl->curlib; /* newly added lib, assign before append end */
+ BLO_library_link_end(mainl, &(self->blo_handle), self->flag, NULL, NULL, NULL, NULL);
+ BLO_blendhandle_close(self->blo_handle);
+ self->blo_handle = NULL;
+
+ GHash *old_to_new_ids = BLI_ghash_ptr_new(__func__);
+
+ /* copied from wm_operator.c */
+ {
+ /* mark all library linked objects to be updated */
+ BKE_main_lib_objects_recalc_all(bmain);
+
+ /* append, rather than linking */
+ if (do_append) {
+ BKE_library_make_local(bmain, lib, old_to_new_ids, true, false);
+ }
+ }
+
+ BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
+
+ /* finally swap the capsules for real bpy objects
+ * important since BLO_library_append_end initializes NodeTree types used by srna->refine */
#ifdef USE_RNA_DATABLOCKS
- {
- int idcode_step = 0, idcode;
- while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
- if (BKE_idcode_is_linkable(idcode) && (idcode != ID_WS || do_append)) {
- const char *name_plural = BKE_idcode_to_name_plural(idcode);
- PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
- if (ls && PyList_Check(ls)) {
- Py_ssize_t size = PyList_GET_SIZE(ls);
- Py_ssize_t i;
- PyObject *item;
-
- for (i = 0; i < size; i++) {
- item = PyList_GET_ITEM(ls, i);
- if (PyCapsule_CheckExact(item)) {
- PointerRNA id_ptr;
- ID *id;
-
- id = PyCapsule_GetPointer(item, NULL);
- id = BLI_ghash_lookup_default(old_to_new_ids, id, id);
- Py_DECREF(item);
-
- RNA_id_pointer_create(id, &id_ptr);
- item = pyrna_struct_CreatePyObject(&id_ptr);
- PyList_SET_ITEM(ls, i, item);
- }
- }
- }
- }
- }
- }
-#endif /* USE_RNA_DATABLOCKS */
-
- BLI_ghash_free(old_to_new_ids, NULL, NULL);
- Py_RETURN_NONE;
- }
+ {
+ int idcode_step = 0, idcode;
+ while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
+ if (BKE_idcode_is_linkable(idcode) && (idcode != ID_WS || do_append)) {
+ const char *name_plural = BKE_idcode_to_name_plural(idcode);
+ PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
+ if (ls && PyList_Check(ls)) {
+ Py_ssize_t size = PyList_GET_SIZE(ls);
+ Py_ssize_t i;
+ PyObject *item;
+
+ for (i = 0; i < size; i++) {
+ item = PyList_GET_ITEM(ls, i);
+ if (PyCapsule_CheckExact(item)) {
+ PointerRNA id_ptr;
+ ID *id;
+
+ id = PyCapsule_GetPointer(item, NULL);
+ id = BLI_ghash_lookup_default(old_to_new_ids, id, id);
+ Py_DECREF(item);
+
+ RNA_id_pointer_create(id, &id_ptr);
+ item = pyrna_struct_CreatePyObject(&id_ptr);
+ PyList_SET_ITEM(ls, i, item);
+ }
+ }
+ }
+ }
+ }
+ }
+#endif /* USE_RNA_DATABLOCKS */
+
+ BLI_ghash_free(old_to_new_ids, NULL, NULL);
+ Py_RETURN_NONE;
+ }
}
static PyObject *bpy_lib_dir(BPy_Library *self)
{
- return PyDict_Keys(self->dict);
+ return PyDict_Keys(self->dict);
}
-
int BPY_library_load_module(PyObject *mod_par)
{
- static PyMethodDef load_meth = {
- "load", (PyCFunction)bpy_lib_load,
- METH_STATIC | METH_VARARGS | METH_KEYWORDS,
- bpy_lib_load_doc,
- };
- PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
-
- /* some compilers don't like accessing this directly, delay assignment */
- bpy_lib_Type.tp_getattro = PyObject_GenericGetAttr;
-
- if (PyType_Ready(&bpy_lib_Type) < 0) {
- return -1;
- }
-
- return 0;
+ static PyMethodDef load_meth = {
+ "load",
+ (PyCFunction)bpy_lib_load,
+ METH_STATIC | METH_VARARGS | METH_KEYWORDS,
+ bpy_lib_load_doc,
+ };
+ PyModule_AddObject(mod_par, "_library_load", PyCFunction_New(&load_meth, NULL));
+
+ /* some compilers don't like accessing this directly, delay assignment */
+ bpy_lib_Type.tp_getattro = PyObject_GenericGetAttr;
+
+ if (PyType_Ready(&bpy_lib_Type) < 0) {
+ return -1;
+ }
+
+ return 0;
}
diff --git a/source/blender/python/intern/bpy_library_write.c b/source/blender/python/intern/bpy_library_write.c
index 7b7457bc4b3..a1894b7f000 100644
--- a/source/blender/python/intern/bpy_library_write.c
+++ b/source/blender/python/intern/bpy_library_write.c
@@ -43,174 +43,177 @@
#include "../generic/py_capi_utils.h"
-
-PyDoc_STRVAR(bpy_lib_write_doc,
-".. method:: write(filepath, datablocks, relative_remap=False, fake_user=False, compress=False)\n"
-"\n"
-" Write data-blocks into a blend file.\n"
-"\n"
-" .. note::\n"
-"\n"
-" Indirectly referenced data-blocks will be expanded and written too.\n"
-"\n"
-" :arg filepath: The path to write the blend-file.\n"
-" :type filepath: string\n"
-" :arg datablocks: set of data-blocks (:class:`bpy.types.ID` instances).\n"
-" :type datablocks: set\n"
-" :arg relative_remap: When True, make paths relative to the current blend-file.\n"
-" :type relative_remap: bool\n"
-" :arg fake_user: When True, data-blocks will be written with fake-user flag enabled.\n"
-" :type fake_user: bool\n"
-" :arg compress: When True, write a compressed blend file.\n"
-" :type compress: bool\n"
-);
+PyDoc_STRVAR(
+ bpy_lib_write_doc,
+ ".. method:: write(filepath, datablocks, relative_remap=False, fake_user=False, "
+ "compress=False)\n"
+ "\n"
+ " Write data-blocks into a blend file.\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " Indirectly referenced data-blocks will be expanded and written too.\n"
+ "\n"
+ " :arg filepath: The path to write the blend-file.\n"
+ " :type filepath: string\n"
+ " :arg datablocks: set of data-blocks (:class:`bpy.types.ID` instances).\n"
+ " :type datablocks: set\n"
+ " :arg relative_remap: When True, make paths relative to the current blend-file.\n"
+ " :type relative_remap: bool\n"
+ " :arg fake_user: When True, data-blocks will be written with fake-user flag enabled.\n"
+ " :type fake_user: bool\n"
+ " :arg compress: When True, write a compressed blend file.\n"
+ " :type compress: bool\n");
static PyObject *bpy_lib_write(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- /* args */
- const char *filepath;
- char filepath_abs[FILE_MAX];
- PyObject *datablocks = NULL;
- bool use_relative_remap = false, use_fake_user = false, use_compress = false;
-
- static const char *_keywords[] = {
- "filepath", "datablocks",
- /* optional */
- "relative_remap", "fake_user", "compress",
- NULL,
- };
- static _PyArg_Parser _parser = {"sO!|$O&O&O&:write", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &filepath,
- &PySet_Type, &datablocks,
- PyC_ParseBool, &use_relative_remap,
- PyC_ParseBool, &use_fake_user,
- PyC_ParseBool, &use_compress))
- {
- return NULL;
- }
-
- Main *bmain_src = G_MAIN;
- int write_flags = 0;
-
- if (use_relative_remap) {
- write_flags |= G_FILE_RELATIVE_REMAP;
- }
-
- if (use_compress) {
- write_flags |= G_FILE_COMPRESS;
- }
-
- BLI_strncpy(filepath_abs, filepath, FILE_MAX);
- BLI_path_abs(filepath_abs, BKE_main_blendfile_path_from_global());
-
- BKE_blendfile_write_partial_begin(bmain_src);
-
- /* array of ID's and backup any data we modify */
- struct {
- ID *id;
- /* original values */
- short id_flag;
- short id_us;
- } *id_store_array, *id_store;
- int id_store_len = 0;
-
- PyObject *ret;
-
- /* collect all id data from the set and store in 'id_store_array' */
- {
- Py_ssize_t pos, hash;
- PyObject *key;
-
- id_store_array = MEM_mallocN(sizeof(*id_store_array) * PySet_Size(datablocks), __func__);
- id_store = id_store_array;
-
- pos = hash = 0;
- while (_PySet_NextEntry(datablocks, &pos, &key, &hash)) {
-
- if (!pyrna_id_FromPyObject(key, &id_store->id)) {
- PyErr_Format(PyExc_TypeError,
- "Expected an ID type, not %.200s",
- Py_TYPE(key)->tp_name);
- ret = NULL;
- goto finally;
- }
- else {
- id_store->id_flag = id_store->id->flag;
- id_store->id_us = id_store->id->us;
-
- if (use_fake_user) {
- id_store->id->flag |= LIB_FAKEUSER;
- }
- id_store->id->us = 1;
-
- BKE_blendfile_write_partial_tag_ID(id_store->id, true);
-
- id_store_len += 1;
- id_store++;
- }
- }
- }
-
- /* write blend */
- int retval = 0;
- ReportList reports;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- retval = BKE_blendfile_write_partial(bmain_src, filepath_abs, write_flags, &reports);
-
- /* cleanup state */
- BKE_blendfile_write_partial_end(bmain_src);
-
- if (retval) {
- BKE_reports_print(&reports, RPT_ERROR_ALL);
- BKE_reports_clear(&reports);
- ret = Py_None;
- Py_INCREF(ret);
- }
- else {
- if (BPy_reports_to_error(&reports, PyExc_IOError, true) == 0) {
- PyErr_SetString(PyExc_IOError, "Unknown error writing library data");
- }
- ret = NULL;
- }
-
+ /* args */
+ const char *filepath;
+ char filepath_abs[FILE_MAX];
+ PyObject *datablocks = NULL;
+ bool use_relative_remap = false, use_fake_user = false, use_compress = false;
+
+ static const char *_keywords[] = {
+ "filepath",
+ "datablocks",
+ /* optional */
+ "relative_remap",
+ "fake_user",
+ "compress",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"sO!|$O&O&O&:write", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &filepath,
+ &PySet_Type,
+ &datablocks,
+ PyC_ParseBool,
+ &use_relative_remap,
+ PyC_ParseBool,
+ &use_fake_user,
+ PyC_ParseBool,
+ &use_compress)) {
+ return NULL;
+ }
+
+ Main *bmain_src = G_MAIN;
+ int write_flags = 0;
+
+ if (use_relative_remap) {
+ write_flags |= G_FILE_RELATIVE_REMAP;
+ }
+
+ if (use_compress) {
+ write_flags |= G_FILE_COMPRESS;
+ }
+
+ BLI_strncpy(filepath_abs, filepath, FILE_MAX);
+ BLI_path_abs(filepath_abs, BKE_main_blendfile_path_from_global());
+
+ BKE_blendfile_write_partial_begin(bmain_src);
+
+ /* array of ID's and backup any data we modify */
+ struct {
+ ID *id;
+ /* original values */
+ short id_flag;
+ short id_us;
+ } * id_store_array, *id_store;
+ int id_store_len = 0;
+
+ PyObject *ret;
+
+ /* collect all id data from the set and store in 'id_store_array' */
+ {
+ Py_ssize_t pos, hash;
+ PyObject *key;
+
+ id_store_array = MEM_mallocN(sizeof(*id_store_array) * PySet_Size(datablocks), __func__);
+ id_store = id_store_array;
+
+ pos = hash = 0;
+ while (_PySet_NextEntry(datablocks, &pos, &key, &hash)) {
+
+ if (!pyrna_id_FromPyObject(key, &id_store->id)) {
+ PyErr_Format(PyExc_TypeError, "Expected an ID type, not %.200s", Py_TYPE(key)->tp_name);
+ ret = NULL;
+ goto finally;
+ }
+ else {
+ id_store->id_flag = id_store->id->flag;
+ id_store->id_us = id_store->id->us;
+
+ if (use_fake_user) {
+ id_store->id->flag |= LIB_FAKEUSER;
+ }
+ id_store->id->us = 1;
+
+ BKE_blendfile_write_partial_tag_ID(id_store->id, true);
+
+ id_store_len += 1;
+ id_store++;
+ }
+ }
+ }
+
+ /* write blend */
+ int retval = 0;
+ ReportList reports;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ retval = BKE_blendfile_write_partial(bmain_src, filepath_abs, write_flags, &reports);
+
+ /* cleanup state */
+ BKE_blendfile_write_partial_end(bmain_src);
+
+ if (retval) {
+ BKE_reports_print(&reports, RPT_ERROR_ALL);
+ BKE_reports_clear(&reports);
+ ret = Py_None;
+ Py_INCREF(ret);
+ }
+ else {
+ if (BPy_reports_to_error(&reports, PyExc_IOError, true) == 0) {
+ PyErr_SetString(PyExc_IOError, "Unknown error writing library data");
+ }
+ ret = NULL;
+ }
finally:
- /* clear all flags for ID's added to the store (may run on error too) */
- id_store = id_store_array;
+ /* clear all flags for ID's added to the store (may run on error too) */
+ id_store = id_store_array;
- for (int i = 0; i < id_store_len; id_store++, i++) {
+ for (int i = 0; i < id_store_len; id_store++, i++) {
+ if (use_fake_user) {
+ if ((id_store->id_flag & LIB_FAKEUSER) == 0) {
+ id_store->id->flag &= ~LIB_FAKEUSER;
+ }
+ }
- if (use_fake_user) {
- if ((id_store->id_flag & LIB_FAKEUSER) == 0) {
- id_store->id->flag &= ~LIB_FAKEUSER;
- }
- }
+ id_store->id->us = id_store->id_us;
- id_store->id->us = id_store->id_us;
+ BKE_blendfile_write_partial_tag_ID(id_store->id, false);
+ }
- BKE_blendfile_write_partial_tag_ID(id_store->id, false);
- }
+ MEM_freeN(id_store_array);
- MEM_freeN(id_store_array);
-
- return ret;
+ return ret;
}
-
int BPY_library_write_module(PyObject *mod_par)
{
- static PyMethodDef write_meth = {
- "write", (PyCFunction)bpy_lib_write,
- METH_STATIC | METH_VARARGS | METH_KEYWORDS,
- bpy_lib_write_doc,
- };
+ static PyMethodDef write_meth = {
+ "write",
+ (PyCFunction)bpy_lib_write,
+ METH_STATIC | METH_VARARGS | METH_KEYWORDS,
+ bpy_lib_write_doc,
+ };
- PyModule_AddObject(mod_par, "_library_write", PyCFunction_New(&write_meth, NULL));
+ PyModule_AddObject(mod_par, "_library_write", PyCFunction_New(&write_meth, NULL));
- return 0;
+ return 0;
}
diff --git a/source/blender/python/intern/bpy_msgbus.c b/source/blender/python/intern/bpy_msgbus.c
index bfcf089fb60..9db4201c252 100644
--- a/source/blender/python/intern/bpy_msgbus.c
+++ b/source/blender/python/intern/bpy_msgbus.c
@@ -40,24 +40,22 @@
#include "bpy_capi_utils.h"
#include "bpy_rna.h"
#include "bpy_intern_string.h"
-#include "bpy_gizmo_wrap.h" /* own include */
-
-
-#include "bpy_msgbus.h" /* own include */
+#include "bpy_gizmo_wrap.h" /* own include */
+#include "bpy_msgbus.h" /* own include */
/* -------------------------------------------------------------------- */
/** \name Internal Utils
* \{ */
#define BPY_MSGBUS_RNA_MSGKEY_DOC \
-" :arg key: Represents the type of data being subscribed to\n" \
-"\n" \
-" Arguments include\n" \
-" - :class:`bpy.types.Property` instance.\n" \
-" - :class:`bpy.types.Struct` type.\n" \
-" - (:class:`bpy.types.Struct`, str) type and property name.\n" \
-" :type key: Muliple\n"
+ " :arg key: Represents the type of data being subscribed to\n" \
+ "\n" \
+ " Arguments include\n" \
+ " - :class:`bpy.types.Property` instance.\n" \
+ " - :class:`bpy.types.Struct` type.\n" \
+ " - (:class:`bpy.types.Struct`, str) type and property name.\n" \
+ " :type key: Muliple\n"
/**
* There are multiple ways we can get RNA from Python,
@@ -69,87 +67,78 @@
* \param msg_key_params: Message key with all members zeroed out.
* \return -1 on failure, 0 on success.
*/
-static int py_msgbus_rna_key_from_py(
- PyObject *py_sub,
- wmMsgParams_RNA *msg_key_params,
- const char *error_prefix)
+static int py_msgbus_rna_key_from_py(PyObject *py_sub,
+ wmMsgParams_RNA *msg_key_params,
+ const char *error_prefix)
{
- /* Allow common case, object rotation, location - etc. */
- if (BaseMathObject_CheckExact(py_sub)) {
- BaseMathObject *py_sub_math = (BaseMathObject *)py_sub;
- if (py_sub_math->cb_user == NULL) {
- PyErr_Format(
- PyExc_TypeError,
- "%s: math argument has no owner",
- error_prefix);
- return -1;
- }
- py_sub = py_sub_math->cb_user;
- /* Common case will use BPy_PropertyRNA_Check below. */
- }
-
- if (BPy_PropertyRNA_Check(py_sub)) {
- BPy_PropertyRNA *data_prop = (BPy_PropertyRNA *)py_sub;
- PYRNA_PROP_CHECK_INT(data_prop);
- msg_key_params->ptr = data_prop->ptr;
- msg_key_params->prop = data_prop->prop;
- }
- else if (BPy_StructRNA_Check(py_sub)) {
- /* note, this isn't typically used since we don't edit structs directly. */
- BPy_StructRNA *data_srna = (BPy_StructRNA *)py_sub;
- PYRNA_STRUCT_CHECK_INT(data_srna);
- msg_key_params->ptr = data_srna->ptr;
- }
- /* TODO - property / type, not instance. */
- else if (PyType_Check(py_sub)) {
- StructRNA *data_type = pyrna_struct_as_srna(py_sub, false, error_prefix);
- if (data_type == NULL) {
- return -1;
- }
- msg_key_params->ptr.type = data_type;
- }
- else if (PyTuple_CheckExact(py_sub)) {
- if (PyTuple_GET_SIZE(py_sub) == 2) {
- PyObject *data_type_py = PyTuple_GET_ITEM(py_sub, 0);
- PyObject *data_prop_py = PyTuple_GET_ITEM(py_sub, 1);
- StructRNA *data_type = pyrna_struct_as_srna(data_type_py, false, error_prefix);
- if (data_type == NULL) {
- return -1;
- }
- if (!PyUnicode_CheckExact(data_prop_py)) {
- PyErr_Format(
- PyExc_TypeError,
- "%s: expected property to be a string",
- error_prefix);
- return -1;
- }
- PointerRNA data_type_ptr = { .type = data_type, };
- const char *data_prop_str = _PyUnicode_AsString(data_prop_py);
- PropertyRNA *data_prop = RNA_struct_find_property(&data_type_ptr, data_prop_str);
-
- if (data_prop == NULL) {
- PyErr_Format(
- PyExc_TypeError,
- "%s: struct %.200s does not contain property %.200s",
- error_prefix,
- RNA_struct_identifier(data_type),
- data_prop_str);
- return -1;
- }
-
- msg_key_params->ptr.type = data_type;
- msg_key_params->prop = data_prop;
- }
- else {
- PyErr_Format(
- PyExc_ValueError,
- "%s: Expected a pair (type, property_id)",
- error_prefix);
- return -1;
- }
- }
- return 0;
+ /* Allow common case, object rotation, location - etc. */
+ if (BaseMathObject_CheckExact(py_sub)) {
+ BaseMathObject *py_sub_math = (BaseMathObject *)py_sub;
+ if (py_sub_math->cb_user == NULL) {
+ PyErr_Format(PyExc_TypeError, "%s: math argument has no owner", error_prefix);
+ return -1;
+ }
+ py_sub = py_sub_math->cb_user;
+ /* Common case will use BPy_PropertyRNA_Check below. */
+ }
+
+ if (BPy_PropertyRNA_Check(py_sub)) {
+ BPy_PropertyRNA *data_prop = (BPy_PropertyRNA *)py_sub;
+ PYRNA_PROP_CHECK_INT(data_prop);
+ msg_key_params->ptr = data_prop->ptr;
+ msg_key_params->prop = data_prop->prop;
+ }
+ else if (BPy_StructRNA_Check(py_sub)) {
+ /* note, this isn't typically used since we don't edit structs directly. */
+ BPy_StructRNA *data_srna = (BPy_StructRNA *)py_sub;
+ PYRNA_STRUCT_CHECK_INT(data_srna);
+ msg_key_params->ptr = data_srna->ptr;
+ }
+ /* TODO - property / type, not instance. */
+ else if (PyType_Check(py_sub)) {
+ StructRNA *data_type = pyrna_struct_as_srna(py_sub, false, error_prefix);
+ if (data_type == NULL) {
+ return -1;
+ }
+ msg_key_params->ptr.type = data_type;
+ }
+ else if (PyTuple_CheckExact(py_sub)) {
+ if (PyTuple_GET_SIZE(py_sub) == 2) {
+ PyObject *data_type_py = PyTuple_GET_ITEM(py_sub, 0);
+ PyObject *data_prop_py = PyTuple_GET_ITEM(py_sub, 1);
+ StructRNA *data_type = pyrna_struct_as_srna(data_type_py, false, error_prefix);
+ if (data_type == NULL) {
+ return -1;
+ }
+ if (!PyUnicode_CheckExact(data_prop_py)) {
+ PyErr_Format(PyExc_TypeError, "%s: expected property to be a string", error_prefix);
+ return -1;
+ }
+ PointerRNA data_type_ptr = {
+ .type = data_type,
+ };
+ const char *data_prop_str = _PyUnicode_AsString(data_prop_py);
+ PropertyRNA *data_prop = RNA_struct_find_property(&data_type_ptr, data_prop_str);
+
+ if (data_prop == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s: struct %.200s does not contain property %.200s",
+ error_prefix,
+ RNA_struct_identifier(data_type),
+ data_prop_str);
+ return -1;
+ }
+
+ msg_key_params->ptr.type = data_type;
+ msg_key_params->prop = data_prop;
+ }
+ else {
+ PyErr_Format(PyExc_ValueError, "%s: Expected a pair (type, property_id)", error_prefix);
+ return -1;
+ }
+ }
+ return 0;
}
/** \} */
@@ -161,51 +150,52 @@ static int py_msgbus_rna_key_from_py(
#define BPY_MSGBUS_USER_DATA_LEN 2
/* Follow wmMsgNotifyFn spec */
-static void bpy_msgbus_notify(
- bContext *C, wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
+static void bpy_msgbus_notify(bContext *C,
+ wmMsgSubscribeKey *UNUSED(msg_key),
+ wmMsgSubscribeValue *msg_val)
{
- PyGILState_STATE gilstate;
- bpy_context_set(C, &gilstate);
-
- PyObject *user_data = msg_val->user_data;
- BLI_assert(PyTuple_GET_SIZE(user_data) == BPY_MSGBUS_USER_DATA_LEN);
-
- PyObject *callback_args = PyTuple_GET_ITEM(user_data, 0);
- PyObject *callback_notify = PyTuple_GET_ITEM(user_data, 1);
-
- const bool is_write_ok = pyrna_write_check();
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- PyObject *ret = PyObject_CallObject(callback_notify, callback_args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(callback_notify);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(callback_notify);
- }
- Py_DECREF(ret);
- }
-
- bpy_context_clear(C, &gilstate);
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyGILState_STATE gilstate;
+ bpy_context_set(C, &gilstate);
+
+ PyObject *user_data = msg_val->user_data;
+ BLI_assert(PyTuple_GET_SIZE(user_data) == BPY_MSGBUS_USER_DATA_LEN);
+
+ PyObject *callback_args = PyTuple_GET_ITEM(user_data, 0);
+ PyObject *callback_notify = PyTuple_GET_ITEM(user_data, 1);
+
+ const bool is_write_ok = pyrna_write_check();
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ PyObject *ret = PyObject_CallObject(callback_notify, callback_args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(callback_notify);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(callback_notify);
+ }
+ Py_DECREF(ret);
+ }
+
+ bpy_context_clear(C, &gilstate);
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
/* Follow wmMsgSubscribeValueFreeDataFn spec */
-static void bpy_msgbus_subscribe_value_free_data(
- struct wmMsgSubscribeKey *UNUSED(msg_key), struct wmMsgSubscribeValue *msg_val)
+static void bpy_msgbus_subscribe_value_free_data(struct wmMsgSubscribeKey *UNUSED(msg_key),
+ struct wmMsgSubscribeValue *msg_val)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
- Py_DECREF(msg_val->owner);
- Py_DECREF(msg_val->user_data);
- PyGILState_Release(gilstate);
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ Py_DECREF(msg_val->owner);
+ Py_DECREF(msg_val->user_data);
+ PyGILState_Release(gilstate);
}
/** \} */
@@ -214,201 +204,196 @@ static void bpy_msgbus_subscribe_value_free_data(
/** \name Public Message Bus API
* \{ */
-PyDoc_STRVAR(bpy_msgbus_subscribe_rna_doc,
-".. function:: subscribe_rna(data, owner, args, notify, options=set())\n"
-"\n"
-BPY_MSGBUS_RNA_MSGKEY_DOC
-" :arg owner: Handle for this subscription (compared by identity).\n"
-" :type owner: Any type.\n"
-" :arg options: Change the behavior of the subscriber.\n"
-"\n"
-" - ``PERSISTENT`` when set, the subscriber will be kept when remapping ID data.\n"
-"\n"
-" :type options: set of str.\n"
-"\n"
-" Returns a new vector int property definition.\n"
-);
+PyDoc_STRVAR(
+ bpy_msgbus_subscribe_rna_doc,
+ ".. function:: subscribe_rna(data, owner, args, notify, options=set())\n"
+ "\n" BPY_MSGBUS_RNA_MSGKEY_DOC
+ " :arg owner: Handle for this subscription (compared by identity).\n"
+ " :type owner: Any type.\n"
+ " :arg options: Change the behavior of the subscriber.\n"
+ "\n"
+ " - ``PERSISTENT`` when set, the subscriber will be kept when remapping ID data.\n"
+ "\n"
+ " :type options: set of str.\n"
+ "\n"
+ " Returns a new vector int property definition.\n");
static PyObject *bpy_msgbus_subscribe_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- const char *error_prefix = "subscribe_rna";
- PyObject *py_sub = NULL;
- PyObject *py_owner = NULL;
- PyObject *callback_args = NULL;
- PyObject *callback_notify = NULL;
-
- enum {
- IS_PERSISTENT = (1 << 0),
- };
- PyObject *py_options = NULL;
- EnumPropertyItem py_options_enum[] = {
- {IS_PERSISTENT, "PERSISTENT", 0, ""},
- {0, NULL, 0, NULL, NULL},
- };
- int options = 0;
-
- if (PyTuple_GET_SIZE(args) != 0) {
- PyErr_Format(
- PyExc_TypeError,
- "%s: only keyword arguments are supported",
- error_prefix);
- return NULL;
- }
- static const char *_keywords[] = {
- "key",
- "owner",
- "args",
- "notify",
- "options",
- NULL,
- };
- static _PyArg_Parser _parser = {"OOO!O|O!:subscribe_rna", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &py_sub, &py_owner,
- &PyTuple_Type, &callback_args,
- &callback_notify,
- &PySet_Type, &py_options))
- {
- return NULL;
- }
-
- if (py_options &&
- (pyrna_set_to_enum_bitfield(py_options_enum, py_options, &options, error_prefix)) == -1)
- {
- return NULL;
- }
-
- /* Note: we may want to have a way to pass this in. */
- bContext *C = (bContext *)BPy_GetContext();
- struct wmMsgBus *mbus = CTX_wm_message_bus(C);
- wmMsgParams_RNA msg_key_params = {{{0}}};
-
- wmMsgSubscribeValue msg_val_params = {0};
-
- if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
- return NULL;
- }
-
- if (!PyFunction_Check(callback_notify)) {
- PyErr_Format(
- PyExc_TypeError,
- "notify expects a function, found %.200s",
- Py_TYPE(callback_notify)->tp_name);
- return NULL;
- }
-
- if (options != 0) {
- if (options & IS_PERSISTENT) {
- msg_val_params.is_persistent = true;
- }
- }
-
- /* owner can be anything. */
- {
- msg_val_params.owner = py_owner;
- Py_INCREF(py_owner);
- }
-
- {
- PyObject *user_data = PyTuple_New(2);
- PyTuple_SET_ITEMS(
- user_data,
- Py_INCREF_RET(callback_args),
- Py_INCREF_RET(callback_notify));
- msg_val_params.user_data = user_data;
- }
-
- msg_val_params.notify = bpy_msgbus_notify;
- msg_val_params.free_data = bpy_msgbus_subscribe_value_free_data;
-
- WM_msg_subscribe_rna_params(mbus, &msg_key_params, &msg_val_params, __func__);
-
- WM_msg_dump(mbus, __func__);
-
- Py_RETURN_NONE;
+ const char *error_prefix = "subscribe_rna";
+ PyObject *py_sub = NULL;
+ PyObject *py_owner = NULL;
+ PyObject *callback_args = NULL;
+ PyObject *callback_notify = NULL;
+
+ enum {
+ IS_PERSISTENT = (1 << 0),
+ };
+ PyObject *py_options = NULL;
+ EnumPropertyItem py_options_enum[] = {
+ {IS_PERSISTENT, "PERSISTENT", 0, ""},
+ {0, NULL, 0, NULL, NULL},
+ };
+ int options = 0;
+
+ if (PyTuple_GET_SIZE(args) != 0) {
+ PyErr_Format(PyExc_TypeError, "%s: only keyword arguments are supported", error_prefix);
+ return NULL;
+ }
+ static const char *_keywords[] = {
+ "key",
+ "owner",
+ "args",
+ "notify",
+ "options",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"OOO!O|O!:subscribe_rna", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &py_sub,
+ &py_owner,
+ &PyTuple_Type,
+ &callback_args,
+ &callback_notify,
+ &PySet_Type,
+ &py_options)) {
+ return NULL;
+ }
+
+ if (py_options &&
+ (pyrna_set_to_enum_bitfield(py_options_enum, py_options, &options, error_prefix)) == -1) {
+ return NULL;
+ }
+
+ /* Note: we may want to have a way to pass this in. */
+ bContext *C = (bContext *)BPy_GetContext();
+ struct wmMsgBus *mbus = CTX_wm_message_bus(C);
+ wmMsgParams_RNA msg_key_params = {{{0}}};
+
+ wmMsgSubscribeValue msg_val_params = {0};
+
+ if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
+ return NULL;
+ }
+
+ if (!PyFunction_Check(callback_notify)) {
+ PyErr_Format(PyExc_TypeError,
+ "notify expects a function, found %.200s",
+ Py_TYPE(callback_notify)->tp_name);
+ return NULL;
+ }
+
+ if (options != 0) {
+ if (options & IS_PERSISTENT) {
+ msg_val_params.is_persistent = true;
+ }
+ }
+
+ /* owner can be anything. */
+ {
+ msg_val_params.owner = py_owner;
+ Py_INCREF(py_owner);
+ }
+
+ {
+ PyObject *user_data = PyTuple_New(2);
+ PyTuple_SET_ITEMS(user_data, Py_INCREF_RET(callback_args), Py_INCREF_RET(callback_notify));
+ msg_val_params.user_data = user_data;
+ }
+
+ msg_val_params.notify = bpy_msgbus_notify;
+ msg_val_params.free_data = bpy_msgbus_subscribe_value_free_data;
+
+ WM_msg_subscribe_rna_params(mbus, &msg_key_params, &msg_val_params, __func__);
+
+ WM_msg_dump(mbus, __func__);
+
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(bpy_msgbus_publish_rna_doc,
-".. function:: publish_rna(data, owner, args, notify)\n"
-"\n"
-BPY_MSGBUS_RNA_MSGKEY_DOC
-"\n"
-" Notify subscribers of changes to this property\n"
-" (this typically doesn't need to be called explicitly since changes will automatically publish updates).\n"
-" In some cases it may be useful to publish changes explicitly using more general keys.\n"
-);
+PyDoc_STRVAR(
+ bpy_msgbus_publish_rna_doc,
+ ".. function:: publish_rna(data, owner, args, notify)\n"
+ "\n" BPY_MSGBUS_RNA_MSGKEY_DOC
+ "\n"
+ " Notify subscribers of changes to this property\n"
+ " (this typically doesn't need to be called explicitly since changes will automatically "
+ "publish updates).\n"
+ " In some cases it may be useful to publish changes explicitly using more general keys.\n");
static PyObject *bpy_msgbus_publish_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- const char *error_prefix = "publish_rna";
- PyObject *py_sub = NULL;
-
- if (PyTuple_GET_SIZE(args) != 0) {
- PyErr_Format(
- PyExc_TypeError,
- "%s: only keyword arguments are supported",
- error_prefix);
- return NULL;
- }
- static const char *_keywords[] = {
- "key",
- NULL,
- };
- static _PyArg_Parser _parser = {"O:publish_rna", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &py_sub))
- {
- return NULL;
- }
-
- /* Note: we may want to have a way to pass this in. */
- bContext *C = (bContext *)BPy_GetContext();
- struct wmMsgBus *mbus = CTX_wm_message_bus(C);
- wmMsgParams_RNA msg_key_params = {{{0}}};
-
- if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
- return NULL;
- }
-
- WM_msg_publish_rna_params(mbus, &msg_key_params);
-
- Py_RETURN_NONE;
+ const char *error_prefix = "publish_rna";
+ PyObject *py_sub = NULL;
+
+ if (PyTuple_GET_SIZE(args) != 0) {
+ PyErr_Format(PyExc_TypeError, "%s: only keyword arguments are supported", error_prefix);
+ return NULL;
+ }
+ static const char *_keywords[] = {
+ "key",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"O:publish_rna", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &py_sub)) {
+ return NULL;
+ }
+
+ /* Note: we may want to have a way to pass this in. */
+ bContext *C = (bContext *)BPy_GetContext();
+ struct wmMsgBus *mbus = CTX_wm_message_bus(C);
+ wmMsgParams_RNA msg_key_params = {{{0}}};
+
+ if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
+ return NULL;
+ }
+
+ WM_msg_publish_rna_params(mbus, &msg_key_params);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(bpy_msgbus_clear_by_owner_doc,
-".. function:: clear_by_owner(owner)\n"
-"\n"
-" Clear all subscribers using this owner.\n"
-);
+ ".. function:: clear_by_owner(owner)\n"
+ "\n"
+ " Clear all subscribers using this owner.\n");
static PyObject *bpy_msgbus_clear_by_owner(PyObject *UNUSED(self), PyObject *py_owner)
{
- bContext *C = (bContext *)BPy_GetContext();
- struct wmMsgBus *mbus = CTX_wm_message_bus(C);
- WM_msgbus_clear_by_owner(mbus, py_owner);
- Py_RETURN_NONE;
+ bContext *C = (bContext *)BPy_GetContext();
+ struct wmMsgBus *mbus = CTX_wm_message_bus(C);
+ WM_msgbus_clear_by_owner(mbus, py_owner);
+ Py_RETURN_NONE;
}
static struct PyMethodDef BPy_msgbus_methods[] = {
- {"subscribe_rna", (PyCFunction)bpy_msgbus_subscribe_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_subscribe_rna_doc},
- {"publish_rna", (PyCFunction)bpy_msgbus_publish_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_publish_rna_doc},
- {"clear_by_owner", (PyCFunction)bpy_msgbus_clear_by_owner, METH_O, bpy_msgbus_clear_by_owner_doc},
- {NULL, NULL, 0, NULL},
+ {"subscribe_rna",
+ (PyCFunction)bpy_msgbus_subscribe_rna,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_msgbus_subscribe_rna_doc},
+ {"publish_rna",
+ (PyCFunction)bpy_msgbus_publish_rna,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_msgbus_publish_rna_doc},
+ {"clear_by_owner",
+ (PyCFunction)bpy_msgbus_clear_by_owner,
+ METH_O,
+ bpy_msgbus_clear_by_owner_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef _bpy_msgbus_def = {
- PyModuleDef_HEAD_INIT,
- .m_name = "msgbus",
- .m_methods = BPy_msgbus_methods,
+ PyModuleDef_HEAD_INIT,
+ .m_name = "msgbus",
+ .m_methods = BPy_msgbus_methods,
};
-
PyObject *BPY_msgbus_module(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&_bpy_msgbus_def);
+ submodule = PyModule_Create(&_bpy_msgbus_def);
- return submodule;
+ return submodule;
}
/** \} */
diff --git a/source/blender/python/intern/bpy_msgbus.h b/source/blender/python/intern/bpy_msgbus.h
index 179b220c3c2..2b3cc4cfaf4 100644
--- a/source/blender/python/intern/bpy_msgbus.h
+++ b/source/blender/python/intern/bpy_msgbus.h
@@ -23,4 +23,4 @@
PyObject *BPY_msgbus_module(void);
-#endif /* __BPY_MSGBUS_H__ */
+#endif /* __BPY_MSGBUS_H__ */
diff --git a/source/blender/python/intern/bpy_operator.c b/source/blender/python/intern/bpy_operator.c
index ff6bd3840e9..1e979ad1d0b 100644
--- a/source/blender/python/intern/bpy_operator.c
+++ b/source/blender/python/intern/bpy_operator.c
@@ -59,385 +59,407 @@
static wmOperatorType *ot_lookup_from_py_string(PyObject *value, const char *py_fn_id)
{
- const char *opname = _PyUnicode_AsString(value);
- if (opname == NULL) {
- PyErr_Format(PyExc_TypeError, "%s() expects a string argument", py_fn_id);
- return NULL;
- }
-
- wmOperatorType *ot = WM_operatortype_find(opname, true);
- if (ot == NULL) {
- PyErr_Format(PyExc_KeyError, "%s(\"%s\") not found", py_fn_id, opname);
- return NULL;
- }
- return ot;
+ const char *opname = _PyUnicode_AsString(value);
+ if (opname == NULL) {
+ PyErr_Format(PyExc_TypeError, "%s() expects a string argument", py_fn_id);
+ return NULL;
+ }
+
+ wmOperatorType *ot = WM_operatortype_find(opname, true);
+ if (ot == NULL) {
+ PyErr_Format(PyExc_KeyError, "%s(\"%s\") not found", py_fn_id, opname);
+ return NULL;
+ }
+ return ot;
}
static PyObject *pyop_poll(PyObject *UNUSED(self), PyObject *args)
{
- wmOperatorType *ot;
- const char *opname;
- PyObject *context_dict = NULL; /* optional args */
- PyObject *context_dict_back;
- const char *context_str = NULL;
- PyObject *ret;
-
- int context = WM_OP_EXEC_DEFAULT;
-
- /* XXX Todo, work out a better solution for passing on context,
- * could make a tuple from self and pack the name and Context into it... */
- bContext *C = (bContext *)BPy_GetContext();
-
- if (C == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "s|Os:_bpy.ops.poll", &opname, &context_dict, &context_str)) {
- return NULL;
- }
-
- ot = WM_operatortype_find(opname, true);
-
- if (ot == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "Polling operator \"bpy.ops.%s\" error, "
- "could not be found", opname);
- return NULL;
- }
-
- if (context_str) {
- if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context) == 0) {
- char *enum_str = BPy_enum_as_string(rna_enum_operator_context_items);
- PyErr_Format(PyExc_TypeError,
- "Calling operator \"bpy.ops.%s.poll\" error, "
- "expected a string enum in (%s)",
- opname, enum_str);
- MEM_freeN(enum_str);
- return NULL;
- }
- }
-
- if (context_dict == NULL || context_dict == Py_None) {
- context_dict = NULL;
- }
- else if (!PyDict_Check(context_dict)) {
- PyErr_Format(PyExc_TypeError,
- "Calling operator \"bpy.ops.%s.poll\" error, "
- "custom context expected a dict or None, got a %.200s",
- opname, Py_TYPE(context_dict)->tp_name);
- return NULL;
- }
-
- context_dict_back = CTX_py_dict_get(C);
- CTX_py_dict_set(C, (void *)context_dict);
- Py_XINCREF(context_dict); /* so we done loose it */
-
- /* main purpose of this function */
- ret = WM_operator_poll_context((bContext *)C, ot, context) ? Py_True : Py_False;
-
- /* restore with original context dict, probably NULL but need this for nested operator calls */
- Py_XDECREF(context_dict);
- CTX_py_dict_set(C, (void *)context_dict_back);
-
- return Py_INCREF_RET(ret);
+ wmOperatorType *ot;
+ const char *opname;
+ PyObject *context_dict = NULL; /* optional args */
+ PyObject *context_dict_back;
+ const char *context_str = NULL;
+ PyObject *ret;
+
+ int context = WM_OP_EXEC_DEFAULT;
+
+ /* XXX Todo, work out a better solution for passing on context,
+ * could make a tuple from self and pack the name and Context into it... */
+ bContext *C = (bContext *)BPy_GetContext();
+
+ if (C == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "s|Os:_bpy.ops.poll", &opname, &context_dict, &context_str)) {
+ return NULL;
+ }
+
+ ot = WM_operatortype_find(opname, true);
+
+ if (ot == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "Polling operator \"bpy.ops.%s\" error, "
+ "could not be found",
+ opname);
+ return NULL;
+ }
+
+ if (context_str) {
+ if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context) == 0) {
+ char *enum_str = BPy_enum_as_string(rna_enum_operator_context_items);
+ PyErr_Format(PyExc_TypeError,
+ "Calling operator \"bpy.ops.%s.poll\" error, "
+ "expected a string enum in (%s)",
+ opname,
+ enum_str);
+ MEM_freeN(enum_str);
+ return NULL;
+ }
+ }
+
+ if (context_dict == NULL || context_dict == Py_None) {
+ context_dict = NULL;
+ }
+ else if (!PyDict_Check(context_dict)) {
+ PyErr_Format(PyExc_TypeError,
+ "Calling operator \"bpy.ops.%s.poll\" error, "
+ "custom context expected a dict or None, got a %.200s",
+ opname,
+ Py_TYPE(context_dict)->tp_name);
+ return NULL;
+ }
+
+ context_dict_back = CTX_py_dict_get(C);
+ CTX_py_dict_set(C, (void *)context_dict);
+ Py_XINCREF(context_dict); /* so we done loose it */
+
+ /* main purpose of this function */
+ ret = WM_operator_poll_context((bContext *)C, ot, context) ? Py_True : Py_False;
+
+ /* restore with original context dict, probably NULL but need this for nested operator calls */
+ Py_XDECREF(context_dict);
+ CTX_py_dict_set(C, (void *)context_dict_back);
+
+ return Py_INCREF_RET(ret);
}
static PyObject *pyop_call(PyObject *UNUSED(self), PyObject *args)
{
- wmOperatorType *ot;
- int error_val = 0;
- PointerRNA ptr;
- int operator_ret = OPERATOR_CANCELLED;
-
- const char *opname;
- const char *context_str = NULL;
- PyObject *kw = NULL; /* optional args */
- PyObject *context_dict = NULL; /* optional args */
- PyObject *context_dict_back;
-
- /* note that context is an int, python does the conversion in this case */
- int context = WM_OP_EXEC_DEFAULT;
- int is_undo = false;
-
- /* XXX Todo, work out a better solution for passing on context,
- * could make a tuple from self and pack the name and Context into it... */
- bContext *C = (bContext *)BPy_GetContext();
-
- if (C == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "sO|O!si:_bpy.ops.call",
- &opname, &context_dict, &PyDict_Type, &kw, &context_str, &is_undo))
- {
- return NULL;
- }
-
- ot = WM_operatortype_find(opname, true);
-
- if (ot == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "Calling operator \"bpy.ops.%s\" error, "
- "could not be found", opname);
- return NULL;
- }
-
- if (!pyrna_write_check()) {
- PyErr_Format(PyExc_RuntimeError,
- "Calling operator \"bpy.ops.%s\" error, "
- "can't modify blend data in this state (drawing/rendering)",
- opname);
- return NULL;
- }
-
- if (context_str) {
- if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context) == 0) {
- char *enum_str = BPy_enum_as_string(rna_enum_operator_context_items);
- PyErr_Format(PyExc_TypeError,
- "Calling operator \"bpy.ops.%s\" error, "
- "expected a string enum in (%s)",
- opname, enum_str);
- MEM_freeN(enum_str);
- return NULL;
- }
- }
-
- if (context_dict == NULL || context_dict == Py_None) {
- context_dict = NULL;
- }
- else if (!PyDict_Check(context_dict)) {
- PyErr_Format(PyExc_TypeError,
- "Calling operator \"bpy.ops.%s\" error, "
- "custom context expected a dict or None, got a %.200s",
- opname, Py_TYPE(context_dict)->tp_name);
- return NULL;
- }
-
- context_dict_back = CTX_py_dict_get(C);
-
- CTX_py_dict_set(C, (void *)context_dict);
- Py_XINCREF(context_dict); /* so we done loose it */
-
- if (WM_operator_poll_context((bContext *)C, ot, context) == false) {
- const char *msg = CTX_wm_operator_poll_msg_get(C);
- PyErr_Format(PyExc_RuntimeError,
- "Operator bpy.ops.%.200s.poll() %.200s",
- opname, msg ? msg : "failed, context is incorrect");
- CTX_wm_operator_poll_msg_set(C, NULL); /* better set to NULL else it could be used again */
- error_val = -1;
- }
- else {
- WM_operator_properties_create_ptr(&ptr, ot);
- WM_operator_properties_sanitize(&ptr, 0);
-
- if (kw && PyDict_Size(kw)) {
- error_val = pyrna_pydict_to_props(&ptr, kw, false, "Converting py args to operator properties: ");
- }
-
- if (error_val == 0) {
- ReportList *reports;
-
- reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
- BKE_reports_init(reports, RPT_STORE | RPT_OP_HOLD); /* own so these don't move into global reports */
+ wmOperatorType *ot;
+ int error_val = 0;
+ PointerRNA ptr;
+ int operator_ret = OPERATOR_CANCELLED;
+
+ const char *opname;
+ const char *context_str = NULL;
+ PyObject *kw = NULL; /* optional args */
+ PyObject *context_dict = NULL; /* optional args */
+ PyObject *context_dict_back;
+
+ /* note that context is an int, python does the conversion in this case */
+ int context = WM_OP_EXEC_DEFAULT;
+ int is_undo = false;
+
+ /* XXX Todo, work out a better solution for passing on context,
+ * could make a tuple from self and pack the name and Context into it... */
+ bContext *C = (bContext *)BPy_GetContext();
+
+ if (C == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args,
+ "sO|O!si:_bpy.ops.call",
+ &opname,
+ &context_dict,
+ &PyDict_Type,
+ &kw,
+ &context_str,
+ &is_undo)) {
+ return NULL;
+ }
+
+ ot = WM_operatortype_find(opname, true);
+
+ if (ot == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "Calling operator \"bpy.ops.%s\" error, "
+ "could not be found",
+ opname);
+ return NULL;
+ }
+
+ if (!pyrna_write_check()) {
+ PyErr_Format(PyExc_RuntimeError,
+ "Calling operator \"bpy.ops.%s\" error, "
+ "can't modify blend data in this state (drawing/rendering)",
+ opname);
+ return NULL;
+ }
+
+ if (context_str) {
+ if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context) == 0) {
+ char *enum_str = BPy_enum_as_string(rna_enum_operator_context_items);
+ PyErr_Format(PyExc_TypeError,
+ "Calling operator \"bpy.ops.%s\" error, "
+ "expected a string enum in (%s)",
+ opname,
+ enum_str);
+ MEM_freeN(enum_str);
+ return NULL;
+ }
+ }
+
+ if (context_dict == NULL || context_dict == Py_None) {
+ context_dict = NULL;
+ }
+ else if (!PyDict_Check(context_dict)) {
+ PyErr_Format(PyExc_TypeError,
+ "Calling operator \"bpy.ops.%s\" error, "
+ "custom context expected a dict or None, got a %.200s",
+ opname,
+ Py_TYPE(context_dict)->tp_name);
+ return NULL;
+ }
+
+ context_dict_back = CTX_py_dict_get(C);
+
+ CTX_py_dict_set(C, (void *)context_dict);
+ Py_XINCREF(context_dict); /* so we done loose it */
+
+ if (WM_operator_poll_context((bContext *)C, ot, context) == false) {
+ const char *msg = CTX_wm_operator_poll_msg_get(C);
+ PyErr_Format(PyExc_RuntimeError,
+ "Operator bpy.ops.%.200s.poll() %.200s",
+ opname,
+ msg ? msg : "failed, context is incorrect");
+ CTX_wm_operator_poll_msg_set(C, NULL); /* better set to NULL else it could be used again */
+ error_val = -1;
+ }
+ else {
+ WM_operator_properties_create_ptr(&ptr, ot);
+ WM_operator_properties_sanitize(&ptr, 0);
+
+ if (kw && PyDict_Size(kw)) {
+ error_val = pyrna_pydict_to_props(
+ &ptr, kw, false, "Converting py args to operator properties: ");
+ }
+
+ if (error_val == 0) {
+ ReportList *reports;
+
+ reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
+ BKE_reports_init(reports,
+ RPT_STORE | RPT_OP_HOLD); /* own so these don't move into global reports */
#ifdef BPY_RELEASE_GIL
- /* release GIL, since a thread could be started from an operator
- * that updates a driver */
- /* note: I have not seen any examples of code that does this
- * so it may not be officially supported but seems to work ok. */
- {
- PyThreadState *ts = PyEval_SaveThread();
+ /* release GIL, since a thread could be started from an operator
+ * that updates a driver */
+ /* note: I have not seen any examples of code that does this
+ * so it may not be officially supported but seems to work ok. */
+ {
+ PyThreadState *ts = PyEval_SaveThread();
#endif
- operator_ret = WM_operator_call_py(C, ot, context, &ptr, reports, is_undo);
+ operator_ret = WM_operator_call_py(C, ot, context, &ptr, reports, is_undo);
#ifdef BPY_RELEASE_GIL
- /* regain GIL */
- PyEval_RestoreThread(ts);
- }
+ /* regain GIL */
+ PyEval_RestoreThread(ts);
+ }
#endif
- error_val = BPy_reports_to_error(reports, PyExc_RuntimeError, false);
+ error_val = BPy_reports_to_error(reports, PyExc_RuntimeError, false);
- /* operator output is nice to have in the terminal/console too */
- if (!BLI_listbase_is_empty(&reports->list)) {
- BPy_reports_write_stdout(reports, NULL);
- }
+ /* operator output is nice to have in the terminal/console too */
+ if (!BLI_listbase_is_empty(&reports->list)) {
+ BPy_reports_write_stdout(reports, NULL);
+ }
- BKE_reports_clear(reports);
- if ((reports->flag & RPT_FREE) == 0) {
- MEM_freeN(reports);
- }
- else {
- /* The WM is now responsible for running the modal operator,
- * show reports in the info window. */
- reports->flag &= ~RPT_OP_HOLD;
- }
- }
+ BKE_reports_clear(reports);
+ if ((reports->flag & RPT_FREE) == 0) {
+ MEM_freeN(reports);
+ }
+ else {
+ /* The WM is now responsible for running the modal operator,
+ * show reports in the info window. */
+ reports->flag &= ~RPT_OP_HOLD;
+ }
+ }
- WM_operator_properties_free(&ptr);
+ WM_operator_properties_free(&ptr);
#if 0
- /* if there is some way to know an operator takes args we should use this */
- {
- /* no props */
- if (kw != NULL) {
- PyErr_Format(PyExc_AttributeError,
- "Operator \"%s\" does not take any args",
- opname);
- return NULL;
- }
-
- WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
- }
+ /* if there is some way to know an operator takes args we should use this */
+ {
+ /* no props */
+ if (kw != NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "Operator \"%s\" does not take any args",
+ opname);
+ return NULL;
+ }
+
+ WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
+ }
#endif
- }
+ }
- /* restore with original context dict, probably NULL but need this for nested operator calls */
- Py_XDECREF(context_dict);
- CTX_py_dict_set(C, (void *)context_dict_back);
+ /* restore with original context dict, probably NULL but need this for nested operator calls */
+ Py_XDECREF(context_dict);
+ CTX_py_dict_set(C, (void *)context_dict_back);
- if (error_val == -1) {
- return NULL;
- }
+ if (error_val == -1) {
+ return NULL;
+ }
- /* when calling bpy.ops.wm.read_factory_settings() bpy.data's main pointer is freed by clear_globals(),
- * further access will crash blender. setting context is not needed in this case, only calling because this
- * function corrects bpy.data (internal Main pointer) */
- BPY_modules_update(C);
+ /* when calling bpy.ops.wm.read_factory_settings() bpy.data's main pointer is freed by clear_globals(),
+ * further access will crash blender. setting context is not needed in this case, only calling because this
+ * function corrects bpy.data (internal Main pointer) */
+ BPY_modules_update(C);
- /* needed for when WM_OT_read_factory_settings us called from within a script */
- bpy_import_main_set(CTX_data_main(C));
-
- /* return operator_ret as a bpy enum */
- return pyrna_enum_bitfield_to_py(rna_enum_operator_return_items, operator_ret);
+ /* needed for when WM_OT_read_factory_settings us called from within a script */
+ bpy_import_main_set(CTX_data_main(C));
+ /* return operator_ret as a bpy enum */
+ return pyrna_enum_bitfield_to_py(rna_enum_operator_return_items, operator_ret);
}
static PyObject *pyop_as_string(PyObject *UNUSED(self), PyObject *args)
{
- wmOperatorType *ot;
- PointerRNA ptr;
-
- const char *opname;
- PyObject *kw = NULL; /* optional args */
- bool all_args = true;
- bool macro_args = true;
- int error_val = 0;
-
- char *buf = NULL;
- PyObject *pybuf;
-
- bContext *C = (bContext *)BPy_GetContext();
-
- if (C == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "Context is None, cant get the string representation of this object.");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(
- args, "s|O!O&O&:_bpy.ops.as_string",
- &opname, &PyDict_Type, &kw,
- PyC_ParseBool, &all_args,
- PyC_ParseBool, &macro_args))
- {
- return NULL;
- }
-
- ot = WM_operatortype_find(opname, true);
-
- if (ot == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "_bpy.ops.as_string: operator \"%.200s\" "
- "could not be found", opname);
- return NULL;
- }
-
- /* WM_operator_properties_create(&ptr, opname); */
- /* Save another lookup */
- RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
-
- if (kw && PyDict_Size(kw)) {
- error_val = pyrna_pydict_to_props(&ptr, kw, false, "Converting py args to operator properties: ");
- }
-
- if (error_val == 0) {
- buf = WM_operator_pystring_ex(C, NULL, all_args, macro_args, ot, &ptr);
- }
-
- WM_operator_properties_free(&ptr);
-
- if (error_val == -1) {
- return NULL;
- }
-
- if (buf) {
- pybuf = PyUnicode_FromString(buf);
- MEM_freeN(buf);
- }
- else {
- pybuf = PyUnicode_FromString("");
- }
-
- return pybuf;
+ wmOperatorType *ot;
+ PointerRNA ptr;
+
+ const char *opname;
+ PyObject *kw = NULL; /* optional args */
+ bool all_args = true;
+ bool macro_args = true;
+ int error_val = 0;
+
+ char *buf = NULL;
+ PyObject *pybuf;
+
+ bContext *C = (bContext *)BPy_GetContext();
+
+ if (C == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Context is None, cant get the string representation of this object.");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args,
+ "s|O!O&O&:_bpy.ops.as_string",
+ &opname,
+ &PyDict_Type,
+ &kw,
+ PyC_ParseBool,
+ &all_args,
+ PyC_ParseBool,
+ &macro_args)) {
+ return NULL;
+ }
+
+ ot = WM_operatortype_find(opname, true);
+
+ if (ot == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "_bpy.ops.as_string: operator \"%.200s\" "
+ "could not be found",
+ opname);
+ return NULL;
+ }
+
+ /* WM_operator_properties_create(&ptr, opname); */
+ /* Save another lookup */
+ RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
+
+ if (kw && PyDict_Size(kw)) {
+ error_val = pyrna_pydict_to_props(
+ &ptr, kw, false, "Converting py args to operator properties: ");
+ }
+
+ if (error_val == 0) {
+ buf = WM_operator_pystring_ex(C, NULL, all_args, macro_args, ot, &ptr);
+ }
+
+ WM_operator_properties_free(&ptr);
+
+ if (error_val == -1) {
+ return NULL;
+ }
+
+ if (buf) {
+ pybuf = PyUnicode_FromString(buf);
+ MEM_freeN(buf);
+ }
+ else {
+ pybuf = PyUnicode_FromString("");
+ }
+
+ return pybuf;
}
static PyObject *pyop_dir(PyObject *UNUSED(self))
{
- GHashIterator iter;
- PyObject *list;
- int i;
+ GHashIterator iter;
+ PyObject *list;
+ int i;
- WM_operatortype_iter(&iter);
- list = PyList_New(BLI_ghash_len(iter.gh));
+ WM_operatortype_iter(&iter);
+ list = PyList_New(BLI_ghash_len(iter.gh));
- for (i = 0; !BLI_ghashIterator_done(&iter); BLI_ghashIterator_step(&iter), i++) {
- wmOperatorType *ot = BLI_ghashIterator_getValue(&iter);
- PyList_SET_ITEM(list, i, PyUnicode_FromString(ot->idname));
- }
+ for (i = 0; !BLI_ghashIterator_done(&iter); BLI_ghashIterator_step(&iter), i++) {
+ wmOperatorType *ot = BLI_ghashIterator_getValue(&iter);
+ PyList_SET_ITEM(list, i, PyUnicode_FromString(ot->idname));
+ }
- return list;
+ return list;
}
static PyObject *pyop_getrna_type(PyObject *UNUSED(self), PyObject *value)
{
- wmOperatorType *ot;
- if ((ot = ot_lookup_from_py_string(value, "get_rna_type")) == NULL) {
- return NULL;
- }
-
- PointerRNA ptr;
- RNA_pointer_create(NULL, &RNA_Struct, ot->srna, &ptr);
- BPy_StructRNA *pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
- return (PyObject *)pyrna;
+ wmOperatorType *ot;
+ if ((ot = ot_lookup_from_py_string(value, "get_rna_type")) == NULL) {
+ return NULL;
+ }
+
+ PointerRNA ptr;
+ RNA_pointer_create(NULL, &RNA_Struct, ot->srna, &ptr);
+ BPy_StructRNA *pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
+ return (PyObject *)pyrna;
}
static struct PyMethodDef bpy_ops_methods[] = {
- {"poll", (PyCFunction) pyop_poll, METH_VARARGS, NULL},
- {"call", (PyCFunction) pyop_call, METH_VARARGS, NULL},
- {"as_string", (PyCFunction) pyop_as_string, METH_VARARGS, NULL},
- {"dir", (PyCFunction) pyop_dir, METH_NOARGS, NULL},
- {"get_rna_type", (PyCFunction) pyop_getrna_type, METH_O, NULL},
- {"macro_define", (PyCFunction) PYOP_wrap_macro_define, METH_VARARGS, NULL},
- {NULL, NULL, 0, NULL},
+ {"poll", (PyCFunction)pyop_poll, METH_VARARGS, NULL},
+ {"call", (PyCFunction)pyop_call, METH_VARARGS, NULL},
+ {"as_string", (PyCFunction)pyop_as_string, METH_VARARGS, NULL},
+ {"dir", (PyCFunction)pyop_dir, METH_NOARGS, NULL},
+ {"get_rna_type", (PyCFunction)pyop_getrna_type, METH_O, NULL},
+ {"macro_define", (PyCFunction)PYOP_wrap_macro_define, METH_VARARGS, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef bpy_ops_module = {
- PyModuleDef_HEAD_INIT,
- "_bpy.ops",
- NULL,
- -1, /* multiple "initialization" just copies the module dict. */
- bpy_ops_methods,
- NULL, NULL, NULL, NULL,
+ PyModuleDef_HEAD_INIT,
+ "_bpy.ops",
+ NULL,
+ -1, /* multiple "initialization" just copies the module dict. */
+ bpy_ops_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
PyObject *BPY_operator_module(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&bpy_ops_module);
+ submodule = PyModule_Create(&bpy_ops_module);
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/intern/bpy_operator.h b/source/blender/python/intern/bpy_operator.h
index 8ecf66adad7..37f6b90fbdb 100644
--- a/source/blender/python/intern/bpy_operator.h
+++ b/source/blender/python/intern/bpy_operator.h
@@ -23,10 +23,10 @@
extern PyTypeObject pyop_base_Type;
-#define BPy_OperatorBase_Check(v) (PyObject_TypeCheck(v, &pyop_base_Type))
+#define BPy_OperatorBase_Check(v) (PyObject_TypeCheck(v, &pyop_base_Type))
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
} BPy_OperatorBase;
PyObject *BPY_operator_module(void);
diff --git a/source/blender/python/intern/bpy_operator_wrap.c b/source/blender/python/intern/bpy_operator_wrap.c
index 6a130a7c52b..976ed4611b0 100644
--- a/source/blender/python/intern/bpy_operator_wrap.c
+++ b/source/blender/python/intern/bpy_operator_wrap.c
@@ -35,163 +35,158 @@
#include "bpy_rna.h"
#include "bpy_intern_string.h"
-#include "bpy_operator_wrap.h" /* own include */
+#include "bpy_operator_wrap.h" /* own include */
static void operator_properties_init(wmOperatorType *ot)
{
- PyTypeObject *py_class = ot->ext.data;
- RNA_struct_blender_type_set(ot->ext.srna, ot);
-
- /* Only call this so pyrna_deferred_register_class gives a useful error
- * WM_operatortype_append_ptr will call RNA_def_struct_identifier later.
- *
- * Note the 'no_struct_map' function is used since the actual struct name is already used by the operator.
- */
- RNA_def_struct_identifier_no_struct_map(ot->srna, ot->idname);
-
- if (pyrna_deferred_register_class(ot->srna, py_class) != 0) {
- PyErr_Print(); /* failed to register operator props */
- PyErr_Clear();
- }
-
- /* set the default property: ot->prop */
- {
- /* picky developers will notice that 'bl_property' won't work with inheritance
- * get direct from the dict to avoid raising a load of attribute errors (yes this isnt ideal) - campbell */
- PyObject *py_class_dict = py_class->tp_dict;
- PyObject *bl_property = PyDict_GetItem(py_class_dict, bpy_intern_str_bl_property);
- const char *prop_id;
- bool prop_raise_error;
-
- if (bl_property) {
- if (PyUnicode_Check(bl_property)) {
- /* since the property is explicitly given, raise an error if its not found */
- prop_id = _PyUnicode_AsString(bl_property);
- prop_raise_error = true;
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "%.200s.bl_property should be a string, not %.200s",
- ot->idname, Py_TYPE(bl_property)->tp_name);
-
- /* this could be done cleaner, for now its OK */
- PyErr_Print();
- PyErr_Clear();
-
- prop_id = NULL;
- prop_raise_error = false;
- }
- }
- else {
- /* fallback to hard-coded string (pre 2.66, could be deprecated) */
- prop_id = "type";
- prop_raise_error = false;
- }
-
- if (prop_id) {
- PointerRNA ptr;
- PropertyRNA *prop;
-
- RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
- prop = RNA_struct_find_property(&ptr, prop_id);
- if (prop) {
- ot->prop = prop;
- }
- else {
- if (prop_raise_error) {
- PyErr_Format(PyExc_ValueError,
- "%.200s.bl_property '%.200s' not found",
- ot->idname, prop_id);
-
- /* this could be done cleaner, for now its OK */
- PyErr_Print();
- PyErr_Clear();
- }
- }
- }
- }
- /* end 'ot->prop' assignment */
-
+ PyTypeObject *py_class = ot->ext.data;
+ RNA_struct_blender_type_set(ot->ext.srna, ot);
+
+ /* Only call this so pyrna_deferred_register_class gives a useful error
+ * WM_operatortype_append_ptr will call RNA_def_struct_identifier later.
+ *
+ * Note the 'no_struct_map' function is used since the actual struct name is already used by the operator.
+ */
+ RNA_def_struct_identifier_no_struct_map(ot->srna, ot->idname);
+
+ if (pyrna_deferred_register_class(ot->srna, py_class) != 0) {
+ PyErr_Print(); /* failed to register operator props */
+ PyErr_Clear();
+ }
+
+ /* set the default property: ot->prop */
+ {
+ /* picky developers will notice that 'bl_property' won't work with inheritance
+ * get direct from the dict to avoid raising a load of attribute errors (yes this isnt ideal) - campbell */
+ PyObject *py_class_dict = py_class->tp_dict;
+ PyObject *bl_property = PyDict_GetItem(py_class_dict, bpy_intern_str_bl_property);
+ const char *prop_id;
+ bool prop_raise_error;
+
+ if (bl_property) {
+ if (PyUnicode_Check(bl_property)) {
+ /* since the property is explicitly given, raise an error if its not found */
+ prop_id = _PyUnicode_AsString(bl_property);
+ prop_raise_error = true;
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s.bl_property should be a string, not %.200s",
+ ot->idname,
+ Py_TYPE(bl_property)->tp_name);
+
+ /* this could be done cleaner, for now its OK */
+ PyErr_Print();
+ PyErr_Clear();
+
+ prop_id = NULL;
+ prop_raise_error = false;
+ }
+ }
+ else {
+ /* fallback to hard-coded string (pre 2.66, could be deprecated) */
+ prop_id = "type";
+ prop_raise_error = false;
+ }
+
+ if (prop_id) {
+ PointerRNA ptr;
+ PropertyRNA *prop;
+
+ RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
+ prop = RNA_struct_find_property(&ptr, prop_id);
+ if (prop) {
+ ot->prop = prop;
+ }
+ else {
+ if (prop_raise_error) {
+ PyErr_Format(
+ PyExc_ValueError, "%.200s.bl_property '%.200s' not found", ot->idname, prop_id);
+
+ /* this could be done cleaner, for now its OK */
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
+ }
+ }
+ /* end 'ot->prop' assignment */
}
void BPY_RNA_operator_wrapper(wmOperatorType *ot, void *userdata)
{
- /* take care not to overwrite anything set in
- * WM_operatortype_append_ptr before opfunc() is called */
- StructRNA *srna = ot->srna;
- *ot = *((wmOperatorType *)userdata);
- ot->srna = srna; /* restore */
-
- /* Use i18n context from ext.srna if possible (py operators). */
- if (ot->ext.srna) {
- RNA_def_struct_translation_context(ot->srna, RNA_struct_translation_context(ot->ext.srna));
- }
-
- operator_properties_init(ot);
+ /* take care not to overwrite anything set in
+ * WM_operatortype_append_ptr before opfunc() is called */
+ StructRNA *srna = ot->srna;
+ *ot = *((wmOperatorType *)userdata);
+ ot->srna = srna; /* restore */
+
+ /* Use i18n context from ext.srna if possible (py operators). */
+ if (ot->ext.srna) {
+ RNA_def_struct_translation_context(ot->srna, RNA_struct_translation_context(ot->ext.srna));
+ }
+
+ operator_properties_init(ot);
}
void BPY_RNA_operator_macro_wrapper(wmOperatorType *ot, void *userdata)
{
- wmOperatorType *data = (wmOperatorType *)userdata;
-
- /* only copy a couple of things, the rest is set by the macro registration */
- ot->name = data->name;
- ot->idname = data->idname;
- ot->description = data->description;
- ot->flag |= data->flag; /* append flags to the one set by registration */
- ot->pyop_poll = data->pyop_poll;
- ot->ui = data->ui;
- ot->ext = data->ext;
-
- /* Use i18n context from ext.srna if possible (py operators). */
- if (ot->ext.srna) {
- RNA_def_struct_translation_context(ot->srna, RNA_struct_translation_context(ot->ext.srna));
- }
-
- operator_properties_init(ot);
+ wmOperatorType *data = (wmOperatorType *)userdata;
+
+ /* only copy a couple of things, the rest is set by the macro registration */
+ ot->name = data->name;
+ ot->idname = data->idname;
+ ot->description = data->description;
+ ot->flag |= data->flag; /* append flags to the one set by registration */
+ ot->pyop_poll = data->pyop_poll;
+ ot->ui = data->ui;
+ ot->ext = data->ext;
+
+ /* Use i18n context from ext.srna if possible (py operators). */
+ if (ot->ext.srna) {
+ RNA_def_struct_translation_context(ot->srna, RNA_struct_translation_context(ot->ext.srna));
+ }
+
+ operator_properties_init(ot);
}
PyObject *PYOP_wrap_macro_define(PyObject *UNUSED(self), PyObject *args)
{
- wmOperatorType *ot;
- wmOperatorTypeMacro *otmacro;
- PyObject *macro;
- PointerRNA ptr_otmacro;
- StructRNA *srna;
-
- const char *opname;
- const char *macroname;
-
- if (!PyArg_ParseTuple(args, "Os:_bpy.ops.macro_define", &macro, &opname)) {
- return NULL;
- }
-
- if (WM_operatortype_find(opname, true) == NULL) {
- PyErr_Format(PyExc_ValueError,
- "Macro Define: '%s' is not a valid operator id",
- opname);
- return NULL;
- }
-
- /* identifiers */
- srna = pyrna_struct_as_srna((PyObject *)macro, false, "Macro Define:");
- if (srna == NULL) {
- return NULL;
- }
-
- macroname = RNA_struct_identifier(srna);
- ot = WM_operatortype_find(macroname, true);
-
- if (!ot) {
- PyErr_Format(PyExc_ValueError,
- "Macro Define: '%s' is not a valid macro",
- macroname);
- return NULL;
- }
-
- otmacro = WM_operatortype_macro_define(ot, opname);
-
- RNA_pointer_create(NULL, &RNA_OperatorMacro, otmacro, &ptr_otmacro);
-
- return pyrna_struct_CreatePyObject(&ptr_otmacro);
+ wmOperatorType *ot;
+ wmOperatorTypeMacro *otmacro;
+ PyObject *macro;
+ PointerRNA ptr_otmacro;
+ StructRNA *srna;
+
+ const char *opname;
+ const char *macroname;
+
+ if (!PyArg_ParseTuple(args, "Os:_bpy.ops.macro_define", &macro, &opname)) {
+ return NULL;
+ }
+
+ if (WM_operatortype_find(opname, true) == NULL) {
+ PyErr_Format(PyExc_ValueError, "Macro Define: '%s' is not a valid operator id", opname);
+ return NULL;
+ }
+
+ /* identifiers */
+ srna = pyrna_struct_as_srna((PyObject *)macro, false, "Macro Define:");
+ if (srna == NULL) {
+ return NULL;
+ }
+
+ macroname = RNA_struct_identifier(srna);
+ ot = WM_operatortype_find(macroname, true);
+
+ if (!ot) {
+ PyErr_Format(PyExc_ValueError, "Macro Define: '%s' is not a valid macro", macroname);
+ return NULL;
+ }
+
+ otmacro = WM_operatortype_macro_define(ot, opname);
+
+ RNA_pointer_create(NULL, &RNA_OperatorMacro, otmacro, &ptr_otmacro);
+
+ return pyrna_struct_CreatePyObject(&ptr_otmacro);
}
diff --git a/source/blender/python/intern/bpy_path.c b/source/blender/python/intern/bpy_path.c
index 89f7fda9d4f..2ac59a694ec 100644
--- a/source/blender/python/intern/bpy_path.c
+++ b/source/blender/python/intern/bpy_path.c
@@ -35,26 +35,26 @@ extern const char *imb_ext_audio[];
/*----------------------------MODULE INIT-------------------------*/
static struct PyModuleDef _bpy_path_module_def = {
- PyModuleDef_HEAD_INIT,
- "_bpy_path", /* m_name */
- NULL, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "_bpy_path", /* m_name */
+ NULL, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyObject *BPyInit__bpy_path(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&_bpy_path_module_def);
+ submodule = PyModule_Create(&_bpy_path_module_def);
- PyModule_AddObject(submodule, "extensions_image", PyC_FrozenSetFromStrings(imb_ext_image));
- PyModule_AddObject(submodule, "extensions_movie", PyC_FrozenSetFromStrings(imb_ext_movie));
- PyModule_AddObject(submodule, "extensions_audio", PyC_FrozenSetFromStrings(imb_ext_audio));
+ PyModule_AddObject(submodule, "extensions_image", PyC_FrozenSetFromStrings(imb_ext_image));
+ PyModule_AddObject(submodule, "extensions_movie", PyC_FrozenSetFromStrings(imb_ext_movie));
+ PyModule_AddObject(submodule, "extensions_audio", PyC_FrozenSetFromStrings(imb_ext_audio));
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/intern/bpy_path.h b/source/blender/python/intern/bpy_path.h
index 7e38e3693fc..3f102ae2bb9 100644
--- a/source/blender/python/intern/bpy_path.h
+++ b/source/blender/python/intern/bpy_path.h
@@ -18,7 +18,6 @@
* \ingroup pythonintern
*/
-
#ifndef __BPY_PATH_H__
#define __BPY_PATH_H__
diff --git a/source/blender/python/intern/bpy_props.c b/source/blender/python/intern/bpy_props.c
index 18a39f39e70..19315d9f2cc 100644
--- a/source/blender/python/intern/bpy_props.c
+++ b/source/blender/python/intern/bpy_props.c
@@ -22,7 +22,6 @@
* existing blender types.
*/
-
#include <Python.h>
#include "RNA_types.h"
@@ -45,102 +44,110 @@
/* initial definition of callback slots we'll probably have more than 1 */
enum {
- BPY_DATA_CB_SLOT_UPDATE = 0,
- BPY_DATA_CB_SLOT_GET = 1,
- BPY_DATA_CB_SLOT_SET = 2,
- BPY_DATA_CB_SLOT_POLL = 3,
- BPY_DATA_CB_SLOT_SIZE = 4,
+ BPY_DATA_CB_SLOT_UPDATE = 0,
+ BPY_DATA_CB_SLOT_GET = 1,
+ BPY_DATA_CB_SLOT_SET = 2,
+ BPY_DATA_CB_SLOT_POLL = 3,
+ BPY_DATA_CB_SLOT_SIZE = 4,
};
static const EnumPropertyItem property_flag_items[] = {
- {PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
- {PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
- {PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
- {PROP_LIB_EXCEPTION, "LIBRARY_EDITABLE", 0, "Library Editable", ""},
- {PROP_PROPORTIONAL, "PROPORTIONAL", 0, "Adjust values proportionally to eachother", ""},
- {PROP_TEXTEDIT_UPDATE, "TEXTEDIT_UPDATE", 0, "Update on every keystroke in textedit 'mode'", ""},
- {0, NULL, 0, NULL, NULL},
+ {PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
+ {PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
+ {PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
+ {PROP_LIB_EXCEPTION, "LIBRARY_EDITABLE", 0, "Library Editable", ""},
+ {PROP_PROPORTIONAL, "PROPORTIONAL", 0, "Adjust values proportionally to eachother", ""},
+ {PROP_TEXTEDIT_UPDATE,
+ "TEXTEDIT_UPDATE",
+ 0,
+ "Update on every keystroke in textedit 'mode'",
+ ""},
+ {0, NULL, 0, NULL, NULL},
};
#define BPY_PROPDEF_OPTIONS_DOC \
-" :arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'LIBRARY_EDITABLE', 'PROPORTIONAL'," \
- "'TEXTEDIT_UPDATE'].\n" \
-" :type options: set\n" \
+ " :arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'LIBRARY_EDITABLE', " \
+ "'PROPORTIONAL'," \
+ "'TEXTEDIT_UPDATE'].\n" \
+ " :type options: set\n"
static const EnumPropertyItem property_flag_enum_items[] = {
- {PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
- {PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
- {PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
- {PROP_LIB_EXCEPTION, "LIBRARY_EDITABLE", 0, "Library Editable", ""},
- {PROP_ENUM_FLAG, "ENUM_FLAG", 0, "Enum Flag", ""},
- {0, NULL, 0, NULL, NULL},
+ {PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
+ {PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
+ {PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
+ {PROP_LIB_EXCEPTION, "LIBRARY_EDITABLE", 0, "Library Editable", ""},
+ {PROP_ENUM_FLAG, "ENUM_FLAG", 0, "Enum Flag", ""},
+ {0, NULL, 0, NULL, NULL},
};
#define BPY_PROPDEF_OPTIONS_ENUM_DOC \
-" :arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'ENUM_FLAG', 'LIBRARY_EDITABLE'].\n" \
-" :type options: set\n" \
+ " :arg options: Enumerator in ['HIDDEN', 'SKIP_SAVE', 'ANIMATABLE', 'ENUM_FLAG', " \
+ "'LIBRARY_EDITABLE'].\n" \
+ " :type options: set\n"
/* subtypes */
/* XXX Keep in sync with rna_rna.c's rna_enum_property_subtype_items ???
* Currently it is not...
*/
static const EnumPropertyItem property_subtype_string_items[] = {
- {PROP_FILEPATH, "FILE_PATH", 0, "File Path", ""},
- {PROP_DIRPATH, "DIR_PATH", 0, "Directory Path", ""},
- {PROP_FILENAME, "FILE_NAME", 0, "Filename", ""},
- {PROP_BYTESTRING, "BYTE_STRING", 0, "Byte String", ""},
- {PROP_PASSWORD, "PASSWORD", 0, "Password", "A string that is displayed hidden ('********')"},
-
- {PROP_NONE, "NONE", 0, "None", ""},
- {0, NULL, 0, NULL, NULL},
+ {PROP_FILEPATH, "FILE_PATH", 0, "File Path", ""},
+ {PROP_DIRPATH, "DIR_PATH", 0, "Directory Path", ""},
+ {PROP_FILENAME, "FILE_NAME", 0, "Filename", ""},
+ {PROP_BYTESTRING, "BYTE_STRING", 0, "Byte String", ""},
+ {PROP_PASSWORD, "PASSWORD", 0, "Password", "A string that is displayed hidden ('********')"},
+
+ {PROP_NONE, "NONE", 0, "None", ""},
+ {0, NULL, 0, NULL, NULL},
};
#define BPY_PROPDEF_SUBTYPE_STRING_DOC \
-" :arg subtype: Enumerator in ['FILE_PATH', 'DIR_PATH', 'FILE_NAME', 'BYTE_STRING', 'PASSWORD', 'NONE'].\n" \
-" :type subtype: string\n" \
+ " :arg subtype: Enumerator in ['FILE_PATH', 'DIR_PATH', 'FILE_NAME', 'BYTE_STRING', " \
+ "'PASSWORD', 'NONE'].\n" \
+ " :type subtype: string\n"
static const EnumPropertyItem property_subtype_number_items[] = {
- {PROP_PIXEL, "PIXEL", 0, "Pixel", ""},
- {PROP_UNSIGNED, "UNSIGNED", 0, "Unsigned", ""},
- {PROP_PERCENTAGE, "PERCENTAGE", 0, "Percentage", ""},
- {PROP_FACTOR, "FACTOR", 0, "Factor", ""},
- {PROP_ANGLE, "ANGLE", 0, "Angle", ""},
- {PROP_TIME, "TIME", 0, "Time", ""},
- {PROP_DISTANCE, "DISTANCE", 0, "Distance", ""},
-
- {PROP_NONE, "NONE", 0, "None", ""},
- {0, NULL, 0, NULL, NULL},
+ {PROP_PIXEL, "PIXEL", 0, "Pixel", ""},
+ {PROP_UNSIGNED, "UNSIGNED", 0, "Unsigned", ""},
+ {PROP_PERCENTAGE, "PERCENTAGE", 0, "Percentage", ""},
+ {PROP_FACTOR, "FACTOR", 0, "Factor", ""},
+ {PROP_ANGLE, "ANGLE", 0, "Angle", ""},
+ {PROP_TIME, "TIME", 0, "Time", ""},
+ {PROP_DISTANCE, "DISTANCE", 0, "Distance", ""},
+
+ {PROP_NONE, "NONE", 0, "None", ""},
+ {0, NULL, 0, NULL, NULL},
};
#define BPY_PROPDEF_SUBTYPE_NUMBER_DOC \
-" :arg subtype: Enumerator in ['PIXEL', 'UNSIGNED', 'PERCENTAGE', 'FACTOR', 'ANGLE', 'TIME', 'DISTANCE', 'NONE'].\n" \
-" :type subtype: string\n" \
+ " :arg subtype: Enumerator in ['PIXEL', 'UNSIGNED', 'PERCENTAGE', 'FACTOR', 'ANGLE', " \
+ "'TIME', 'DISTANCE', 'NONE'].\n" \
+ " :type subtype: string\n"
static const EnumPropertyItem property_subtype_array_items[] = {
- {PROP_COLOR, "COLOR", 0, "Color", ""},
- {PROP_TRANSLATION, "TRANSLATION", 0, "Translation", ""},
- {PROP_DIRECTION, "DIRECTION", 0, "Direction", ""},
- {PROP_VELOCITY, "VELOCITY", 0, "Velocity", ""},
- {PROP_ACCELERATION, "ACCELERATION", 0, "Acceleration", ""},
- {PROP_MATRIX, "MATRIX", 0, "Matrix", ""},
- {PROP_EULER, "EULER", 0, "Euler", ""},
- {PROP_QUATERNION, "QUATERNION", 0, "Quaternion", ""},
- {PROP_AXISANGLE, "AXISANGLE", 0, "Axis Angle", ""},
- {PROP_XYZ, "XYZ", 0, "XYZ", ""},
- {PROP_COLOR_GAMMA, "COLOR_GAMMA", 0, "Color Gamma", ""},
- {PROP_LAYER, "LAYER", 0, "Layer", ""},
- {PROP_LAYER_MEMBER, "LAYER_MEMBER", 0, "Layer Member", ""},
- {PROP_POWER, "POWER", 0, "Power", ""},
-
- {PROP_NONE, "NONE", 0, "None", ""},
- {0, NULL, 0, NULL, NULL},
+ {PROP_COLOR, "COLOR", 0, "Color", ""},
+ {PROP_TRANSLATION, "TRANSLATION", 0, "Translation", ""},
+ {PROP_DIRECTION, "DIRECTION", 0, "Direction", ""},
+ {PROP_VELOCITY, "VELOCITY", 0, "Velocity", ""},
+ {PROP_ACCELERATION, "ACCELERATION", 0, "Acceleration", ""},
+ {PROP_MATRIX, "MATRIX", 0, "Matrix", ""},
+ {PROP_EULER, "EULER", 0, "Euler", ""},
+ {PROP_QUATERNION, "QUATERNION", 0, "Quaternion", ""},
+ {PROP_AXISANGLE, "AXISANGLE", 0, "Axis Angle", ""},
+ {PROP_XYZ, "XYZ", 0, "XYZ", ""},
+ {PROP_COLOR_GAMMA, "COLOR_GAMMA", 0, "Color Gamma", ""},
+ {PROP_LAYER, "LAYER", 0, "Layer", ""},
+ {PROP_LAYER_MEMBER, "LAYER_MEMBER", 0, "Layer Member", ""},
+ {PROP_POWER, "POWER", 0, "Power", ""},
+
+ {PROP_NONE, "NONE", 0, "None", ""},
+ {0, NULL, 0, NULL, NULL},
};
#define BPY_PROPDEF_SUBTYPE_ARRAY_DOC \
-" :arg subtype: Enumerator in ['COLOR', 'TRANSLATION', 'DIRECTION', " \
- "'VELOCITY', 'ACCELERATION', 'MATRIX', 'EULER', 'QUATERNION', 'AXISANGLE', " \
- "'XYZ', 'COLOR_GAMMA', 'LAYER', 'LAYER_MEMBER', 'POWER', 'NONE'].\n" \
-" :type subtype: string\n"
+ " :arg subtype: Enumerator in ['COLOR', 'TRANSLATION', 'DIRECTION', " \
+ "'VELOCITY', 'ACCELERATION', 'MATRIX', 'EULER', 'QUATERNION', 'AXISANGLE', " \
+ "'XYZ', 'COLOR_GAMMA', 'LAYER', 'LAYER_MEMBER', 'POWER', 'NONE'].\n" \
+ " :type subtype: string\n"
/* PyObject's */
static PyObject *pymeth_BoolProperty = NULL;
@@ -157,39 +164,39 @@ static PyObject *pymeth_RemoveProperty = NULL;
static PyObject *pyrna_struct_as_instance(PointerRNA *ptr)
{
- PyObject *self = NULL;
- /* first get self */
- /* operators can store their own instance for later use */
- if (ptr->data) {
- void **instance = RNA_struct_instance(ptr);
-
- if (instance) {
- if (*instance) {
- self = *instance;
- Py_INCREF(self);
- }
- }
- }
-
- /* in most cases this will run */
- if (self == NULL) {
- self = pyrna_struct_CreatePyObject(ptr);
- }
-
- return self;
+ PyObject *self = NULL;
+ /* first get self */
+ /* operators can store their own instance for later use */
+ if (ptr->data) {
+ void **instance = RNA_struct_instance(ptr);
+
+ if (instance) {
+ if (*instance) {
+ self = *instance;
+ Py_INCREF(self);
+ }
+ }
+ }
+
+ /* in most cases this will run */
+ if (self == NULL) {
+ self = pyrna_struct_CreatePyObject(ptr);
+ }
+
+ return self;
}
static void bpy_prop_assign_flag(PropertyRNA *prop, const int flag)
{
- const int flag_mask = ((PROP_ANIMATABLE) & ~flag);
+ const int flag_mask = ((PROP_ANIMATABLE) & ~flag);
- if (flag) {
- RNA_def_property_flag(prop, flag);
- }
+ if (flag) {
+ RNA_def_property_flag(prop, flag);
+ }
- if (flag_mask) {
- RNA_def_property_clear_flag(prop, flag_mask);
- }
+ if (flag_mask) {
+ RNA_def_property_clear_flag(prop, flag_mask);
+ }
}
/* operators and classes use this so it can store the args given but defer
@@ -197,3092 +204,3289 @@ static void bpy_prop_assign_flag(PropertyRNA *prop, const int flag)
* the default args for that operator instance */
static PyObject *bpy_prop_deferred_return(PyObject *func, PyObject *kw)
{
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEM(ret, 0, func);
- Py_INCREF(func);
+ PyObject *ret = PyTuple_New(2);
+ PyTuple_SET_ITEM(ret, 0, func);
+ Py_INCREF(func);
- if (kw == NULL) {
- kw = PyDict_New();
- }
- else {
- Py_INCREF(kw);
- }
+ if (kw == NULL) {
+ kw = PyDict_New();
+ }
+ else {
+ Py_INCREF(kw);
+ }
- PyTuple_SET_ITEM(ret, 1, kw);
+ PyTuple_SET_ITEM(ret, 1, kw);
- return ret;
+ return ret;
}
/* callbacks */
-static void bpy_prop_update_cb(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop)
+static void bpy_prop_update_cb(struct bContext *C,
+ struct PointerRNA *ptr,
+ struct PropertyRNA *prop)
{
- PyGILState_STATE gilstate;
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- const bool is_write_ok = pyrna_write_check();
+ PyGILState_STATE gilstate;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ const bool is_write_ok = pyrna_write_check();
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- bpy_context_set(C, &gilstate);
+ bpy_context_set(C, &gilstate);
- py_func = py_data[BPY_DATA_CB_SLOT_UPDATE];
+ py_func = py_data[BPY_DATA_CB_SLOT_UPDATE];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- PyTuple_SET_ITEM(args, 1, (PyObject *)bpy_context_module);
- Py_INCREF(bpy_context_module);
+ PyTuple_SET_ITEM(args, 1, (PyObject *)bpy_context_module);
+ Py_INCREF(bpy_context_module);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- bpy_context_clear(C, &gilstate);
+ bpy_context_clear(C, &gilstate);
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static bool bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- bool value;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ bool value;
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- value = false;
- }
- else {
- int value_i = PyC_Long_AsBool(ret);
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = false;
+ }
+ else {
+ int value_i = PyC_Long_AsBool(ret);
- if (value_i == -1 && PyErr_Occurred()) {
- PyC_Err_PrintWithFunc(py_func);
- value = false;
- }
- else {
- value = (bool)value_i;
- }
+ if (value_i == -1 && PyErr_Occurred()) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = false;
+ }
+ else {
+ value = (bool)value_i;
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
- return value;
+ return value;
}
static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, bool value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- PyTuple_SET_ITEM(args, 1, PyBool_FromLong(value));
+ PyTuple_SET_ITEM(args, 1, PyBool_FromLong(value));
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static bool bpy_prop_poll_cb(struct PointerRNA *self, PointerRNA candidate, struct PropertyRNA *prop)
+static bool bpy_prop_poll_cb(struct PointerRNA *self,
+ PointerRNA candidate,
+ struct PropertyRNA *prop)
{
- PyObject *py_self;
- PyObject *py_candidate;
- PyObject *py_func;
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *args;
- PyObject *ret;
- bool result;
- const int is_write_ok = pyrna_write_check();
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- BLI_assert(self != NULL);
-
- py_self = pyrna_struct_as_instance(self);
- py_candidate = pyrna_struct_as_instance(&candidate);
- py_func = py_data[BPY_DATA_CB_SLOT_POLL];
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- args = PyTuple_New(2);
- PyTuple_SET_ITEM(args, 0, py_self);
- PyTuple_SET_ITEM(args, 1, py_candidate);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- result = false;
- }
- else {
- result = PyObject_IsTrue(ret);
- Py_DECREF(ret);
- }
-
- PyGILState_Release(gilstate);
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
-
- return result;
+ PyObject *py_self;
+ PyObject *py_candidate;
+ PyObject *py_func;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *args;
+ PyObject *ret;
+ bool result;
+ const int is_write_ok = pyrna_write_check();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ BLI_assert(self != NULL);
+
+ py_self = pyrna_struct_as_instance(self);
+ py_candidate = pyrna_struct_as_instance(&candidate);
+ py_func = py_data[BPY_DATA_CB_SLOT_POLL];
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ args = PyTuple_New(2);
+ PyTuple_SET_ITEM(args, 0, py_self);
+ PyTuple_SET_ITEM(args, 1, py_candidate);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ result = false;
+ }
+ else {
+ result = PyObject_IsTrue(ret);
+ Py_DECREF(ret);
+ }
+
+ PyGILState_Release(gilstate);
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
+
+ return result;
}
-static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, bool *values)
+static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ bool *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int i, len = RNA_property_array_length(ptr, prop);
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
-
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = false;
- }
- }
- else {
- if (PyC_AsArray(values, ret, len, &PyBool_Type, false, "BoolVectorProperty get") == -1) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = false;
- }
-
- /* PyC_AsArray decrements refcount internally on error */
- }
- else {
- Py_DECREF(ret);
- }
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int i, len = RNA_property_array_length(ptr, prop);
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
+
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = false;
+ }
+ }
+ else {
+ if (PyC_AsArray(values, ret, len, &PyBool_Type, false, "BoolVectorProperty get") == -1) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = false;
+ }
+
+ /* PyC_AsArray decrements refcount internally on error */
+ }
+ else {
+ Py_DECREF(ret);
+ }
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const bool *values)
+static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ const bool *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyObject *py_values;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int len = RNA_property_array_length(ptr, prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyObject *py_values;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int len = RNA_property_array_length(ptr, prop);
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_Tuple_PackArray_Bool(values, len);
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_Bool(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static int bpy_prop_int_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int value;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int value;
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- value = 0.0f;
- }
- else {
- value = PyC_Long_AsI32(ret);
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = 0.0f;
+ }
+ else {
+ value = PyC_Long_AsI32(ret);
- if (value == -1 && PyErr_Occurred()) {
- PyC_Err_PrintWithFunc(py_func);
- value = 0;
- }
+ if (value == -1 && PyErr_Occurred()) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = 0;
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
- return value;
+ return value;
}
static void bpy_prop_int_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- PyTuple_SET_ITEM(args, 1, PyLong_FromLong(value));
+ PyTuple_SET_ITEM(args, 1, PyLong_FromLong(value));
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static void bpy_prop_int_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values)
+static void bpy_prop_int_array_get_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ int *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int i, len = RNA_property_array_length(ptr, prop);
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
-
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = 0;
- }
- }
- else {
- if (PyC_AsArray(values, ret, len, &PyLong_Type, false, "IntVectorProperty get") == -1) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = 0;
- }
-
- /* PyC_AsArray decrements refcount internally on error */
- }
- else {
- Py_DECREF(ret);
- }
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int i, len = RNA_property_array_length(ptr, prop);
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
+
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = 0;
+ }
+ }
+ else {
+ if (PyC_AsArray(values, ret, len, &PyLong_Type, false, "IntVectorProperty get") == -1) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = 0;
+ }
+
+ /* PyC_AsArray decrements refcount internally on error */
+ }
+ else {
+ Py_DECREF(ret);
+ }
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static void bpy_prop_int_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values)
+static void bpy_prop_int_array_set_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ const int *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyObject *py_values;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int len = RNA_property_array_length(ptr, prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyObject *py_values;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int len = RNA_property_array_length(ptr, prop);
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_Tuple_PackArray_I32(values, len);
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_I32(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static float bpy_prop_float_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- float value;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ float value;
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- value = 0.0f;
- }
- else {
- value = PyFloat_AsDouble(ret);
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = 0.0f;
+ }
+ else {
+ value = PyFloat_AsDouble(ret);
- if (value == -1.0f && PyErr_Occurred()) {
- PyC_Err_PrintWithFunc(py_func);
- value = 0.0f;
- }
+ if (value == -1.0f && PyErr_Occurred()) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = 0.0f;
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
- return value;
+ return value;
}
static void bpy_prop_float_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, float value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- PyTuple_SET_ITEM(args, 1, PyFloat_FromDouble(value));
+ PyTuple_SET_ITEM(args, 1, PyFloat_FromDouble(value));
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static void bpy_prop_float_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, float *values)
+static void bpy_prop_float_array_get_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ float *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int i, len = RNA_property_array_length(ptr, prop);
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
-
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = 0.0f;
- }
- }
- else {
- if (PyC_AsArray(values, ret, len, &PyFloat_Type, false, "FloatVectorProperty get") == -1) {
- PyC_Err_PrintWithFunc(py_func);
-
- for (i = 0; i < len; ++i) {
- values[i] = 0.0f;
- }
-
- /* PyC_AsArray decrements refcount internally on error */
- }
- else {
- Py_DECREF(ret);
- }
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int i, len = RNA_property_array_length(ptr, prop);
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
+
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = 0.0f;
+ }
+ }
+ else {
+ if (PyC_AsArray(values, ret, len, &PyFloat_Type, false, "FloatVectorProperty get") == -1) {
+ PyC_Err_PrintWithFunc(py_func);
+
+ for (i = 0; i < len; ++i) {
+ values[i] = 0.0f;
+ }
+
+ /* PyC_AsArray decrements refcount internally on error */
+ }
+ else {
+ Py_DECREF(ret);
+ }
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
-static void bpy_prop_float_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const float *values)
+static void bpy_prop_float_array_set_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ const float *values)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyObject *py_values;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int len = RNA_property_array_length(ptr, prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyObject *py_values;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int len = RNA_property_array_length(ptr, prop);
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_Tuple_PackArray_F32(values, len);
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_F32(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static void bpy_prop_string_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, char *value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
-
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- value[0] = '\0';
- }
- else if (!PyUnicode_Check(ret)) {
- PyErr_Format(PyExc_TypeError,
- "return value must be a string, not %.200s",
- Py_TYPE(ret)->tp_name);
- PyC_Err_PrintWithFunc(py_func);
- value[0] = '\0';
- Py_DECREF(ret);
- }
- else {
- Py_ssize_t length;
- const char *buffer = _PyUnicode_AsStringAndSize(ret, &length);
- memcpy(value, buffer, length + 1);
- Py_DECREF(ret);
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
+
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ value[0] = '\0';
+ }
+ else if (!PyUnicode_Check(ret)) {
+ PyErr_Format(
+ PyExc_TypeError, "return value must be a string, not %.200s", Py_TYPE(ret)->tp_name);
+ PyC_Err_PrintWithFunc(py_func);
+ value[0] = '\0';
+ Py_DECREF(ret);
+ }
+ else {
+ Py_ssize_t length;
+ const char *buffer = _PyUnicode_AsStringAndSize(ret, &length);
+ memcpy(value, buffer, length + 1);
+ Py_DECREF(ret);
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static int bpy_prop_string_length_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int length;
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
-
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- length = 0;
- }
- else if (!PyUnicode_Check(ret)) {
- PyErr_Format(PyExc_TypeError,
- "return value must be a string, not %.200s",
- Py_TYPE(ret)->tp_name);
- PyC_Err_PrintWithFunc(py_func);
- length = 0;
- Py_DECREF(ret);
- }
- else {
- Py_ssize_t length_ssize_t = 0;
- _PyUnicode_AsStringAndSize(ret, &length_ssize_t);
- length = length_ssize_t;
- Py_DECREF(ret);
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
-
- return length;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int length;
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
+
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ length = 0;
+ }
+ else if (!PyUnicode_Check(ret)) {
+ PyErr_Format(
+ PyExc_TypeError, "return value must be a string, not %.200s", Py_TYPE(ret)->tp_name);
+ PyC_Err_PrintWithFunc(py_func);
+ length = 0;
+ Py_DECREF(ret);
+ }
+ else {
+ Py_ssize_t length_ssize_t = 0;
+ _PyUnicode_AsStringAndSize(ret, &length_ssize_t);
+ length = length_ssize_t;
+ Py_DECREF(ret);
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
+
+ return length;
}
-static void bpy_prop_string_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const char *value)
+static void bpy_prop_string_set_cb(struct PointerRNA *ptr,
+ struct PropertyRNA *prop,
+ const char *value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- PyObject *py_value;
-
- BLI_assert(py_data != NULL);
-
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
-
- use_gil = true; /* !PyC_IsInterpreterActive(); */
-
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
-
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
-
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- py_value = PyUnicode_FromString(value);
- if (!py_value) {
- PyErr_SetString(PyExc_ValueError, "the return value must be a string");
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- PyTuple_SET_ITEM(args, 1, py_value);
- }
-
- ret = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
-
- Py_DECREF(ret);
- }
-
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
-
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ PyObject *py_value;
+
+ BLI_assert(py_data != NULL);
+
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
+
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
+
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
+
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
+
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ py_value = PyUnicode_FromString(value);
+ if (!py_value) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be a string");
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ PyTuple_SET_ITEM(args, 1, py_value);
+ }
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
+
+ Py_DECREF(ret);
+ }
+
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
+
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
static int bpy_prop_enum_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
- int value;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
+ int value;
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_GET];
+ py_func = py_data[BPY_DATA_CB_SLOT_GET];
- args = PyTuple_New(1);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(1);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- value = RNA_property_enum_get_default(ptr, prop);
- }
- else {
- value = PyC_Long_AsI32(ret);
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = RNA_property_enum_get_default(ptr, prop);
+ }
+ else {
+ value = PyC_Long_AsI32(ret);
- if (value == -1 && PyErr_Occurred()) {
- PyC_Err_PrintWithFunc(py_func);
- value = RNA_property_enum_get_default(ptr, prop);
- }
+ if (value == -1 && PyErr_Occurred()) {
+ PyC_Err_PrintWithFunc(py_func);
+ value = RNA_property_enum_get_default(ptr, prop);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
- return value;
+ return value;
}
static void bpy_prop_enum_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- PyObject *py_func;
- PyObject *args;
- PyObject *self;
- PyObject *ret;
- PyGILState_STATE gilstate;
- bool use_gil;
- const bool is_write_ok = pyrna_write_check();
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *py_func;
+ PyObject *args;
+ PyObject *self;
+ PyObject *ret;
+ PyGILState_STATE gilstate;
+ bool use_gil;
+ const bool is_write_ok = pyrna_write_check();
- BLI_assert(py_data != NULL);
+ BLI_assert(py_data != NULL);
- if (!is_write_ok) {
- pyrna_write_set(true);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(true);
+ }
- use_gil = true; /* !PyC_IsInterpreterActive(); */
+ use_gil = true; /* !PyC_IsInterpreterActive(); */
- if (use_gil) {
- gilstate = PyGILState_Ensure();
- }
+ if (use_gil) {
+ gilstate = PyGILState_Ensure();
+ }
- py_func = py_data[BPY_DATA_CB_SLOT_SET];
+ py_func = py_data[BPY_DATA_CB_SLOT_SET];
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
- PyTuple_SET_ITEM(args, 1, PyLong_FromLong(value));
+ PyTuple_SET_ITEM(args, 1, PyLong_FromLong(value));
- ret = PyObject_CallObject(py_func, args);
+ ret = PyObject_CallObject(py_func, args);
- Py_DECREF(args);
+ Py_DECREF(args);
- if (ret == NULL) {
- PyC_Err_PrintWithFunc(py_func);
- }
- else {
- if (ret != Py_None) {
- PyErr_SetString(PyExc_ValueError, "the return value must be None");
- PyC_Err_PrintWithFunc(py_func);
- }
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ }
+ else {
+ if (ret != Py_None) {
+ PyErr_SetString(PyExc_ValueError, "the return value must be None");
+ PyC_Err_PrintWithFunc(py_func);
+ }
- Py_DECREF(ret);
- }
+ Py_DECREF(ret);
+ }
- if (use_gil) {
- PyGILState_Release(gilstate);
- }
+ if (use_gil) {
+ PyGILState_Release(gilstate);
+ }
- if (!is_write_ok) {
- pyrna_write_set(false);
- }
+ if (!is_write_ok) {
+ pyrna_write_set(false);
+ }
}
/* utility function we need for parsing int's in an if statement */
static int py_long_as_int(PyObject *py_long, int *r_int)
{
- if (PyLong_CheckExact(py_long)) {
- *r_int = (int)PyLong_AS_LONG(py_long);
- return 0;
- }
- else {
- return -1;
- }
+ if (PyLong_CheckExact(py_long)) {
+ *r_int = (int)PyLong_AS_LONG(py_long);
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
#if 0
/* copies orig to buf, then sets orig to buf, returns copy length */
static size_t strswapbufcpy(char *buf, const char **orig)
{
- const char *src = *orig;
- char *dst = buf;
- size_t i = 0;
- *orig = buf;
- while ((*dst = *src)) { dst++; src++; i++; }
- return i + 1; /* include '\0' */
+ const char *src = *orig;
+ char *dst = buf;
+ size_t i = 0;
+ *orig = buf;
+ while ((*dst = *src)) { dst++; src++; i++; }
+ return i + 1; /* include '\0' */
}
#endif
static int icon_id_from_name(const char *name)
{
- const EnumPropertyItem *item;
- int id;
-
- if (name[0]) {
- for (item = rna_enum_icon_items, id = 0; item->identifier; item++, id++) {
- if (STREQ(item->name, name)) {
- return item->value;
- }
- }
- }
-
- return 0;
+ const EnumPropertyItem *item;
+ int id;
+
+ if (name[0]) {
+ for (item = rna_enum_icon_items, id = 0; item->identifier; item++, id++) {
+ if (STREQ(item->name, name)) {
+ return item->value;
+ }
+ }
+ }
+
+ return 0;
}
-static const EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const bool is_enum_flag)
+static const EnumPropertyItem *enum_items_from_py(PyObject *seq_fast,
+ PyObject *def,
+ int *defvalue,
+ const bool is_enum_flag)
{
- EnumPropertyItem *items;
- PyObject *item;
- const Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq_fast);
- PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
- Py_ssize_t totbuf = 0;
- int i;
- short def_used = 0;
- const char *def_cmp = NULL;
-
- if (is_enum_flag) {
- if (seq_len > RNA_ENUM_BITFLAG_SIZE) {
- PyErr_SetString(PyExc_TypeError,
- "EnumProperty(...): maximum "
- STRINGIFY(RNA_ENUM_BITFLAG_SIZE)
- " members for a ENUM_FLAG type property");
- return NULL;
- }
- if (def && !PySet_Check(def)) {
- PyErr_Format(PyExc_TypeError,
- "EnumProperty(...): default option must be a 'set' "
- "type when ENUM_FLAG is enabled, not a '%.200s'",
- Py_TYPE(def)->tp_name);
- return NULL;
- }
- }
- else {
- if (def) {
- def_cmp = _PyUnicode_AsString(def);
- if (def_cmp == NULL) {
- PyErr_Format(PyExc_TypeError,
- "EnumProperty(...): default option must be a 'str' "
- "type when ENUM_FLAG is disabled, not a '%.200s'",
- Py_TYPE(def)->tp_name);
- return NULL;
- }
- }
- }
-
- /* blank value */
- *defvalue = 0;
-
- items = MEM_callocN(sizeof(EnumPropertyItem) * (seq_len + 1), "enum_items_from_py1");
-
- for (i = 0; i < seq_len; i++) {
- EnumPropertyItem tmp = {0, "", 0, "", ""};
- const char *tmp_icon = NULL;
- Py_ssize_t item_size;
- Py_ssize_t id_str_size;
- Py_ssize_t name_str_size;
- Py_ssize_t desc_str_size;
-
- item = seq_fast_items[i];
-
- if ((PyTuple_CheckExact(item)) &&
- (item_size = PyTuple_GET_SIZE(item)) &&
- (item_size >= 3 && item_size <= 5) &&
- (tmp.identifier = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 0), &id_str_size)) &&
- (tmp.name = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 1), &name_str_size)) &&
- (tmp.description = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 2), &desc_str_size)) &&
- /* TODO, number isn't ensured to be unique from the script author */
- (item_size != 4 || py_long_as_int(PyTuple_GET_ITEM(item, 3), &tmp.value) != -1) &&
- (item_size != 5 || ((py_long_as_int(PyTuple_GET_ITEM(item, 3), &tmp.icon) != -1 ||
- (tmp_icon = _PyUnicode_AsString(PyTuple_GET_ITEM(item, 3)))) &&
- py_long_as_int(PyTuple_GET_ITEM(item, 4), &tmp.value) != -1)))
- {
- if (is_enum_flag) {
- if (item_size < 4) {
- tmp.value = 1 << i;
- }
-
- if (def && PySet_Contains(def, PyTuple_GET_ITEM(item, 0))) {
- *defvalue |= tmp.value;
- def_used++;
- }
- }
- else {
- if (item_size < 4) {
- tmp.value = i;
- }
-
- if (def && def_used == 0 && STREQ(def_cmp, tmp.identifier)) {
- *defvalue = tmp.value;
- def_used++; /* only ever 1 */
- }
- }
-
- if (tmp_icon) {
- tmp.icon = icon_id_from_name(tmp_icon);
- }
-
- items[i] = tmp;
-
- /* calculate combine string length */
- totbuf += id_str_size + name_str_size + desc_str_size + 3; /* 3 is for '\0's */
- }
- else {
- MEM_freeN(items);
- PyErr_SetString(PyExc_TypeError,
- "EnumProperty(...): expected a tuple containing "
- "(identifier, name, description) and optionally an "
- "icon name and unique number");
- return NULL;
- }
-
- }
-
- if (is_enum_flag) {
- /* strict check that all set members were used */
- if (def && def_used != PySet_GET_SIZE(def)) {
- MEM_freeN(items);
-
- PyErr_Format(PyExc_TypeError,
- "EnumProperty(..., default={...}): set has %d unused member(s)",
- PySet_GET_SIZE(def) - def_used);
- return NULL;
- }
- }
- else {
- if (def && def_used == 0) {
- MEM_freeN(items);
-
- PyErr_Format(PyExc_TypeError,
- "EnumProperty(..., default=\'%s\'): not found in enum members",
- def_cmp);
- return NULL;
- }
- }
-
- /* disabled duplicating strings because the array can still be freed and
- * the strings from it referenced, for now we can't support dynamically
- * created strings from python. */
+ EnumPropertyItem *items;
+ PyObject *item;
+ const Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq_fast);
+ PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
+ Py_ssize_t totbuf = 0;
+ int i;
+ short def_used = 0;
+ const char *def_cmp = NULL;
+
+ if (is_enum_flag) {
+ if (seq_len > RNA_ENUM_BITFLAG_SIZE) {
+ PyErr_SetString(PyExc_TypeError,
+ "EnumProperty(...): maximum " STRINGIFY(
+ RNA_ENUM_BITFLAG_SIZE) " members for a ENUM_FLAG type property");
+ return NULL;
+ }
+ if (def && !PySet_Check(def)) {
+ PyErr_Format(PyExc_TypeError,
+ "EnumProperty(...): default option must be a 'set' "
+ "type when ENUM_FLAG is enabled, not a '%.200s'",
+ Py_TYPE(def)->tp_name);
+ return NULL;
+ }
+ }
+ else {
+ if (def) {
+ def_cmp = _PyUnicode_AsString(def);
+ if (def_cmp == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "EnumProperty(...): default option must be a 'str' "
+ "type when ENUM_FLAG is disabled, not a '%.200s'",
+ Py_TYPE(def)->tp_name);
+ return NULL;
+ }
+ }
+ }
+
+ /* blank value */
+ *defvalue = 0;
+
+ items = MEM_callocN(sizeof(EnumPropertyItem) * (seq_len + 1), "enum_items_from_py1");
+
+ for (i = 0; i < seq_len; i++) {
+ EnumPropertyItem tmp = {0, "", 0, "", ""};
+ const char *tmp_icon = NULL;
+ Py_ssize_t item_size;
+ Py_ssize_t id_str_size;
+ Py_ssize_t name_str_size;
+ Py_ssize_t desc_str_size;
+
+ item = seq_fast_items[i];
+
+ if ((PyTuple_CheckExact(item)) && (item_size = PyTuple_GET_SIZE(item)) &&
+ (item_size >= 3 && item_size <= 5) &&
+ (tmp.identifier = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 0), &id_str_size)) &&
+ (tmp.name = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 1), &name_str_size)) &&
+ (tmp.description = _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 2),
+ &desc_str_size)) &&
+ /* TODO, number isn't ensured to be unique from the script author */
+ (item_size != 4 || py_long_as_int(PyTuple_GET_ITEM(item, 3), &tmp.value) != -1) &&
+ (item_size != 5 || ((py_long_as_int(PyTuple_GET_ITEM(item, 3), &tmp.icon) != -1 ||
+ (tmp_icon = _PyUnicode_AsString(PyTuple_GET_ITEM(item, 3)))) &&
+ py_long_as_int(PyTuple_GET_ITEM(item, 4), &tmp.value) != -1))) {
+ if (is_enum_flag) {
+ if (item_size < 4) {
+ tmp.value = 1 << i;
+ }
+
+ if (def && PySet_Contains(def, PyTuple_GET_ITEM(item, 0))) {
+ *defvalue |= tmp.value;
+ def_used++;
+ }
+ }
+ else {
+ if (item_size < 4) {
+ tmp.value = i;
+ }
+
+ if (def && def_used == 0 && STREQ(def_cmp, tmp.identifier)) {
+ *defvalue = tmp.value;
+ def_used++; /* only ever 1 */
+ }
+ }
+
+ if (tmp_icon) {
+ tmp.icon = icon_id_from_name(tmp_icon);
+ }
+
+ items[i] = tmp;
+
+ /* calculate combine string length */
+ totbuf += id_str_size + name_str_size + desc_str_size + 3; /* 3 is for '\0's */
+ }
+ else {
+ MEM_freeN(items);
+ PyErr_SetString(PyExc_TypeError,
+ "EnumProperty(...): expected a tuple containing "
+ "(identifier, name, description) and optionally an "
+ "icon name and unique number");
+ return NULL;
+ }
+ }
+
+ if (is_enum_flag) {
+ /* strict check that all set members were used */
+ if (def && def_used != PySet_GET_SIZE(def)) {
+ MEM_freeN(items);
+
+ PyErr_Format(PyExc_TypeError,
+ "EnumProperty(..., default={...}): set has %d unused member(s)",
+ PySet_GET_SIZE(def) - def_used);
+ return NULL;
+ }
+ }
+ else {
+ if (def && def_used == 0) {
+ MEM_freeN(items);
+
+ PyErr_Format(PyExc_TypeError,
+ "EnumProperty(..., default=\'%s\'): not found in enum members",
+ def_cmp);
+ return NULL;
+ }
+ }
+
+ /* disabled duplicating strings because the array can still be freed and
+ * the strings from it referenced, for now we can't support dynamically
+ * created strings from python. */
#if 0
- /* this would all work perfectly _but_ the python strings may be freed
- * immediately after use, so we need to duplicate them, ugh.
- * annoying because it works most of the time without this. */
- {
- EnumPropertyItem *items_dup = MEM_mallocN((sizeof(EnumPropertyItem) * (seq_len + 1)) + (sizeof(char) * totbuf),
- "enum_items_from_py2");
- EnumPropertyItem *items_ptr = items_dup;
- char *buf = ((char *)items_dup) + (sizeof(EnumPropertyItem) * (seq_len + 1));
- memcpy(items_dup, items, sizeof(EnumPropertyItem) * (seq_len + 1));
- for (i = 0; i < seq_len; i++, items_ptr++) {
- buf += strswapbufcpy(buf, &items_ptr->identifier);
- buf += strswapbufcpy(buf, &items_ptr->name);
- buf += strswapbufcpy(buf, &items_ptr->description);
- }
- MEM_freeN(items);
- items = items_dup;
- }
- /* end string duplication */
+ /* this would all work perfectly _but_ the python strings may be freed
+ * immediately after use, so we need to duplicate them, ugh.
+ * annoying because it works most of the time without this. */
+ {
+ EnumPropertyItem *items_dup = MEM_mallocN((sizeof(EnumPropertyItem) * (seq_len + 1)) + (sizeof(char) * totbuf),
+ "enum_items_from_py2");
+ EnumPropertyItem *items_ptr = items_dup;
+ char *buf = ((char *)items_dup) + (sizeof(EnumPropertyItem) * (seq_len + 1));
+ memcpy(items_dup, items, sizeof(EnumPropertyItem) * (seq_len + 1));
+ for (i = 0; i < seq_len; i++, items_ptr++) {
+ buf += strswapbufcpy(buf, &items_ptr->identifier);
+ buf += strswapbufcpy(buf, &items_ptr->name);
+ buf += strswapbufcpy(buf, &items_ptr->description);
+ }
+ MEM_freeN(items);
+ items = items_dup;
+ }
+ /* end string duplication */
#endif
- return items;
+ return items;
}
-static const EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ bool *r_free)
{
- PyGILState_STATE gilstate;
-
- PyObject *py_func = RNA_property_enum_py_data_get(prop);
- PyObject *self = NULL;
- PyObject *args;
- PyObject *items; /* returned from the function call */
-
- const EnumPropertyItem *eitems = NULL;
- int err = 0;
-
- if (C) {
- bpy_context_set(C, &gilstate);
- }
- else {
- gilstate = PyGILState_Ensure();
- }
-
- args = PyTuple_New(2);
- self = pyrna_struct_as_instance(ptr);
- PyTuple_SET_ITEM(args, 0, self);
-
- /* now get the context */
- if (C) {
- PyTuple_SET_ITEM(args, 1, (PyObject *)bpy_context_module);
- Py_INCREF(bpy_context_module);
- }
- else {
- PyTuple_SET_ITEM(args, 1, Py_None);
- Py_INCREF(Py_None);
- }
-
- items = PyObject_CallObject(py_func, args);
-
- Py_DECREF(args);
-
- if (items == NULL) {
- err = -1;
- }
- else {
- PyObject *items_fast;
- int defvalue_dummy = 0;
-
- if (!(items_fast = PySequence_Fast(items, "EnumProperty(...): "
- "return value from the callback was not a sequence")))
- {
- err = -1;
- }
- else {
- eitems = enum_items_from_py(items_fast, NULL, &defvalue_dummy,
- (RNA_property_flag(prop) & PROP_ENUM_FLAG) != 0);
-
- Py_DECREF(items_fast);
-
- if (!eitems) {
- err = -1;
- }
- }
-
- Py_DECREF(items);
- }
-
- if (err != -1) { /* worked */
- *r_free = true;
- }
- else {
- PyC_Err_PrintWithFunc(py_func);
-
- eitems = DummyRNA_NULL_items;
- }
-
- if (C) {
- bpy_context_clear(C, &gilstate);
- }
- else {
- PyGILState_Release(gilstate);
- }
-
- return eitems;
+ PyGILState_STATE gilstate;
+
+ PyObject *py_func = RNA_property_enum_py_data_get(prop);
+ PyObject *self = NULL;
+ PyObject *args;
+ PyObject *items; /* returned from the function call */
+
+ const EnumPropertyItem *eitems = NULL;
+ int err = 0;
+
+ if (C) {
+ bpy_context_set(C, &gilstate);
+ }
+ else {
+ gilstate = PyGILState_Ensure();
+ }
+
+ args = PyTuple_New(2);
+ self = pyrna_struct_as_instance(ptr);
+ PyTuple_SET_ITEM(args, 0, self);
+
+ /* now get the context */
+ if (C) {
+ PyTuple_SET_ITEM(args, 1, (PyObject *)bpy_context_module);
+ Py_INCREF(bpy_context_module);
+ }
+ else {
+ PyTuple_SET_ITEM(args, 1, Py_None);
+ Py_INCREF(Py_None);
+ }
+
+ items = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (items == NULL) {
+ err = -1;
+ }
+ else {
+ PyObject *items_fast;
+ int defvalue_dummy = 0;
+
+ if (!(items_fast = PySequence_Fast(items,
+ "EnumProperty(...): "
+ "return value from the callback was not a sequence"))) {
+ err = -1;
+ }
+ else {
+ eitems = enum_items_from_py(
+ items_fast, NULL, &defvalue_dummy, (RNA_property_flag(prop) & PROP_ENUM_FLAG) != 0);
+
+ Py_DECREF(items_fast);
+
+ if (!eitems) {
+ err = -1;
+ }
+ }
+
+ Py_DECREF(items);
+ }
+
+ if (err != -1) { /* worked */
+ *r_free = true;
+ }
+ else {
+ PyC_Err_PrintWithFunc(py_func);
+
+ eitems = DummyRNA_NULL_items;
+ }
+
+ if (C) {
+ bpy_context_clear(C, &gilstate);
+ }
+ else {
+ PyGILState_Release(gilstate);
+ }
+
+ return eitems;
}
static int bpy_prop_callback_check(PyObject *py_func, const char *keyword, int argcount)
{
- if (py_func && py_func != Py_None) {
- if (!PyFunction_Check(py_func)) {
- PyErr_Format(PyExc_TypeError,
- "%s keyword: expected a function type, not a %.200s",
- keyword, Py_TYPE(py_func)->tp_name);
- return -1;
- }
- else {
- PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
- if (f_code->co_argcount != argcount) {
- PyErr_Format(PyExc_TypeError,
- "%s keyword: expected a function taking %d arguments, not %d",
- keyword, argcount, f_code->co_argcount);
- return -1;
- }
- }
- }
-
- return 0;
+ if (py_func && py_func != Py_None) {
+ if (!PyFunction_Check(py_func)) {
+ PyErr_Format(PyExc_TypeError,
+ "%s keyword: expected a function type, not a %.200s",
+ keyword,
+ Py_TYPE(py_func)->tp_name);
+ return -1;
+ }
+ else {
+ PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
+ if (f_code->co_argcount != argcount) {
+ PyErr_Format(PyExc_TypeError,
+ "%s keyword: expected a function taking %d arguments, not %d",
+ keyword,
+ argcount,
+ f_code->co_argcount);
+ return -1;
+ }
+ }
+ }
+
+ return 0;
}
static PyObject **bpy_prop_py_data_get(struct PropertyRNA *prop)
{
- PyObject **py_data = RNA_property_py_data_get(prop);
- if (!py_data) {
- py_data = MEM_callocN(sizeof(PyObject *) * BPY_DATA_CB_SLOT_SIZE, __func__);
- RNA_def_py_data(prop, py_data);
- }
- return py_data;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ if (!py_data) {
+ py_data = MEM_callocN(sizeof(PyObject *) * BPY_DATA_CB_SLOT_SIZE, __func__);
+ RNA_def_py_data(prop, py_data);
+ }
+ return py_data;
}
static void bpy_prop_callback_assign_update(struct PropertyRNA *prop, PyObject *update_cb)
{
- /* assume this is already checked for type and arg length */
- if (update_cb && update_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ /* assume this is already checked for type and arg length */
+ if (update_cb && update_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- RNA_def_property_update_runtime(prop, (void *)bpy_prop_update_cb);
- py_data[BPY_DATA_CB_SLOT_UPDATE] = update_cb;
+ RNA_def_property_update_runtime(prop, (void *)bpy_prop_update_cb);
+ py_data[BPY_DATA_CB_SLOT_UPDATE] = update_cb;
- RNA_def_property_flag(prop, PROP_CONTEXT_PROPERTY_UPDATE);
- }
+ RNA_def_property_flag(prop, PROP_CONTEXT_PROPERTY_UPDATE);
+ }
}
static void bpy_prop_callback_assign_pointer(struct PropertyRNA *prop, PyObject *poll_cb)
{
- if (poll_cb && poll_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (poll_cb && poll_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- RNA_def_property_poll_runtime(prop, (void *) bpy_prop_poll_cb);
- py_data[BPY_DATA_CB_SLOT_POLL] = poll_cb;
- }
+ RNA_def_property_poll_runtime(prop, (void *)bpy_prop_poll_cb);
+ py_data[BPY_DATA_CB_SLOT_POLL] = poll_cb;
+ }
}
-static void bpy_prop_callback_assign_boolean(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_boolean(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- BooleanPropertyGetFunc rna_get_cb = NULL;
- BooleanPropertySetFunc rna_set_cb = NULL;
+ BooleanPropertyGetFunc rna_get_cb = NULL;
+ BooleanPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_boolean_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_boolean_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_boolean_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_boolean_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_boolean_funcs_runtime(prop, rna_get_cb, rna_set_cb);
+ RNA_def_property_boolean_funcs_runtime(prop, rna_get_cb, rna_set_cb);
}
-static void bpy_prop_callback_assign_boolean_array(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_boolean_array(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- BooleanArrayPropertyGetFunc rna_get_cb = NULL;
- BooleanArrayPropertySetFunc rna_set_cb = NULL;
+ BooleanArrayPropertyGetFunc rna_get_cb = NULL;
+ BooleanArrayPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_boolean_array_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_boolean_array_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_boolean_array_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_boolean_array_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_boolean_array_funcs_runtime(prop, rna_get_cb, rna_set_cb);
+ RNA_def_property_boolean_array_funcs_runtime(prop, rna_get_cb, rna_set_cb);
}
-static void bpy_prop_callback_assign_int(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_int(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- IntPropertyGetFunc rna_get_cb = NULL;
- IntPropertySetFunc rna_set_cb = NULL;
+ IntPropertyGetFunc rna_get_cb = NULL;
+ IntPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_int_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_int_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_int_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_int_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_int_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
+ RNA_def_property_int_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
}
-static void bpy_prop_callback_assign_int_array(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_int_array(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- IntArrayPropertyGetFunc rna_get_cb = NULL;
- IntArrayPropertySetFunc rna_set_cb = NULL;
+ IntArrayPropertyGetFunc rna_get_cb = NULL;
+ IntArrayPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_int_array_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_int_array_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_int_array_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_int_array_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_int_array_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
+ RNA_def_property_int_array_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
}
-static void bpy_prop_callback_assign_float(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_float(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- FloatPropertyGetFunc rna_get_cb = NULL;
- FloatPropertySetFunc rna_set_cb = NULL;
+ FloatPropertyGetFunc rna_get_cb = NULL;
+ FloatPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_float_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_float_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_float_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_float_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_float_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
+ RNA_def_property_float_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
}
-static void bpy_prop_callback_assign_float_array(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_float_array(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- FloatArrayPropertyGetFunc rna_get_cb = NULL;
- FloatArrayPropertySetFunc rna_set_cb = NULL;
+ FloatArrayPropertyGetFunc rna_get_cb = NULL;
+ FloatArrayPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_float_array_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_float_array_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_float_array_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_float_array_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_float_array_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
+ RNA_def_property_float_array_funcs_runtime(prop, rna_get_cb, rna_set_cb, NULL);
}
-static void bpy_prop_callback_assign_string(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
+static void bpy_prop_callback_assign_string(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb)
{
- StringPropertyGetFunc rna_get_cb = NULL;
- StringPropertyLengthFunc rna_length_cb = NULL;
- StringPropertySetFunc rna_set_cb = NULL;
+ StringPropertyGetFunc rna_get_cb = NULL;
+ StringPropertyLengthFunc rna_length_cb = NULL;
+ StringPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_string_get_cb;
- rna_length_cb = bpy_prop_string_length_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_string_get_cb;
+ rna_length_cb = bpy_prop_string_length_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_string_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_string_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- RNA_def_property_string_funcs_runtime(prop, rna_get_cb, rna_length_cb, rna_set_cb);
+ RNA_def_property_string_funcs_runtime(prop, rna_get_cb, rna_length_cb, rna_set_cb);
}
-static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb, PyObject *itemf_cb)
+static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop,
+ PyObject *get_cb,
+ PyObject *set_cb,
+ PyObject *itemf_cb)
{
- EnumPropertyGetFunc rna_get_cb = NULL;
- EnumPropertyItemFunc rna_itemf_cb = NULL;
- EnumPropertySetFunc rna_set_cb = NULL;
+ EnumPropertyGetFunc rna_get_cb = NULL;
+ EnumPropertyItemFunc rna_itemf_cb = NULL;
+ EnumPropertySetFunc rna_set_cb = NULL;
- if (get_cb && get_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (get_cb && get_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_get_cb = bpy_prop_enum_get_cb;
- py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
- }
+ rna_get_cb = bpy_prop_enum_get_cb;
+ py_data[BPY_DATA_CB_SLOT_GET] = get_cb;
+ }
- if (set_cb && set_cb != Py_None) {
- PyObject **py_data = bpy_prop_py_data_get(prop);
+ if (set_cb && set_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
- rna_set_cb = bpy_prop_enum_set_cb;
- py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
- }
+ rna_set_cb = bpy_prop_enum_set_cb;
+ py_data[BPY_DATA_CB_SLOT_SET] = set_cb;
+ }
- if (itemf_cb && itemf_cb != Py_None) {
- rna_itemf_cb = bpy_prop_enum_itemf_cb;
- RNA_def_property_enum_py_data(prop, (void *)itemf_cb);
+ if (itemf_cb && itemf_cb != Py_None) {
+ rna_itemf_cb = bpy_prop_enum_itemf_cb;
+ RNA_def_property_enum_py_data(prop, (void *)itemf_cb);
- /* watch out!, if a user is tricky they can probably crash blender
- * if they manage to free the callback, take care! */
- /* Py_INCREF(itemf_cb); */
- }
+ /* watch out!, if a user is tricky they can probably crash blender
+ * if they manage to free the callback, take care! */
+ /* Py_INCREF(itemf_cb); */
+ }
- RNA_def_property_enum_funcs_runtime(prop, rna_get_cb, rna_set_cb, rna_itemf_cb);
+ RNA_def_property_enum_funcs_runtime(prop, rna_get_cb, rna_set_cb, rna_itemf_cb);
}
/* this define runs at the start of each function and deals with
* returning a deferred property (to be registered later) */
-#define BPY_PROPDEF_HEAD(_func) \
- if (PyTuple_GET_SIZE(args) == 1) { \
- PyObject *ret; \
- self = PyTuple_GET_ITEM(args, 0); \
- args = PyTuple_New(0); \
- ret = BPy_##_func(self, args, kw); \
- Py_DECREF(args); \
- return ret; \
- } \
- else if (PyTuple_GET_SIZE(args) > 1) { \
- PyErr_SetString(PyExc_ValueError, "all args must be keywords"); \
- return NULL; \
- } \
- srna = srna_from_self(self, #_func"(...):"); \
- if (srna == NULL) { \
- if (PyErr_Occurred()) \
- return NULL; \
- return bpy_prop_deferred_return(pymeth_##_func, kw); \
- } (void)0
+#define BPY_PROPDEF_HEAD(_func) \
+ if (PyTuple_GET_SIZE(args) == 1) { \
+ PyObject *ret; \
+ self = PyTuple_GET_ITEM(args, 0); \
+ args = PyTuple_New(0); \
+ ret = BPy_##_func(self, args, kw); \
+ Py_DECREF(args); \
+ return ret; \
+ } \
+ else if (PyTuple_GET_SIZE(args) > 1) { \
+ PyErr_SetString(PyExc_ValueError, "all args must be keywords"); \
+ return NULL; \
+ } \
+ srna = srna_from_self(self, #_func "(...):"); \
+ if (srna == NULL) { \
+ if (PyErr_Occurred()) \
+ return NULL; \
+ return bpy_prop_deferred_return(pymeth_##_func, kw); \
+ } \
+ (void)0
/* terse macros for error checks shared between all funcs cant use function
* calls because of static strings passed to pyrna_set_to_enum_bitfield */
-#define BPY_PROPDEF_CHECK(_func, _property_flag_items) \
- if (UNLIKELY(id_len >= MAX_IDPROP_NAME)) { \
- PyErr_Format(PyExc_TypeError, \
- #_func"(): '%.200s' too long, max length is %d", \
- id, MAX_IDPROP_NAME - 1); \
- return NULL; \
- } \
- if (UNLIKELY(RNA_def_property_free_identifier(srna, id) == -1)) { \
- PyErr_Format(PyExc_TypeError, \
- #_func"(): '%s' is defined as a non-dynamic type", \
- id); \
- return NULL; \
- } \
- if (UNLIKELY(pyopts && pyrna_set_to_enum_bitfield(_property_flag_items, \
- pyopts, \
- &opts, \
- #_func"(options={ ...}):"))) \
- { \
- return NULL; \
- } \
- { \
- const EnumPropertyItem *tag_defines = RNA_struct_property_tag_defines(srna); \
- if (py_tags && !tag_defines) { \
- PyErr_Format(PyExc_TypeError, \
- #_func"(): property-tags not available for '%s'", \
- RNA_struct_identifier(srna)); \
- return NULL; \
- } \
- if (UNLIKELY(py_tags && pyrna_set_to_enum_bitfield( \
- tag_defines, py_tags, \
- &prop_tags, #_func"(tags={ ...}):"))) \
- { \
- return NULL; \
- } \
- }(void)0
-
-#define BPY_PROPDEF_SUBTYPE_CHECK(_func, _property_flag_items, _subtype) \
- BPY_PROPDEF_CHECK(_func, _property_flag_items); \
- if (UNLIKELY(pysubtype && RNA_enum_value_from_id(_subtype, \
- pysubtype, \
- &subtype) == 0)) \
- { \
- const char *enum_str = BPy_enum_as_string(_subtype); \
- PyErr_Format(PyExc_TypeError, \
- #_func"(subtype='%s'): " \
- "subtype not found in (%s)", \
- pysubtype, enum_str); \
- MEM_freeN((void *)enum_str); \
- return NULL; \
- } (void)0
-
+#define BPY_PROPDEF_CHECK(_func, _property_flag_items) \
+ if (UNLIKELY(id_len >= MAX_IDPROP_NAME)) { \
+ PyErr_Format(PyExc_TypeError, \
+ #_func "(): '%.200s' too long, max length is %d", \
+ id, \
+ MAX_IDPROP_NAME - 1); \
+ return NULL; \
+ } \
+ if (UNLIKELY(RNA_def_property_free_identifier(srna, id) == -1)) { \
+ PyErr_Format(PyExc_TypeError, #_func "(): '%s' is defined as a non-dynamic type", id); \
+ return NULL; \
+ } \
+ if (UNLIKELY(pyopts && pyrna_set_to_enum_bitfield( \
+ _property_flag_items, pyopts, &opts, #_func "(options={ ...}):"))) { \
+ return NULL; \
+ } \
+ { \
+ const EnumPropertyItem *tag_defines = RNA_struct_property_tag_defines(srna); \
+ if (py_tags && !tag_defines) { \
+ PyErr_Format(PyExc_TypeError, \
+ #_func "(): property-tags not available for '%s'", \
+ RNA_struct_identifier(srna)); \
+ return NULL; \
+ } \
+ if (UNLIKELY(py_tags && pyrna_set_to_enum_bitfield( \
+ tag_defines, py_tags, &prop_tags, #_func "(tags={ ...}):"))) { \
+ return NULL; \
+ } \
+ } \
+ (void)0
+
+#define BPY_PROPDEF_SUBTYPE_CHECK(_func, _property_flag_items, _subtype) \
+ BPY_PROPDEF_CHECK(_func, _property_flag_items); \
+ if (UNLIKELY(pysubtype && RNA_enum_value_from_id(_subtype, pysubtype, &subtype) == 0)) { \
+ const char *enum_str = BPy_enum_as_string(_subtype); \
+ PyErr_Format(PyExc_TypeError, \
+ #_func \
+ "(subtype='%s'): " \
+ "subtype not found in (%s)", \
+ pysubtype, \
+ enum_str); \
+ MEM_freeN((void *)enum_str); \
+ return NULL; \
+ } \
+ (void)0
#define BPY_PROPDEF_NAME_DOC \
-" :arg name: Name used in the user interface.\n" \
-" :type name: string\n" \
+ " :arg name: Name used in the user interface.\n" \
+ " :type name: string\n"
#define BPY_PROPDEF_DESC_DOC \
-" :arg description: Text used for the tooltip and api documentation.\n" \
-" :type description: string\n" \
+ " :arg description: Text used for the tooltip and api documentation.\n" \
+ " :type description: string\n"
#define BPY_PROPDEF_UNIT_DOC \
-" :arg unit: Enumerator in ['NONE', 'LENGTH', 'AREA', 'VOLUME', 'ROTATION', 'TIME', 'VELOCITY', 'ACCELERATION', 'MASS', 'CAMERA', 'POWER'].\n" \
-" :type unit: string\n" \
+ " :arg unit: Enumerator in ['NONE', 'LENGTH', 'AREA', 'VOLUME', 'ROTATION', 'TIME', " \
+ "'VELOCITY', 'ACCELERATION', 'MASS', 'CAMERA', 'POWER'].\n" \
+ " :type unit: string\n"
#define BPY_PROPDEF_NUM_MIN_DOC \
-" :arg min: Hard minimum, trying to assign a value below will silently assign this minimum instead.\n" \
+ " :arg min: Hard minimum, trying to assign a value below will silently assign this minimum " \
+ "instead.\n"
#define BPY_PROPDEF_NUM_MAX_DOC \
-" :arg max: Hard maximum, trying to assign a value above will silently assign this maximum instead.\n" \
+ " :arg max: Hard maximum, trying to assign a value above will silently assign this maximum " \
+ "instead.\n"
#define BPY_PROPDEF_NUM_SOFTMIN_DOC \
-" :arg soft_min: Soft minimum (>= *min*), user won't be able to drag the widget below this value in the UI.\n" \
+ " :arg soft_min: Soft minimum (>= *min*), user won't be able to drag the widget below this " \
+ "value in the UI.\n"
#define BPY_PROPDEF_NUM_SOFTMAX_DOC \
-" :arg soft_max: Soft maximum (<= *max*), user won't be able to drag the widget above this value in the UI.\n" \
+ " :arg soft_max: Soft maximum (<= *max*), user won't be able to drag the widget above this " \
+ "value in the UI.\n"
#define BPY_PROPDEF_VECSIZE_DOC \
-" :arg size: Vector dimensions in [1, " STRINGIFY(PYRNA_STACK_ARRAY) "].\n" \
-" :type size: int\n" \
+ " :arg size: Vector dimensions in [1, " STRINGIFY(PYRNA_STACK_ARRAY) "].\n" \
+" :type size: int\n"
#define BPY_PROPDEF_INT_STEP_DOC \
-" :arg step: Step of increment/decrement in UI, in [1, 100], defaults to 1 (WARNING: unused currently!).\n" \
-" :type step: int\n" \
+ " :arg step: Step of increment/decrement in UI, in [1, 100], defaults to 1 (WARNING: unused " \
+ "currently!).\n" \
+ " :type step: int\n"
#define BPY_PROPDEF_FLOAT_STEP_DOC \
-" :arg step: Step of increment/decrement in UI, in [1, 100], defaults to 3 (WARNING: actual value is /100).\n" \
-" :type step: int\n" \
+ " :arg step: Step of increment/decrement in UI, in [1, 100], defaults to 3 (WARNING: actual " \
+ "value is /100).\n" \
+ " :type step: int\n"
#define BPY_PROPDEF_FLOAT_PREC_DOC \
-" :arg precision: Maximum number of decimal digits to display, in [0, 6].\n" \
-" :type precision: int\n" \
+ " :arg precision: Maximum number of decimal digits to display, in [0, 6].\n" \
+ " :type precision: int\n"
#define BPY_PROPDEF_UPDATE_DOC \
-" :arg update: Function to be called when this value is modified,\n" \
-" This function must take 2 values (self, context) and return None.\n" \
-" *Warning* there are no safety checks to avoid infinite recursion.\n" \
-" :type update: function\n" \
+ " :arg update: Function to be called when this value is modified,\n" \
+ " This function must take 2 values (self, context) and return None.\n" \
+ " *Warning* there are no safety checks to avoid infinite recursion.\n" \
+ " :type update: function\n"
#define BPY_PROPDEF_POLL_DOC \
-" :arg poll: function to be called to determine whether an item is valid for this property.\n" \
-" The function must take 2 values (self, object) and return Bool.\n" \
-" :type poll: function\n" \
+ " :arg poll: function to be called to determine whether an item is valid for this " \
+ "property.\n" \
+ " The function must take 2 values (self, object) and return Bool.\n" \
+ " :type poll: function\n"
#define BPY_PROPDEF_GET_DOC \
-" :arg get: Function to be called when this value is 'read',\n" \
-" This function must take 1 value (self) and return the value of the property.\n" \
-" :type get: function\n" \
+ " :arg get: Function to be called when this value is 'read',\n" \
+ " This function must take 1 value (self) and return the value of the property.\n" \
+ " :type get: function\n"
#define BPY_PROPDEF_SET_DOC \
-" :arg set: Function to be called when this value is 'written',\n" \
-" This function must take 2 values (self, value) and return None.\n" \
-" :type set: function\n" \
+ " :arg set: Function to be called when this value is 'written',\n" \
+ " This function must take 2 values (self, value) and return None.\n" \
+ " :type set: function\n"
#define BPY_PROPDEF_TYPE_DOC \
-" :arg type: A subclass of :class:`bpy.types.PropertyGroup` or :class:`bpy.types.ID`.\n" \
-" :type type: class\n" \
+ " :arg type: A subclass of :class:`bpy.types.PropertyGroup` or :class:`bpy.types.ID`.\n" \
+ " :type type: class\n"
#define BPY_PROPDEF_TAGS_DOC \
-" :arg tags: Enumerator of tags that are defined by parent class.\n" \
-" :type tags: set\n" \
+ " :arg tags: Enumerator of tags that are defined by parent class.\n" \
+ " :type tags: set\n"
#if 0
static int bpy_struct_id_used(StructRNA *srna, char *identifier)
{
- PointerRNA ptr;
- RNA_pointer_create(NULL, srna, NULL, &ptr);
- return (RNA_struct_find_property(&ptr, identifier) != NULL);
+ PointerRNA ptr;
+ RNA_pointer_create(NULL, srna, NULL, &ptr);
+ return (RNA_struct_find_property(&ptr, identifier) != NULL);
}
#endif
-
/* Function that sets RNA, NOTE - self is NULL when called from python,
* but being abused from C so we can pass the srna along.
* This isn't incorrect since its a python object - but be careful */
PyDoc_STRVAR(BPy_BoolProperty_doc,
-".. function:: BoolProperty(name=\"\", "
- "description=\"\", "
- "default=False, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new boolean property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_NUMBER_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: BoolProperty(name=\"\", "
+ "description=\"\", "
+ "default=False, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new boolean property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC BPY_PROPDEF_OPTIONS_DOC
+ BPY_PROPDEF_TAGS_DOC BPY_PROPDEF_SUBTYPE_NUMBER_DOC BPY_PROPDEF_UPDATE_DOC
+ BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(BoolProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- bool def = false;
- PropertyRNA *prop;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "options", "tags", "subtype",
- "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssO&O!O!sOOO:BoolProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, PyC_ParseBool, &def,
- &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(BoolProperty, property_flag_items, property_subtype_number_items);
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_BOOLEAN, subtype);
- RNA_def_property_boolean_default(prop, def);
- RNA_def_property_ui_text(prop, name ? name : id, description);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_boolean(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
-
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(BoolProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ bool def = false;
+ PropertyRNA *prop;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "options",
+ "tags",
+ "subtype",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssO&O!O!sOOO:BoolProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ PyC_ParseBool,
+ &def,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(BoolProperty, property_flag_items, property_subtype_number_items);
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_BOOLEAN, subtype);
+ RNA_def_property_boolean_default(prop, def);
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_boolean(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_BoolVectorProperty_doc,
-".. function:: BoolVectorProperty(name=\"\", "
- "description=\"\", "
- "default=(False, False, False), "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "size=3, "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new vector boolean property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-" :arg default: sequence of booleans the length of *size*.\n"
-" :type default: sequence\n"
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_ARRAY_DOC
-BPY_PROPDEF_VECSIZE_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: BoolVectorProperty(name=\"\", "
+ "description=\"\", "
+ "default=(False, False, False), "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "size=3, "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new vector boolean property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ " :arg default: sequence of booleans the length of *size*.\n"
+ " :type default: sequence\n" BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC
+ BPY_PROPDEF_SUBTYPE_ARRAY_DOC BPY_PROPDEF_VECSIZE_DOC BPY_PROPDEF_UPDATE_DOC
+ BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(BoolVectorProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- bool def[PYRNA_STACK_ARRAY] = {0};
- int size = 3;
- PropertyRNA *prop;
- PyObject *pydef = NULL;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "options", "tags", "subtype", "size",
- "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssOO!O!siOOO:BoolVectorProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &pydef,
- &PySet_Type, &pyopts, &PySet_Type, &py_tags,
- &pysubtype, &size,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(BoolVectorProperty, property_flag_items, property_subtype_array_items);
-
- if (size < 1 || size > PYRNA_STACK_ARRAY) {
- PyErr_Format(PyExc_TypeError,
- "BoolVectorProperty(size=%d): size must be between 0 and "
- STRINGIFY(PYRNA_STACK_ARRAY), size);
- return NULL;
- }
-
- if (pydef && PyC_AsArray(def, pydef, size, &PyBool_Type, false, "BoolVectorProperty(default=sequence)") == -1) {
- return NULL;
- }
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- // prop = RNA_def_boolean_array(srna, id, size, pydef ? def:NULL, name ? name : id, description);
- prop = RNA_def_property(srna, id, PROP_BOOLEAN, subtype);
- RNA_def_property_array(prop, size);
- if (pydef) {
- RNA_def_property_boolean_array_default(prop, def);
- }
- RNA_def_property_ui_text(prop, name ? name : id, description);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_boolean_array(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
-
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(BoolVectorProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ bool def[PYRNA_STACK_ARRAY] = {0};
+ int size = 3;
+ PropertyRNA *prop;
+ PyObject *pydef = NULL;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "options",
+ "tags",
+ "subtype",
+ "size",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOO!O!siOOO:BoolVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &pydef,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &size,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(
+ BoolVectorProperty, property_flag_items, property_subtype_array_items);
+
+ if (size < 1 || size > PYRNA_STACK_ARRAY) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "BoolVectorProperty(size=%d): size must be between 0 and " STRINGIFY(PYRNA_STACK_ARRAY),
+ size);
+ return NULL;
+ }
+
+ if (pydef &&
+ PyC_AsArray(
+ def, pydef, size, &PyBool_Type, false, "BoolVectorProperty(default=sequence)") == -1) {
+ return NULL;
+ }
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ // prop = RNA_def_boolean_array(srna, id, size, pydef ? def:NULL, name ? name : id, description);
+ prop = RNA_def_property(srna, id, PROP_BOOLEAN, subtype);
+ RNA_def_property_array(prop, size);
+ if (pydef) {
+ RNA_def_property_boolean_array_default(prop, def);
+ }
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_boolean_array(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_IntProperty_doc,
-".. function:: IntProperty(name=\"\", "
- "description=\"\", "
- "default=0, "
- "min=-2**31, max=2**31-1, "
- "soft_min=-2**31, soft_max=2**31-1, "
- "step=1, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new int property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-BPY_PROPDEF_NUM_MIN_DOC
-" :type min: int\n"
-BPY_PROPDEF_NUM_MAX_DOC
-" :type max: int\n"
-BPY_PROPDEF_NUM_SOFTMAX_DOC
-" :type soft_min: int\n"
-BPY_PROPDEF_NUM_SOFTMIN_DOC
-" :type soft_max: int\n"
-BPY_PROPDEF_INT_STEP_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_NUMBER_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: IntProperty(name=\"\", "
+ "description=\"\", "
+ "default=0, "
+ "min=-2**31, max=2**31-1, "
+ "soft_min=-2**31, soft_max=2**31-1, "
+ "step=1, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new int property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC BPY_PROPDEF_NUM_MIN_DOC
+ " :type min: int\n" BPY_PROPDEF_NUM_MAX_DOC
+ " :type max: int\n" BPY_PROPDEF_NUM_SOFTMAX_DOC
+ " :type soft_min: int\n" BPY_PROPDEF_NUM_SOFTMIN_DOC
+ " :type soft_max: int\n" BPY_PROPDEF_INT_STEP_DOC BPY_PROPDEF_OPTIONS_DOC
+ BPY_PROPDEF_TAGS_DOC BPY_PROPDEF_SUBTYPE_NUMBER_DOC BPY_PROPDEF_UPDATE_DOC
+ BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(IntProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1, def = 0;
- PropertyRNA *prop;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "options", "tags", "subtype",
- "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssiiiiiiO!O!sOOO:IntProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &def,
- &min, &max, &soft_min, &soft_max,
- &step, &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(IntProperty, property_flag_items, property_subtype_number_items);
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_INT, subtype);
- RNA_def_property_int_default(prop, def);
- RNA_def_property_ui_text(prop, name ? name : id, description);
- RNA_def_property_range(prop, min, max);
- RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_int(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(IntProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1, def = 0;
+ PropertyRNA *prop;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "min",
+ "max",
+ "soft_min",
+ "soft_max",
+ "step",
+ "options",
+ "tags",
+ "subtype",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssiiiiiiO!O!sOOO:IntProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &def,
+ &min,
+ &max,
+ &soft_min,
+ &soft_max,
+ &step,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(IntProperty, property_flag_items, property_subtype_number_items);
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_INT, subtype);
+ RNA_def_property_int_default(prop, def);
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+ RNA_def_property_range(prop, min, max);
+ RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_int(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_IntVectorProperty_doc,
-".. function:: IntVectorProperty(name=\"\", "
- "description=\"\", "
- "default=(0, 0, 0), min=-2**31, max=2**31-1, "
- "soft_min=-2**31, "
- "soft_max=2**31-1, "
- "step=1, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "size=3, "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new vector int property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-" :arg default: sequence of ints the length of *size*.\n"
-" :type default: sequence\n"
-BPY_PROPDEF_NUM_MIN_DOC
-" :type min: int\n"
-BPY_PROPDEF_NUM_MAX_DOC
-" :type max: int\n"
-BPY_PROPDEF_NUM_SOFTMIN_DOC
-" :type soft_min: int\n"
-BPY_PROPDEF_NUM_SOFTMAX_DOC
-" :type soft_max: int\n"
-BPY_PROPDEF_INT_STEP_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_ARRAY_DOC
-BPY_PROPDEF_VECSIZE_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: IntVectorProperty(name=\"\", "
+ "description=\"\", "
+ "default=(0, 0, 0), min=-2**31, max=2**31-1, "
+ "soft_min=-2**31, "
+ "soft_max=2**31-1, "
+ "step=1, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "size=3, "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new vector int property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ " :arg default: sequence of ints the length of *size*.\n"
+ " :type default: sequence\n" BPY_PROPDEF_NUM_MIN_DOC
+ " :type min: int\n" BPY_PROPDEF_NUM_MAX_DOC
+ " :type max: int\n" BPY_PROPDEF_NUM_SOFTMIN_DOC
+ " :type soft_min: int\n" BPY_PROPDEF_NUM_SOFTMAX_DOC
+ " :type soft_max: int\n" BPY_PROPDEF_INT_STEP_DOC BPY_PROPDEF_OPTIONS_DOC
+ BPY_PROPDEF_TAGS_DOC BPY_PROPDEF_SUBTYPE_ARRAY_DOC BPY_PROPDEF_VECSIZE_DOC
+ BPY_PROPDEF_UPDATE_DOC BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(IntVectorProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1;
- int def[PYRNA_STACK_ARRAY] = {0};
- int size = 3;
- PropertyRNA *prop;
- PyObject *pydef = NULL;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "options", "tags", "subtype", "size",
- "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssOiiiiiO!O!siOOO:IntVectorProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &pydef,
- &min, &max, &soft_min, &soft_max,
- &step, &PySet_Type, &pyopts, &PySet_Type, &py_tags,
- &pysubtype, &size,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(IntVectorProperty, property_flag_items, property_subtype_array_items);
-
- if (size < 1 || size > PYRNA_STACK_ARRAY) {
- PyErr_Format(PyExc_TypeError,
- "IntVectorProperty(size=%d): size must be between 0 and "
- STRINGIFY(PYRNA_STACK_ARRAY), size);
- return NULL;
- }
-
- if (pydef && PyC_AsArray(def, pydef, size, &PyLong_Type, false, "IntVectorProperty(default=sequence)") == -1) {
- return NULL;
- }
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_INT, subtype);
- RNA_def_property_array(prop, size);
- if (pydef) {
- RNA_def_property_int_array_default(prop, def);
- }
- RNA_def_property_range(prop, min, max);
- RNA_def_property_ui_text(prop, name ? name : id, description);
- RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_int_array(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(IntVectorProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1;
+ int def[PYRNA_STACK_ARRAY] = {0};
+ int size = 3;
+ PropertyRNA *prop;
+ PyObject *pydef = NULL;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "min",
+ "max",
+ "soft_min",
+ "soft_max",
+ "step",
+ "options",
+ "tags",
+ "subtype",
+ "size",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOiiiiiO!O!siOOO:IntVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &pydef,
+ &min,
+ &max,
+ &soft_min,
+ &soft_max,
+ &step,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &size,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(
+ IntVectorProperty, property_flag_items, property_subtype_array_items);
+
+ if (size < 1 || size > PYRNA_STACK_ARRAY) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "IntVectorProperty(size=%d): size must be between 0 and " STRINGIFY(PYRNA_STACK_ARRAY),
+ size);
+ return NULL;
+ }
+
+ if (pydef &&
+ PyC_AsArray(
+ def, pydef, size, &PyLong_Type, false, "IntVectorProperty(default=sequence)") == -1) {
+ return NULL;
+ }
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_INT, subtype);
+ RNA_def_property_array(prop, size);
+ if (pydef) {
+ RNA_def_property_int_array_default(prop, def);
+ }
+ RNA_def_property_range(prop, min, max);
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+ RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_int_array(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(BPy_FloatProperty_doc,
-".. function:: FloatProperty(name=\"\", "
- "description=\"\", "
- "default=0.0, "
- "min=sys.float_info.min, max=sys.float_info.max, "
- "soft_min=sys.float_info.min, soft_max=sys.float_info.max, "
- "step=3, "
- "precision=2, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "unit='NONE', "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new float property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-BPY_PROPDEF_NUM_MIN_DOC
-" :type min: float\n"
-BPY_PROPDEF_NUM_MAX_DOC
-" :type max: float\n"
-BPY_PROPDEF_NUM_SOFTMIN_DOC
-" :type soft_min: float\n"
-BPY_PROPDEF_NUM_SOFTMAX_DOC
-" :type soft_max: float\n"
-BPY_PROPDEF_FLOAT_STEP_DOC
-BPY_PROPDEF_FLOAT_PREC_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_NUMBER_DOC
-BPY_PROPDEF_UNIT_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: FloatProperty(name=\"\", "
+ "description=\"\", "
+ "default=0.0, "
+ "min=sys.float_info.min, max=sys.float_info.max, "
+ "soft_min=sys.float_info.min, soft_max=sys.float_info.max, "
+ "step=3, "
+ "precision=2, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "unit='NONE', "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new float property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC BPY_PROPDEF_NUM_MIN_DOC
+ " :type min: float\n" BPY_PROPDEF_NUM_MAX_DOC
+ " :type max: float\n" BPY_PROPDEF_NUM_SOFTMIN_DOC
+ " :type soft_min: float\n" BPY_PROPDEF_NUM_SOFTMAX_DOC
+ " :type soft_max: float\n" BPY_PROPDEF_FLOAT_STEP_DOC BPY_PROPDEF_FLOAT_PREC_DOC
+ BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC BPY_PROPDEF_SUBTYPE_NUMBER_DOC
+ BPY_PROPDEF_UNIT_DOC BPY_PROPDEF_UPDATE_DOC BPY_PROPDEF_GET_DOC
+ BPY_PROPDEF_SET_DOC);
static PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(FloatProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3, def = 0.0f;
- int precision = 2;
- PropertyRNA *prop;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- const char *pyunit = NULL;
- int unit = PROP_UNIT_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "precision", "options", "tags", "subtype",
- "unit", "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssffffffiO!O!ssOOO:FloatProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &def,
- &min, &max, &soft_min, &soft_max,
- &step, &precision, &PySet_Type,
- &pyopts, &PySet_Type, &py_tags, &pysubtype, &pyunit,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(FloatProperty, property_flag_items, property_subtype_number_items);
-
- if (pyunit && RNA_enum_value_from_id(rna_enum_property_unit_items, pyunit, &unit) == 0) {
- PyErr_Format(PyExc_TypeError, "FloatProperty(unit='%s'): invalid unit", pyunit);
- return NULL;
- }
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_FLOAT, subtype | unit);
- RNA_def_property_float_default(prop, def);
- RNA_def_property_range(prop, min, max);
- RNA_def_property_ui_text(prop, name ? name : id, description);
- RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_float(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(FloatProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3,
+ def = 0.0f;
+ int precision = 2;
+ PropertyRNA *prop;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ const char *pyunit = NULL;
+ int unit = PROP_UNIT_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "min",
+ "max",
+ "soft_min",
+ "soft_max",
+ "step",
+ "precision",
+ "options",
+ "tags",
+ "subtype",
+ "unit",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssffffffiO!O!ssOOO:FloatProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &def,
+ &min,
+ &max,
+ &soft_min,
+ &soft_max,
+ &step,
+ &precision,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &pyunit,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(FloatProperty, property_flag_items, property_subtype_number_items);
+
+ if (pyunit && RNA_enum_value_from_id(rna_enum_property_unit_items, pyunit, &unit) == 0) {
+ PyErr_Format(PyExc_TypeError, "FloatProperty(unit='%s'): invalid unit", pyunit);
+ return NULL;
+ }
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_FLOAT, subtype | unit);
+ RNA_def_property_float_default(prop, def);
+ RNA_def_property_range(prop, min, max);
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+ RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_float(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_FloatVectorProperty_doc,
-".. function:: FloatVectorProperty(name=\"\", "
- "description=\"\", "
- "default=(0.0, 0.0, 0.0), "
- "min=sys.float_info.min, max=sys.float_info.max, "
- "soft_min=sys.float_info.min, soft_max=sys.float_info.max, "
- "step=3, "
- "precision=2, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "unit='NONE', "
- "size=3, "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new vector float property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-" :arg default: sequence of floats the length of *size*.\n"
-" :type default: sequence\n"
-BPY_PROPDEF_NUM_MIN_DOC
-" :type min: float\n"
-BPY_PROPDEF_NUM_MAX_DOC
-" :type max: float\n"
-BPY_PROPDEF_NUM_SOFTMIN_DOC
-" :type soft_min: float\n"
-BPY_PROPDEF_NUM_SOFTMAX_DOC
-" :type soft_max: float\n"
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_FLOAT_STEP_DOC
-BPY_PROPDEF_FLOAT_PREC_DOC
-BPY_PROPDEF_SUBTYPE_ARRAY_DOC
-BPY_PROPDEF_UNIT_DOC
-BPY_PROPDEF_VECSIZE_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: FloatVectorProperty(name=\"\", "
+ "description=\"\", "
+ "default=(0.0, 0.0, 0.0), "
+ "min=sys.float_info.min, max=sys.float_info.max, "
+ "soft_min=sys.float_info.min, soft_max=sys.float_info.max, "
+ "step=3, "
+ "precision=2, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "unit='NONE', "
+ "size=3, "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new vector float property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ " :arg default: sequence of floats the length of *size*.\n"
+ " :type default: sequence\n" BPY_PROPDEF_NUM_MIN_DOC
+ " :type min: float\n" BPY_PROPDEF_NUM_MAX_DOC
+ " :type max: float\n" BPY_PROPDEF_NUM_SOFTMIN_DOC
+ " :type soft_min: float\n" BPY_PROPDEF_NUM_SOFTMAX_DOC
+ " :type soft_max: float\n" BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC
+ BPY_PROPDEF_FLOAT_STEP_DOC BPY_PROPDEF_FLOAT_PREC_DOC
+ BPY_PROPDEF_SUBTYPE_ARRAY_DOC BPY_PROPDEF_UNIT_DOC BPY_PROPDEF_VECSIZE_DOC
+ BPY_PROPDEF_UPDATE_DOC BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(FloatVectorProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3;
- float def[PYRNA_STACK_ARRAY] = {0.0f};
- int precision = 2, size = 3;
- PropertyRNA *prop;
- PyObject *pydef = NULL;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- const char *pyunit = NULL;
- int unit = PROP_UNIT_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "precision", "options", "tags", "subtype",
- "unit", "size", "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|ssOfffffiO!O!ssiOOO:FloatVectorProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &pydef,
- &min, &max, &soft_min, &soft_max,
- &step, &precision, &PySet_Type,
- &pyopts, &PySet_Type, &py_tags, &pysubtype, &pyunit, &size,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(FloatVectorProperty, property_flag_items, property_subtype_array_items);
-
- if (pyunit && RNA_enum_value_from_id(rna_enum_property_unit_items, pyunit, &unit) == 0) {
- PyErr_Format(PyExc_TypeError, "FloatVectorProperty(unit='%s'): invalid unit", pyunit);
- return NULL;
- }
-
- if (size < 1 || size > PYRNA_STACK_ARRAY) {
- PyErr_Format(PyExc_TypeError,
- "FloatVectorProperty(size=%d): size must be between 0 and "
- STRINGIFY(PYRNA_STACK_ARRAY), size);
- return NULL;
- }
-
- if (pydef && PyC_AsArray(def, pydef, size, &PyFloat_Type, false, "FloatVectorProperty(default=sequence)") == -1) {
- return NULL;
- }
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_FLOAT, subtype | unit);
- RNA_def_property_array(prop, size);
- if (pydef) {
- RNA_def_property_float_array_default(prop, def);
- }
- RNA_def_property_range(prop, min, max);
- RNA_def_property_ui_text(prop, name ? name : id, description);
- RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_float_array(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(FloatVectorProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3;
+ float def[PYRNA_STACK_ARRAY] = {0.0f};
+ int precision = 2, size = 3;
+ PropertyRNA *prop;
+ PyObject *pydef = NULL;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ const char *pyunit = NULL;
+ int unit = PROP_UNIT_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default", "min", "max", "soft_min",
+ "soft_max", "step", "precision", "options", "tags", "subtype", "unit",
+ "size", "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOfffffiO!O!ssiOOO:FloatVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &pydef,
+ &min,
+ &max,
+ &soft_min,
+ &soft_max,
+ &step,
+ &precision,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &pyunit,
+ &size,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(
+ FloatVectorProperty, property_flag_items, property_subtype_array_items);
+
+ if (pyunit && RNA_enum_value_from_id(rna_enum_property_unit_items, pyunit, &unit) == 0) {
+ PyErr_Format(PyExc_TypeError, "FloatVectorProperty(unit='%s'): invalid unit", pyunit);
+ return NULL;
+ }
+
+ if (size < 1 || size > PYRNA_STACK_ARRAY) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "FloatVectorProperty(size=%d): size must be between 0 and " STRINGIFY(PYRNA_STACK_ARRAY),
+ size);
+ return NULL;
+ }
+
+ if (pydef &&
+ PyC_AsArray(
+ def, pydef, size, &PyFloat_Type, false, "FloatVectorProperty(default=sequence)") ==
+ -1) {
+ return NULL;
+ }
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_FLOAT, subtype | unit);
+ RNA_def_property_array(prop, size);
+ if (pydef) {
+ RNA_def_property_float_array_default(prop, def);
+ }
+ RNA_def_property_range(prop, min, max);
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+ RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_float_array(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_StringProperty_doc,
-".. function:: StringProperty(name=\"\", "
- "description=\"\", "
- "default=\"\", "
- "maxlen=0, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "subtype='NONE', "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new string property definition.\n"
-"\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-" :arg default: initializer string.\n"
-" :type default: string\n"
-" :arg maxlen: maximum length of the string.\n"
-" :type maxlen: int\n"
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_SUBTYPE_STRING_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+ ".. function:: StringProperty(name=\"\", "
+ "description=\"\", "
+ "default=\"\", "
+ "maxlen=0, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "subtype='NONE', "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new string property definition.\n"
+ "\n" BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ " :arg default: initializer string.\n"
+ " :type default: string\n"
+ " :arg maxlen: maximum length of the string.\n"
+ " :type maxlen: int\n" BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC
+ BPY_PROPDEF_SUBTYPE_STRING_DOC BPY_PROPDEF_UPDATE_DOC BPY_PROPDEF_GET_DOC
+ BPY_PROPDEF_SET_DOC);
static PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(StringProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "", *def = "";
- int id_len;
- int maxlen = 0;
- PropertyRNA *prop;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- const char *pysubtype = NULL;
- int subtype = PROP_NONE;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "name", "description", "default",
- "maxlen", "options", "tags", "subtype",
- "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#|sssiO!O!sOOO:StringProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &name, &description, &def,
- &maxlen, &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_SUBTYPE_CHECK(StringProperty, property_flag_items, property_subtype_string_items);
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- prop = RNA_def_property(srna, id, PROP_STRING, subtype);
- if (maxlen != 0) {
- RNA_def_property_string_maxlength(prop, maxlen + 1); /* +1 since it includes null terminator */
- }
- if (def && def[0]) {
- RNA_def_property_string_default(prop, def);
- }
- RNA_def_property_ui_text(prop, name ? name : id, description);
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_string(prop, get_cb, set_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(StringProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "", *def = "";
+ int id_len;
+ int maxlen = 0;
+ PropertyRNA *prop;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ const char *pysubtype = NULL;
+ int subtype = PROP_NONE;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "name",
+ "description",
+ "default",
+ "maxlen",
+ "options",
+ "tags",
+ "subtype",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|sssiO!O!sOOO:StringProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &name,
+ &description,
+ &def,
+ &maxlen,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &pysubtype,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_SUBTYPE_CHECK(StringProperty, property_flag_items, property_subtype_string_items);
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ prop = RNA_def_property(srna, id, PROP_STRING, subtype);
+ if (maxlen != 0) {
+ RNA_def_property_string_maxlength(prop,
+ maxlen + 1); /* +1 since it includes null terminator */
+ }
+ if (def && def[0]) {
+ RNA_def_property_string_default(prop, def);
+ }
+ RNA_def_property_ui_text(prop, name ? name : id, description);
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_string(prop, get_cb, set_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(BPy_EnumProperty_doc,
-".. function:: EnumProperty(items, "
- "name=\"\", "
- "description=\"\", "
- "default=None, "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "update=None, "
- "get=None, "
- "set=None)\n"
-"\n"
-" Returns a new enumerator property definition.\n"
-"\n"
-" :arg items: sequence of enum items formatted:\n"
-" ``[(identifier, name, description, icon, number), ...]``.\n"
-"\n"
-" The first three elements of the tuples are mandatory.\n"
-"\n"
-" :identifier: The identifier is used for Python access.\n"
-" :name: Name for the interace.\n"
-" :description: Used for documentation and tooltips.\n"
-" :icon: An icon string identifier or integer icon value\n"
-" (e.g. returned by :class:`bpy.types.UILayout.icon`)\n"
-" :number: Unique value used as the identifier for this item (stored in file data).\n"
-" Use when the identifier may need to change. If the *ENUM_FLAG* option is used,\n"
-" the values are bitmasks and should be powers of two.\n"
-"\n"
-" When an item only contains 4 items they define ``(identifier, name, description, number)``.\n"
-"\n"
-" For dynamic values a callback can be passed which returns a list in\n"
-" the same format as the static list.\n"
-" This function must take 2 arguments ``(self, context)``, **context may be None**.\n"
-"\n"
-" .. warning::\n"
-"\n"
-" There is a known bug with using a callback,\n"
-" Python must keep a reference to the strings returned or Blender will misbehave\n"
-" or even crash."
-"\n"
-" :type items: sequence of string tuples or a function\n"
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-" :arg default: The default value for this enum, a string from the identifiers used in *items*.\n"
-" If the *ENUM_FLAG* option is used this must be a set of such string identifiers instead.\n"
-" WARNING: It shall not be specified (or specified to its default *None* value) for dynamic enums\n"
-" (i.e. if a callback function is given as *items* parameter).\n"
-" :type default: string or set\n"
-BPY_PROPDEF_OPTIONS_ENUM_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_UPDATE_DOC
-BPY_PROPDEF_GET_DOC
-BPY_PROPDEF_SET_DOC
-);
+PyDoc_STRVAR(
+ BPy_EnumProperty_doc,
+ ".. function:: EnumProperty(items, "
+ "name=\"\", "
+ "description=\"\", "
+ "default=None, "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "update=None, "
+ "get=None, "
+ "set=None)\n"
+ "\n"
+ " Returns a new enumerator property definition.\n"
+ "\n"
+ " :arg items: sequence of enum items formatted:\n"
+ " ``[(identifier, name, description, icon, number), ...]``.\n"
+ "\n"
+ " The first three elements of the tuples are mandatory.\n"
+ "\n"
+ " :identifier: The identifier is used for Python access.\n"
+ " :name: Name for the interace.\n"
+ " :description: Used for documentation and tooltips.\n"
+ " :icon: An icon string identifier or integer icon value\n"
+ " (e.g. returned by :class:`bpy.types.UILayout.icon`)\n"
+ " :number: Unique value used as the identifier for this item (stored in file data).\n"
+ " Use when the identifier may need to change. If the *ENUM_FLAG* option is used,\n"
+ " the values are bitmasks and should be powers of two.\n"
+ "\n"
+ " When an item only contains 4 items they define ``(identifier, name, description, "
+ "number)``.\n"
+ "\n"
+ " For dynamic values a callback can be passed which returns a list in\n"
+ " the same format as the static list.\n"
+ " This function must take 2 arguments ``(self, context)``, **context may be None**.\n"
+ "\n"
+ " .. warning::\n"
+ "\n"
+ " There is a known bug with using a callback,\n"
+ " Python must keep a reference to the strings returned or Blender will misbehave\n"
+ " or even crash."
+ "\n"
+ " :type items: sequence of string tuples or a function\n" BPY_PROPDEF_NAME_DOC
+ BPY_PROPDEF_DESC_DOC
+ " :arg default: The default value for this enum, a string from the identifiers used in "
+ "*items*.\n"
+ " If the *ENUM_FLAG* option is used this must be a set of such string identifiers "
+ "instead.\n"
+ " WARNING: It shall not be specified (or specified to its default *None* value) for "
+ "dynamic enums\n"
+ " (i.e. if a callback function is given as *items* parameter).\n"
+ " :type default: string or set\n" BPY_PROPDEF_OPTIONS_ENUM_DOC BPY_PROPDEF_TAGS_DOC
+ BPY_PROPDEF_UPDATE_DOC BPY_PROPDEF_GET_DOC BPY_PROPDEF_SET_DOC);
static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(EnumProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- PyObject *def = NULL;
- int id_len;
- int defvalue = 0;
- PyObject *items, *items_fast;
- const EnumPropertyItem *eitems;
- PropertyRNA *prop;
- PyObject *pyopts = NULL;
- int opts = 0;
- int prop_tags = 0;
- bool is_itemf = false;
- PyObject *update_cb = NULL;
- PyObject *get_cb = NULL;
- PyObject *set_cb = NULL;
- PyObject *py_tags = NULL;
-
- static const char *_keywords[] = {
- "attr", "items", "name", "description", "default",
- "options", "tags", "update", "get", "set", NULL,
- };
- static _PyArg_Parser _parser = {"s#O|ssOO!O!OOO:EnumProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &items, &name, &description,
- &def, &PySet_Type, &pyopts, &PySet_Type, &py_tags,
- &update_cb, &get_cb, &set_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_CHECK(EnumProperty, property_flag_enum_items);
-
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
- return NULL;
- }
-
- if (def == Py_None) {
- /* This allows to get same behavior when explicitly passing None as default value,
- * and not defining a default value at all! */
- def = NULL;
- }
-
- /* items can be a list or a callable */
- if (PyFunction_Check(items)) { /* don't use PyCallable_Check because we need the function code for errors */
- PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(items);
- if (f_code->co_argcount != 2) {
- PyErr_Format(PyExc_ValueError,
- "EnumProperty(...): expected 'items' function to take 2 arguments, not %d",
- f_code->co_argcount);
- return NULL;
- }
-
- if (def) {
- /* note, using type error here is odd but python does this for invalid arguments */
- PyErr_SetString(PyExc_TypeError,
- "EnumProperty(...): 'default' can't be set when 'items' is a function");
- return NULL;
- }
-
- is_itemf = true;
- eitems = DummyRNA_NULL_items;
- }
- else {
- if (!(items_fast = PySequence_Fast(items, "EnumProperty(...): "
- "expected a sequence of tuples for the enum items or a function")))
- {
- return NULL;
- }
-
- eitems = enum_items_from_py(items_fast, def, &defvalue,
- (opts & PROP_ENUM_FLAG) != 0);
-
- if (!eitems) {
- Py_DECREF(items_fast);
- return NULL;
- }
- }
-
- if (opts & PROP_ENUM_FLAG) {
- prop = RNA_def_enum_flag(srna, id, eitems, defvalue, name ? name : id, description);
- }
- else {
- prop = RNA_def_enum(srna, id, eitems, defvalue, name ? name : id, description);
- }
-
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_enum(prop, get_cb, set_cb, (is_itemf ? items : NULL));
- RNA_def_property_duplicate_pointers(srna, prop);
-
- if (is_itemf == false) {
- /* note: this must be postponed until after #RNA_def_property_duplicate_pointers
- * otherwise if this is a generator it may free the strings before we copy them */
- Py_DECREF(items_fast);
-
- MEM_freeN((void *)eitems);
- }
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(EnumProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ PyObject *def = NULL;
+ int id_len;
+ int defvalue = 0;
+ PyObject *items, *items_fast;
+ const EnumPropertyItem *eitems;
+ PropertyRNA *prop;
+ PyObject *pyopts = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ bool is_itemf = false;
+ PyObject *update_cb = NULL;
+ PyObject *get_cb = NULL;
+ PyObject *set_cb = NULL;
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "items",
+ "name",
+ "description",
+ "default",
+ "options",
+ "tags",
+ "update",
+ "get",
+ "set",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssOO!O!OOO:EnumProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &items,
+ &name,
+ &description,
+ &def,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &update_cb,
+ &get_cb,
+ &set_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_CHECK(EnumProperty, property_flag_enum_items);
+
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(get_cb, "get", 1) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(set_cb, "set", 2) == -1) {
+ return NULL;
+ }
+
+ if (def == Py_None) {
+ /* This allows to get same behavior when explicitly passing None as default value,
+ * and not defining a default value at all! */
+ def = NULL;
+ }
+
+ /* items can be a list or a callable */
+ if (PyFunction_Check(
+ items)) { /* don't use PyCallable_Check because we need the function code for errors */
+ PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(items);
+ if (f_code->co_argcount != 2) {
+ PyErr_Format(PyExc_ValueError,
+ "EnumProperty(...): expected 'items' function to take 2 arguments, not %d",
+ f_code->co_argcount);
+ return NULL;
+ }
+
+ if (def) {
+ /* note, using type error here is odd but python does this for invalid arguments */
+ PyErr_SetString(PyExc_TypeError,
+ "EnumProperty(...): 'default' can't be set when 'items' is a function");
+ return NULL;
+ }
+
+ is_itemf = true;
+ eitems = DummyRNA_NULL_items;
+ }
+ else {
+ if (!(items_fast = PySequence_Fast(
+ items,
+ "EnumProperty(...): "
+ "expected a sequence of tuples for the enum items or a function"))) {
+ return NULL;
+ }
+
+ eitems = enum_items_from_py(items_fast, def, &defvalue, (opts & PROP_ENUM_FLAG) != 0);
+
+ if (!eitems) {
+ Py_DECREF(items_fast);
+ return NULL;
+ }
+ }
+
+ if (opts & PROP_ENUM_FLAG) {
+ prop = RNA_def_enum_flag(srna, id, eitems, defvalue, name ? name : id, description);
+ }
+ else {
+ prop = RNA_def_enum(srna, id, eitems, defvalue, name ? name : id, description);
+ }
+
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_enum(prop, get_cb, set_cb, (is_itemf ? items : NULL));
+ RNA_def_property_duplicate_pointers(srna, prop);
+
+ if (is_itemf == false) {
+ /* note: this must be postponed until after #RNA_def_property_duplicate_pointers
+ * otherwise if this is a generator it may free the strings before we copy them */
+ Py_DECREF(items_fast);
+
+ MEM_freeN((void *)eitems);
+ }
+ }
+ Py_RETURN_NONE;
}
StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix)
{
- StructRNA *srna;
-
- srna = srna_from_self(value, "");
- if (!srna) {
- if (PyErr_Occurred()) {
- PyObject *msg = PyC_ExceptionBuffer();
- const char *msg_char = _PyUnicode_AsString(msg);
- PyErr_Format(PyExc_TypeError,
- "%.200s expected an RNA type, failed with: %s",
- error_prefix, msg_char);
- Py_DECREF(msg);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected an RNA type, failed with type '%s'",
- error_prefix, Py_TYPE(value)->tp_name);
- }
- return NULL;
- }
-
- return srna;
+ StructRNA *srna;
+
+ srna = srna_from_self(value, "");
+ if (!srna) {
+ if (PyErr_Occurred()) {
+ PyObject *msg = PyC_ExceptionBuffer();
+ const char *msg_char = _PyUnicode_AsString(msg);
+ PyErr_Format(
+ PyExc_TypeError, "%.200s expected an RNA type, failed with: %s", error_prefix, msg_char);
+ Py_DECREF(msg);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected an RNA type, failed with type '%s'",
+ error_prefix,
+ Py_TYPE(value)->tp_name);
+ }
+ return NULL;
+ }
+
+ return srna;
}
PyDoc_STRVAR(BPy_PointerProperty_doc,
-".. function:: PointerProperty(type=None, "
- "name=\"\", "
- "description=\"\", "
- "options={'ANIMATABLE'}, "
- "tags={}, "
- "poll=None, "
- "update=None)\n"
-"\n"
-" Returns a new pointer property definition.\n"
-"\n"
-BPY_PROPDEF_TYPE_DOC
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-BPY_PROPDEF_POLL_DOC
-BPY_PROPDEF_UPDATE_DOC
-);
+ ".. function:: PointerProperty(type=None, "
+ "name=\"\", "
+ "description=\"\", "
+ "options={'ANIMATABLE'}, "
+ "tags={}, "
+ "poll=None, "
+ "update=None)\n"
+ "\n"
+ " Returns a new pointer property definition.\n"
+ "\n" BPY_PROPDEF_TYPE_DOC BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC BPY_PROPDEF_POLL_DOC
+ BPY_PROPDEF_UPDATE_DOC);
PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(PointerProperty);
-
- if (srna) {
- const char *id = NULL, *name = NULL, *description = "";
- int id_len;
- PropertyRNA *prop;
- StructRNA *ptype;
- PyObject *type = Py_None;
- PyObject *pyopts = NULL;
- PyObject *py_tags = NULL;
- int opts = 0;
- int prop_tags = 0;
- PyObject *update_cb = NULL, *poll_cb = NULL;
-
- static const char *_keywords[] = {
- "attr", "type", "name", "description", "options",
- "tags", "poll", "update", NULL,
- };
- static _PyArg_Parser _parser = {"s#O|ssO!O!OO:PointerProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &type, &name, &description,
- &PySet_Type, &pyopts, &PySet_Type, &py_tags,
- &poll_cb, &update_cb))
- {
- return NULL;
- }
-
- BPY_PROPDEF_CHECK(PointerProperty, property_flag_items);
-
- ptype = pointer_type_from_py(type, "PointerProperty(...)");
- if (!ptype) {
- return NULL;
- }
- if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup) && !RNA_struct_is_ID(ptype)) {
- PyErr_Format(PyExc_TypeError,
- "PointerProperty(...) expected an RNA type derived from %.200s or %.200s",
- RNA_struct_ui_name(&RNA_ID), RNA_struct_ui_name(&RNA_PropertyGroup));
- return NULL;
- }
- if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
- return NULL;
- }
- if (bpy_prop_callback_check(poll_cb, "poll", 2) == -1) {
- return NULL;
- }
- prop = RNA_def_pointer_runtime(srna, id, ptype, name ? name : id, description);
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
-
- if (RNA_struct_idprops_contains_datablock(ptype)) {
- if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
- RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
- }
- }
- bpy_prop_callback_assign_update(prop, update_cb);
- bpy_prop_callback_assign_pointer(prop, poll_cb);
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(PointerProperty);
+
+ if (srna) {
+ const char *id = NULL, *name = NULL, *description = "";
+ int id_len;
+ PropertyRNA *prop;
+ StructRNA *ptype;
+ PyObject *type = Py_None;
+ PyObject *pyopts = NULL;
+ PyObject *py_tags = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+ PyObject *update_cb = NULL, *poll_cb = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ "type",
+ "name",
+ "description",
+ "options",
+ "tags",
+ "poll",
+ "update",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssO!O!OO:PointerProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &type,
+ &name,
+ &description,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags,
+ &poll_cb,
+ &update_cb)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_CHECK(PointerProperty, property_flag_items);
+
+ ptype = pointer_type_from_py(type, "PointerProperty(...)");
+ if (!ptype) {
+ return NULL;
+ }
+ if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup) && !RNA_struct_is_ID(ptype)) {
+ PyErr_Format(PyExc_TypeError,
+ "PointerProperty(...) expected an RNA type derived from %.200s or %.200s",
+ RNA_struct_ui_name(&RNA_ID),
+ RNA_struct_ui_name(&RNA_PropertyGroup));
+ return NULL;
+ }
+ if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
+ return NULL;
+ }
+ if (bpy_prop_callback_check(poll_cb, "poll", 2) == -1) {
+ return NULL;
+ }
+ prop = RNA_def_pointer_runtime(srna, id, ptype, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+
+ if (RNA_struct_idprops_contains_datablock(ptype)) {
+ if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
+ RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
+ }
+ }
+ bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_pointer(prop, poll_cb);
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_CollectionProperty_doc,
-".. function:: CollectionProperty(type=None, "
- "name=\"\", "
- "description=\"\", "
- "options={'ANIMATABLE'}, "
- "tags={})\n"
-"\n"
-" Returns a new collection property definition.\n"
-"\n"
-BPY_PROPDEF_TYPE_DOC
-BPY_PROPDEF_NAME_DOC
-BPY_PROPDEF_DESC_DOC
-BPY_PROPDEF_OPTIONS_DOC
-BPY_PROPDEF_TAGS_DOC
-);
+ ".. function:: CollectionProperty(type=None, "
+ "name=\"\", "
+ "description=\"\", "
+ "options={'ANIMATABLE'}, "
+ "tags={})\n"
+ "\n"
+ " Returns a new collection property definition.\n"
+ "\n" BPY_PROPDEF_TYPE_DOC BPY_PROPDEF_NAME_DOC BPY_PROPDEF_DESC_DOC
+ BPY_PROPDEF_OPTIONS_DOC BPY_PROPDEF_TAGS_DOC);
PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- BPY_PROPDEF_HEAD(CollectionProperty);
-
- if (srna) {
- int id_len;
- const char *id = NULL, *name = NULL, *description = "";
- PropertyRNA *prop;
- StructRNA *ptype;
- PyObject *type = Py_None;
- PyObject *pyopts = NULL;
- PyObject *py_tags = NULL;
- int opts = 0;
- int prop_tags = 0;
-
- static const char *_keywords[] = {
- "attr", "type", "name", "description",
- "options", "tags", NULL,
- };
- static _PyArg_Parser _parser = {"s#O|ssO!O!:CollectionProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id, &id_len,
- &type, &name, &description,
- &PySet_Type, &pyopts, &PySet_Type, &py_tags))
- {
- return NULL;
- }
-
- BPY_PROPDEF_CHECK(CollectionProperty, property_flag_items);
-
- ptype = pointer_type_from_py(type, "CollectionProperty(...):");
- if (!ptype) {
- return NULL;
- }
-
- if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup)) {
- PyErr_Format(
- PyExc_TypeError,
- "CollectionProperty(...) expected an RNA type derived from %.200s",
- RNA_struct_ui_name(&RNA_ID), RNA_struct_ui_name(&RNA_PropertyGroup));
- return NULL;
- }
-
- prop = RNA_def_collection_runtime(srna, id, ptype, name ? name : id, description);
- if (py_tags) {
- RNA_def_property_tags(prop, prop_tags);
- }
- if (pyopts) {
- bpy_prop_assign_flag(prop, opts);
- }
-
- if (RNA_struct_idprops_contains_datablock(ptype)) {
- if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
- RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
- }
- }
- RNA_def_property_duplicate_pointers(srna, prop);
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ BPY_PROPDEF_HEAD(CollectionProperty);
+
+ if (srna) {
+ int id_len;
+ const char *id = NULL, *name = NULL, *description = "";
+ PropertyRNA *prop;
+ StructRNA *ptype;
+ PyObject *type = Py_None;
+ PyObject *pyopts = NULL;
+ PyObject *py_tags = NULL;
+ int opts = 0;
+ int prop_tags = 0;
+
+ static const char *_keywords[] = {
+ "attr",
+ "type",
+ "name",
+ "description",
+ "options",
+ "tags",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssO!O!:CollectionProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &id,
+ &id_len,
+ &type,
+ &name,
+ &description,
+ &PySet_Type,
+ &pyopts,
+ &PySet_Type,
+ &py_tags)) {
+ return NULL;
+ }
+
+ BPY_PROPDEF_CHECK(CollectionProperty, property_flag_items);
+
+ ptype = pointer_type_from_py(type, "CollectionProperty(...):");
+ if (!ptype) {
+ return NULL;
+ }
+
+ if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup)) {
+ PyErr_Format(PyExc_TypeError,
+ "CollectionProperty(...) expected an RNA type derived from %.200s",
+ RNA_struct_ui_name(&RNA_ID),
+ RNA_struct_ui_name(&RNA_PropertyGroup));
+ return NULL;
+ }
+
+ prop = RNA_def_collection_runtime(srna, id, ptype, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
+ if (pyopts) {
+ bpy_prop_assign_flag(prop, opts);
+ }
+
+ if (RNA_struct_idprops_contains_datablock(ptype)) {
+ if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
+ RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
+ }
+ }
+ RNA_def_property_duplicate_pointers(srna, prop);
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_RemoveProperty_doc,
-".. function:: RemoveProperty(cls, attr)\n"
-"\n"
-" Removes a dynamically defined property.\n"
-"\n"
-" :arg cls: The class containing the property (must be a positional argument).\n"
-" :type cls: type\n"
-" :arg attr: Property name (must be passed as a keyword).\n"
-" :type attr: string\n"
-"\n"
-".. note:: Typically this function doesn't need to be accessed directly.\n"
-" Instead use ``del cls.attr``\n"
-);
+ ".. function:: RemoveProperty(cls, attr)\n"
+ "\n"
+ " Removes a dynamically defined property.\n"
+ "\n"
+ " :arg cls: The class containing the property (must be a positional argument).\n"
+ " :type cls: type\n"
+ " :arg attr: Property name (must be passed as a keyword).\n"
+ " :type attr: string\n"
+ "\n"
+ ".. note:: Typically this function doesn't need to be accessed directly.\n"
+ " Instead use ``del cls.attr``\n");
static PyObject *BPy_RemoveProperty(PyObject *self, PyObject *args, PyObject *kw)
{
- StructRNA *srna;
-
- if (PyTuple_GET_SIZE(args) == 1) {
- PyObject *ret;
- self = PyTuple_GET_ITEM(args, 0);
- args = PyTuple_New(0);
- ret = BPy_RemoveProperty(self, args, kw);
- Py_DECREF(args);
- return ret;
- }
- else if (PyTuple_GET_SIZE(args) > 1) {
- PyErr_SetString(PyExc_ValueError, "expected one positional arg, one keyword arg");
- return NULL;
- }
-
- srna = srna_from_self(self, "RemoveProperty(...):");
- if (srna == NULL && PyErr_Occurred()) {
- return NULL; /* self's type was compatible but error getting the srna */
- }
- else if (srna == NULL) {
- PyErr_SetString(PyExc_TypeError, "RemoveProperty(): struct rna not available for this type");
- return NULL;
- }
- else {
- const char *id = NULL;
-
- static const char *_keywords[] = {
- "attr", NULL,
- };
- static _PyArg_Parser _parser = {"s:RemoveProperty", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &id))
- {
- return NULL;
- }
-
- if (RNA_def_property_free_identifier(srna, id) != 1) {
- PyErr_Format(PyExc_TypeError, "RemoveProperty(): '%s' not a defined dynamic property", id);
- return NULL;
- }
- }
- Py_RETURN_NONE;
+ StructRNA *srna;
+
+ if (PyTuple_GET_SIZE(args) == 1) {
+ PyObject *ret;
+ self = PyTuple_GET_ITEM(args, 0);
+ args = PyTuple_New(0);
+ ret = BPy_RemoveProperty(self, args, kw);
+ Py_DECREF(args);
+ return ret;
+ }
+ else if (PyTuple_GET_SIZE(args) > 1) {
+ PyErr_SetString(PyExc_ValueError, "expected one positional arg, one keyword arg");
+ return NULL;
+ }
+
+ srna = srna_from_self(self, "RemoveProperty(...):");
+ if (srna == NULL && PyErr_Occurred()) {
+ return NULL; /* self's type was compatible but error getting the srna */
+ }
+ else if (srna == NULL) {
+ PyErr_SetString(PyExc_TypeError, "RemoveProperty(): struct rna not available for this type");
+ return NULL;
+ }
+ else {
+ const char *id = NULL;
+
+ static const char *_keywords[] = {
+ "attr",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"s:RemoveProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &id)) {
+ return NULL;
+ }
+
+ if (RNA_def_property_free_identifier(srna, id) != 1) {
+ PyErr_Format(PyExc_TypeError, "RemoveProperty(): '%s' not a defined dynamic property", id);
+ return NULL;
+ }
+ }
+ Py_RETURN_NONE;
}
static struct PyMethodDef props_methods[] = {
- {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS | METH_KEYWORDS, BPy_BoolProperty_doc},
- {"BoolVectorProperty", (PyCFunction)BPy_BoolVectorProperty, METH_VARARGS | METH_KEYWORDS, BPy_BoolVectorProperty_doc},
- {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS | METH_KEYWORDS, BPy_IntProperty_doc},
- {"IntVectorProperty", (PyCFunction)BPy_IntVectorProperty, METH_VARARGS | METH_KEYWORDS, BPy_IntVectorProperty_doc},
- {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS | METH_KEYWORDS, BPy_FloatProperty_doc},
- {"FloatVectorProperty", (PyCFunction)BPy_FloatVectorProperty, METH_VARARGS | METH_KEYWORDS, BPy_FloatVectorProperty_doc},
- {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS | METH_KEYWORDS, BPy_StringProperty_doc},
- {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS | METH_KEYWORDS, BPy_EnumProperty_doc},
- {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS | METH_KEYWORDS, BPy_PointerProperty_doc},
- {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS | METH_KEYWORDS, BPy_CollectionProperty_doc},
-
- {"RemoveProperty", (PyCFunction)BPy_RemoveProperty, METH_VARARGS | METH_KEYWORDS, BPy_RemoveProperty_doc},
- {NULL, NULL, 0, NULL},
+ {"BoolProperty",
+ (PyCFunction)BPy_BoolProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_BoolProperty_doc},
+ {"BoolVectorProperty",
+ (PyCFunction)BPy_BoolVectorProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_BoolVectorProperty_doc},
+ {"IntProperty",
+ (PyCFunction)BPy_IntProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_IntProperty_doc},
+ {"IntVectorProperty",
+ (PyCFunction)BPy_IntVectorProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_IntVectorProperty_doc},
+ {"FloatProperty",
+ (PyCFunction)BPy_FloatProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_FloatProperty_doc},
+ {"FloatVectorProperty",
+ (PyCFunction)BPy_FloatVectorProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_FloatVectorProperty_doc},
+ {"StringProperty",
+ (PyCFunction)BPy_StringProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_StringProperty_doc},
+ {"EnumProperty",
+ (PyCFunction)BPy_EnumProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_EnumProperty_doc},
+ {"PointerProperty",
+ (PyCFunction)BPy_PointerProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_PointerProperty_doc},
+ {"CollectionProperty",
+ (PyCFunction)BPy_CollectionProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_CollectionProperty_doc},
+
+ {"RemoveProperty",
+ (PyCFunction)BPy_RemoveProperty,
+ METH_VARARGS | METH_KEYWORDS,
+ BPy_RemoveProperty_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef props_module = {
- PyModuleDef_HEAD_INIT,
- "bpy.props",
- "This module defines properties to extend Blender's internal data. The result of these functions"
- " is used to assign properties to classes registered with Blender and can't be used directly.\n"
- "\n"
- ".. note:: All parameters to these functions must be passed as keywords.\n",
- -1, /* multiple "initialization" just copies the module dict. */
- props_methods,
- NULL, NULL, NULL, NULL,
+ PyModuleDef_HEAD_INIT,
+ "bpy.props",
+ "This module defines properties to extend Blender's internal data. The result of these "
+ "functions"
+ " is used to assign properties to classes registered with Blender and can't be used "
+ "directly.\n"
+ "\n"
+ ".. note:: All parameters to these functions must be passed as keywords.\n",
+ -1, /* multiple "initialization" just copies the module dict. */
+ props_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
PyObject *BPY_rna_props(void)
{
- PyObject *submodule;
- PyObject *submodule_dict;
+ PyObject *submodule;
+ PyObject *submodule_dict;
- submodule = PyModule_Create(&props_module);
- PyDict_SetItemString(PyImport_GetModuleDict(), props_module.m_name, submodule);
+ submodule = PyModule_Create(&props_module);
+ PyDict_SetItemString(PyImport_GetModuleDict(), props_module.m_name, submodule);
- /* api needs the PyObjects internally */
- submodule_dict = PyModule_GetDict(submodule);
+ /* api needs the PyObjects internally */
+ submodule_dict = PyModule_GetDict(submodule);
#define ASSIGN_STATIC(_name) pymeth_##_name = PyDict_GetItemString(submodule_dict, #_name)
- ASSIGN_STATIC(BoolProperty);
- ASSIGN_STATIC(BoolVectorProperty);
- ASSIGN_STATIC(IntProperty);
- ASSIGN_STATIC(IntVectorProperty);
- ASSIGN_STATIC(FloatProperty);
- ASSIGN_STATIC(FloatVectorProperty);
- ASSIGN_STATIC(StringProperty);
- ASSIGN_STATIC(EnumProperty);
- ASSIGN_STATIC(PointerProperty);
- ASSIGN_STATIC(CollectionProperty);
- ASSIGN_STATIC(RemoveProperty);
-
- return submodule;
+ ASSIGN_STATIC(BoolProperty);
+ ASSIGN_STATIC(BoolVectorProperty);
+ ASSIGN_STATIC(IntProperty);
+ ASSIGN_STATIC(IntVectorProperty);
+ ASSIGN_STATIC(FloatProperty);
+ ASSIGN_STATIC(FloatVectorProperty);
+ ASSIGN_STATIC(StringProperty);
+ ASSIGN_STATIC(EnumProperty);
+ ASSIGN_STATIC(PointerProperty);
+ ASSIGN_STATIC(CollectionProperty);
+ ASSIGN_STATIC(RemoveProperty);
+
+ return submodule;
}
diff --git a/source/blender/python/intern/bpy_props.h b/source/blender/python/intern/bpy_props.h
index 4741239be52..d559a3493b4 100644
--- a/source/blender/python/intern/bpy_props.h
+++ b/source/blender/python/intern/bpy_props.h
@@ -18,7 +18,6 @@
* \ingroup pythonintern
*/
-
#ifndef __BPY_PROPS_H__
#define __BPY_PROPS_H__
diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c
index 71d46de1be8..cf45d6ca2d9 100644
--- a/source/blender/python/intern/bpy_rna.c
+++ b/source/blender/python/intern/bpy_rna.c
@@ -83,73 +83,71 @@ BPy_StructRNA *bpy_context_module = NULL; /* for fast access */
static PyObject *pyrna_struct_Subtype(PointerRNA *ptr);
static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
-#define BPY_DOC_ID_PROP_TYPE_NOTE \
-" .. note::\n" \
-"\n" \
-" Only :class:`bpy.types.ID`, :class:`bpy.types.Bone` and\n" \
-" :class:`bpy.types.PoseBone` classes support custom properties.\n"
-
+#define BPY_DOC_ID_PROP_TYPE_NOTE \
+ " .. note::\n" \
+ "\n" \
+ " Only :class:`bpy.types.ID`, :class:`bpy.types.Bone` and\n" \
+ " :class:`bpy.types.PoseBone` classes support custom properties.\n"
int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
{
- if (pysrna->ptr.type) {
- return 0;
- }
- PyErr_Format(PyExc_ReferenceError,
- "StructRNA of type %.200s has been removed",
- Py_TYPE(pysrna)->tp_name);
- return -1;
+ if (pysrna->ptr.type) {
+ return 0;
+ }
+ PyErr_Format(
+ PyExc_ReferenceError, "StructRNA of type %.200s has been removed", Py_TYPE(pysrna)->tp_name);
+ return -1;
}
int pyrna_prop_validity_check(BPy_PropertyRNA *self)
{
- if (self->ptr.type) {
- return 0;
- }
- PyErr_Format(PyExc_ReferenceError,
- "PropertyRNA of type %.200s.%.200s has been removed",
- Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
- return -1;
+ if (self->ptr.type) {
+ return 0;
+ }
+ PyErr_Format(PyExc_ReferenceError,
+ "PropertyRNA of type %.200s.%.200s has been removed",
+ Py_TYPE(self)->tp_name,
+ RNA_property_identifier(self->prop));
+ return -1;
}
void pyrna_invalidate(BPy_DummyPointerRNA *self)
{
- RNA_POINTER_INVALIDATE(&self->ptr);
+ RNA_POINTER_INVALIDATE(&self->ptr);
}
#ifdef USE_PYRNA_INVALIDATE_GC
-#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
+# define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
/* only for sizeof() */
struct gc_generation {
- PyGC_Head head;
- int threshold;
- int count;
+ PyGC_Head head;
+ int threshold;
+ int count;
} gc_generation;
static void id_release_gc(struct ID *id)
{
- unsigned int j;
- // unsigned int i = 0;
- for (j = 0; j < 3; j++) {
- /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
- PyGC_Head *gen = (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
- PyGC_Head *g = gen->gc.gc_next;
- while ((g = g->gc.gc_next) != gen) {
- PyObject *ob = FROM_GC(g);
- if (PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) ||
- PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type))
- {
- BPy_DummyPointerRNA *ob_ptr = (BPy_DummyPointerRNA *)ob;
- if (ob_ptr->ptr.id.data == id) {
- pyrna_invalidate(ob_ptr);
- // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
- // i++;
- }
- }
- }
- }
- // printf("id_release_gc freed '%s': %d\n", id->name, i);
+ unsigned int j;
+ // unsigned int i = 0;
+ for (j = 0; j < 3; j++) {
+ /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
+ PyGC_Head *gen = (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
+ PyGC_Head *g = gen->gc.gc_next;
+ while ((g = g->gc.gc_next) != gen) {
+ PyObject *ob = FROM_GC(g);
+ if (PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) ||
+ PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
+ BPy_DummyPointerRNA *ob_ptr = (BPy_DummyPointerRNA *)ob;
+ if (ob_ptr->ptr.id.data == id) {
+ pyrna_invalidate(ob_ptr);
+ // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
+ // i++;
+ }
+ }
+ }
+ }
+ // printf("id_release_gc freed '%s': %d\n", id->name, i);
}
#endif
@@ -158,128 +156,128 @@ static void id_release_gc(struct ID *id)
struct GHash *id_weakref_pool = NULL;
static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
-static PyMethodDef id_free_weakref_cb_def = {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
+static PyMethodDef id_free_weakref_cb_def = {
+ "id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
/* adds a reference to the list, remember to decref */
static GHash *id_weakref_pool_get(ID *id)
{
- GHash *weakinfo_hash = NULL;
+ GHash *weakinfo_hash = NULL;
- if (id_weakref_pool) {
- weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
- }
- else {
- /* first time, allocate pool */
- id_weakref_pool = BLI_ghash_ptr_new("rna_global_pool");
- weakinfo_hash = NULL;
- }
+ if (id_weakref_pool) {
+ weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
+ }
+ else {
+ /* first time, allocate pool */
+ id_weakref_pool = BLI_ghash_ptr_new("rna_global_pool");
+ weakinfo_hash = NULL;
+ }
- if (weakinfo_hash == NULL) {
- /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
- weakinfo_hash = BLI_ghash_ptr_new("rna_id");
- BLI_ghash_insert(id_weakref_pool, id, weakinfo_hash);
- }
+ if (weakinfo_hash == NULL) {
+ /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
+ weakinfo_hash = BLI_ghash_ptr_new("rna_id");
+ BLI_ghash_insert(id_weakref_pool, id, weakinfo_hash);
+ }
- return weakinfo_hash;
+ return weakinfo_hash;
}
/* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
static void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
{
- PyObject *weakref;
- PyObject *weakref_capsule;
- PyObject *weakref_cb_py;
-
- /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
- GHash *weakinfo_hash = id_weakref_pool_get(id); /* new or existing */
+ PyObject *weakref;
+ PyObject *weakref_capsule;
+ PyObject *weakref_cb_py;
- weakref_capsule = PyCapsule_New(weakinfo_hash, NULL, NULL);
- weakref_cb_py = PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
- Py_DECREF(weakref_capsule);
+ /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
+ GHash *weakinfo_hash = id_weakref_pool_get(id); /* new or existing */
- /* add weakref to weakinfo_hash list */
- weakref = PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
+ weakref_capsule = PyCapsule_New(weakinfo_hash, NULL, NULL);
+ weakref_cb_py = PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
+ Py_DECREF(weakref_capsule);
- Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
+ /* add weakref to weakinfo_hash list */
+ weakref = PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
- /* important to add at the end, since first removal looks at the end */
- BLI_ghash_insert(weakinfo_hash, weakref, id); /* using a hash table as a set, all 'id's are the same */
- /* weakinfo_hash owns the weakref */
+ Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
+ /* important to add at the end, since first removal looks at the end */
+ BLI_ghash_insert(
+ weakinfo_hash, weakref, id); /* using a hash table as a set, all 'id's are the same */
+ /* weakinfo_hash owns the weakref */
}
/* workaround to get the last id without a lookup */
static ID *_id_tmp_ptr;
static void value_id_set(void *id)
{
- _id_tmp_ptr = (ID *)id;
+ _id_tmp_ptr = (ID *)id;
}
static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
{
- /* important to search backwards */
- GHash *weakinfo_hash = PyCapsule_GetPointer(weakinfo_capsule, NULL);
+ /* important to search backwards */
+ GHash *weakinfo_hash = PyCapsule_GetPointer(weakinfo_capsule, NULL);
+ if (BLI_ghash_len(weakinfo_hash) > 1) {
+ BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
+ }
+ else { /* get the last id and free it */
+ BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
+ id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
+ }
- if (BLI_ghash_len(weakinfo_hash) > 1) {
- BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
- }
- else { /* get the last id and free it */
- BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
- id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
- }
+ Py_DECREF(weakref);
- Py_DECREF(weakref);
-
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
{
- GHashIterator weakinfo_hash_iter;
+ GHashIterator weakinfo_hash_iter;
- BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
+ BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
-#ifdef DEBUG_RNA_WEAKREF
- fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_len(weakinfo_hash));
-#endif
+# ifdef DEBUG_RNA_WEAKREF
+ fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_len(weakinfo_hash));
+# endif
- while (!BLI_ghashIterator_done(&weakinfo_hash_iter)) {
- PyObject *weakref = (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
- PyObject *item = PyWeakref_GET_OBJECT(weakref);
- if (item != Py_None) {
+ while (!BLI_ghashIterator_done(&weakinfo_hash_iter)) {
+ PyObject *weakref = (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
+ PyObject *item = PyWeakref_GET_OBJECT(weakref);
+ if (item != Py_None) {
-#ifdef DEBUG_RNA_WEAKREF
- PyC_ObSpit("id_release_weakref item ", item);
-#endif
+# ifdef DEBUG_RNA_WEAKREF
+ PyC_ObSpit("id_release_weakref item ", item);
+# endif
- pyrna_invalidate((BPy_DummyPointerRNA *)item);
- }
+ pyrna_invalidate((BPy_DummyPointerRNA *)item);
+ }
- Py_DECREF(weakref);
+ Py_DECREF(weakref);
- BLI_ghashIterator_step(&weakinfo_hash_iter);
- }
+ BLI_ghashIterator_step(&weakinfo_hash_iter);
+ }
- BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
- BLI_ghash_free(weakinfo_hash, NULL, NULL);
+ BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
+ BLI_ghash_free(weakinfo_hash, NULL, NULL);
- if (BLI_ghash_len(id_weakref_pool) == 0) {
- BLI_ghash_free(id_weakref_pool, NULL, NULL);
- id_weakref_pool = NULL;
-#ifdef DEBUG_RNA_WEAKREF
- printf("id_release_weakref freeing pool\n");
-#endif
- }
+ if (BLI_ghash_len(id_weakref_pool) == 0) {
+ BLI_ghash_free(id_weakref_pool, NULL, NULL);
+ id_weakref_pool = NULL;
+# ifdef DEBUG_RNA_WEAKREF
+ printf("id_release_weakref freeing pool\n");
+# endif
+ }
}
static void id_release_weakref(struct ID *id)
{
- GHash *weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
- if (weakinfo_hash) {
- id_release_weakref_list(id, weakinfo_hash);
- }
+ GHash *weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
+ if (weakinfo_hash) {
+ id_release_weakref_list(id, weakinfo_hash);
+ }
}
#endif /* USE_PYRNA_INVALIDATE_WEAKREF */
@@ -287,20 +285,20 @@ static void id_release_weakref(struct ID *id)
void BPY_id_release(struct ID *id)
{
#ifdef USE_PYRNA_INVALIDATE_GC
- id_release_gc(id);
+ id_release_gc(id);
#endif
#ifdef USE_PYRNA_INVALIDATE_WEAKREF
- if (id_weakref_pool) {
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ if (id_weakref_pool) {
+ PyGILState_STATE gilstate = PyGILState_Ensure();
- id_release_weakref(id);
+ id_release_weakref(id);
- PyGILState_Release(gilstate);
- }
+ PyGILState_Release(gilstate);
+ }
#endif /* USE_PYRNA_INVALIDATE_WEAKREF */
- (void)id;
+ (void)id;
}
#ifdef USE_PEDANTIC_WRITE
@@ -308,480 +306,487 @@ static bool rna_disallow_writes = false;
static bool rna_id_write_error(PointerRNA *ptr, PyObject *key)
{
- ID *id = ptr->id.data;
- if (id) {
- const short idcode = GS(id->name);
- if (!ELEM(idcode, ID_WM, ID_SCR, ID_WS)) { /* may need more added here */
- const char *idtype = BKE_idcode_to_name(idcode);
- const char *pyname;
- if (key && PyUnicode_Check(key)) {
- pyname = _PyUnicode_AsString(key);
- }
- else {
- pyname = "<UNKNOWN>";
- }
-
- /* make a nice string error */
- BLI_assert(idtype != NULL);
- PyErr_Format(PyExc_AttributeError,
- "Writing to ID classes in this context is not allowed: "
- "%.200s, %.200s datablock, error setting %.200s.%.200s",
- id->name + 2, idtype, RNA_struct_identifier(ptr->type), pyname);
-
- return true;
- }
- }
- return false;
-}
-#endif /* USE_PEDANTIC_WRITE */
-
+ ID *id = ptr->id.data;
+ if (id) {
+ const short idcode = GS(id->name);
+ if (!ELEM(idcode, ID_WM, ID_SCR, ID_WS)) { /* may need more added here */
+ const char *idtype = BKE_idcode_to_name(idcode);
+ const char *pyname;
+ if (key && PyUnicode_Check(key)) {
+ pyname = _PyUnicode_AsString(key);
+ }
+ else {
+ pyname = "<UNKNOWN>";
+ }
+
+ /* make a nice string error */
+ BLI_assert(idtype != NULL);
+ PyErr_Format(PyExc_AttributeError,
+ "Writing to ID classes in this context is not allowed: "
+ "%.200s, %.200s datablock, error setting %.200s.%.200s",
+ id->name + 2,
+ idtype,
+ RNA_struct_identifier(ptr->type),
+ pyname);
+
+ return true;
+ }
+ }
+ return false;
+}
+#endif /* USE_PEDANTIC_WRITE */
#ifdef USE_PEDANTIC_WRITE
bool pyrna_write_check(void)
{
- return !rna_disallow_writes;
+ return !rna_disallow_writes;
}
void pyrna_write_set(bool val)
{
- rna_disallow_writes = !val;
+ rna_disallow_writes = !val;
}
#else /* USE_PEDANTIC_WRITE */
bool pyrna_write_check(void)
{
- return true;
+ return true;
}
void pyrna_write_set(bool UNUSED(val))
{
- /* nothing */
+ /* nothing */
}
-#endif /* USE_PEDANTIC_WRITE */
+#endif /* USE_PEDANTIC_WRITE */
static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
-static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
+static int pyrna_py_to_prop(
+ PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
#ifdef USE_MATHUTILS
-#include "../mathutils/mathutils.h" /* so we can have mathutils callbacks */
-
-static PyObject *pyrna_prop_array_subscript_slice(
- BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
- Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length);
-static short pyrna_rotation_euler_order_get(
- PointerRNA *ptr, const short order_fallback,
- PropertyRNA **r_prop_eul_order);
+# include "../mathutils/mathutils.h" /* so we can have mathutils callbacks */
+
+static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ Py_ssize_t start,
+ Py_ssize_t stop,
+ Py_ssize_t length);
+static short pyrna_rotation_euler_order_get(PointerRNA *ptr,
+ const short order_fallback,
+ PropertyRNA **r_prop_eul_order);
/* bpyrna vector/euler/quat callbacks */
static unsigned char mathutils_rna_array_cb_index = -1; /* index for our callbacks */
/* subtype not used much yet */
-#define MATHUTILS_CB_SUBTYPE_EUL 0
-#define MATHUTILS_CB_SUBTYPE_VEC 1
-#define MATHUTILS_CB_SUBTYPE_QUAT 2
-#define MATHUTILS_CB_SUBTYPE_COLOR 3
+# define MATHUTILS_CB_SUBTYPE_EUL 0
+# define MATHUTILS_CB_SUBTYPE_VEC 1
+# define MATHUTILS_CB_SUBTYPE_QUAT 2
+# define MATHUTILS_CB_SUBTYPE_COLOR 3
static int mathutils_rna_generic_check(BaseMathObject *bmo)
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- return self->prop ? 0 : -1;
+ return self->prop ? 0 : -1;
}
static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- if (self->prop == NULL) {
- return -1;
- }
+ if (self->prop == NULL) {
+ return -1;
+ }
- RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
+ RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
- /* Euler order exception */
- if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
- EulerObject *eul = (EulerObject *)bmo;
- PropertyRNA *prop_eul_order = NULL;
- eul->order = pyrna_rotation_euler_order_get(&self->ptr, eul->order, &prop_eul_order);
- }
+ /* Euler order exception */
+ if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
+ EulerObject *eul = (EulerObject *)bmo;
+ PropertyRNA *prop_eul_order = NULL;
+ eul->order = pyrna_rotation_euler_order_get(&self->ptr, eul->order, &prop_eul_order);
+ }
- return 0;
+ return 0;
}
static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- float min, max;
-
- PYRNA_PROP_CHECK_INT(self);
-
- if (self->prop == NULL) {
- return -1;
- }
-
-#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
-
- if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_prop \"%.200s.%.200s\" is read-only",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
- return -1;
- }
-
- RNA_property_float_range(&self->ptr, self->prop, &min, &max);
-
- if (min != -FLT_MAX || max != FLT_MAX) {
- int i, len = RNA_property_array_length(&self->ptr, self->prop);
- for (i = 0; i < len; i++) {
- CLAMP(bmo->data[i], min, max);
- }
- }
-
- RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
- if (RNA_property_update_check(self->prop)) {
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
- }
-
- /* Euler order exception */
- if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
- EulerObject *eul = (EulerObject *)bmo;
- PropertyRNA *prop_eul_order = NULL;
- short order = pyrna_rotation_euler_order_get(&self->ptr, eul->order, &prop_eul_order);
- if (order != eul->order) {
- RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
- if (RNA_property_update_check(prop_eul_order)) {
- RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
- }
- }
- }
- return 0;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ float min, max;
+
+ PYRNA_PROP_CHECK_INT(self);
+
+ if (self->prop == NULL) {
+ return -1;
+ }
+
+# ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return -1;
+ }
+# endif /* USE_PEDANTIC_WRITE */
+
+ if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_prop \"%.200s.%.200s\" is read-only",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop));
+ return -1;
+ }
+
+ RNA_property_float_range(&self->ptr, self->prop, &min, &max);
+
+ if (min != -FLT_MAX || max != FLT_MAX) {
+ int i, len = RNA_property_array_length(&self->ptr, self->prop);
+ for (i = 0; i < len; i++) {
+ CLAMP(bmo->data[i], min, max);
+ }
+ }
+
+ RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
+ if (RNA_property_update_check(self->prop)) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ }
+
+ /* Euler order exception */
+ if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
+ EulerObject *eul = (EulerObject *)bmo;
+ PropertyRNA *prop_eul_order = NULL;
+ short order = pyrna_rotation_euler_order_get(&self->ptr, eul->order, &prop_eul_order);
+ if (order != eul->order) {
+ RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
+ if (RNA_property_update_check(prop_eul_order)) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
+ }
+ }
+ }
+ return 0;
}
static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- if (self->prop == NULL) {
- return -1;
- }
+ if (self->prop == NULL) {
+ return -1;
+ }
- bmo->data[index] = RNA_property_float_get_index(&self->ptr, self->prop, index);
- return 0;
+ bmo->data[index] = RNA_property_float_get_index(&self->ptr, self->prop, index);
+ return 0;
}
static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- if (self->prop == NULL) {
- return -1;
- }
+ if (self->prop == NULL) {
+ return -1;
+ }
-#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
+# ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return -1;
+ }
+# endif /* USE_PEDANTIC_WRITE */
- if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_prop \"%.200s.%.200s\" is read-only",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
- return -1;
- }
+ if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_prop \"%.200s.%.200s\" is read-only",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop));
+ return -1;
+ }
- RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
- RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
+ RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
+ RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
- if (RNA_property_update_check(self->prop)) {
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
- }
+ if (RNA_property_update_check(self->prop)) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ }
- return 0;
+ return 0;
}
static Mathutils_Callback mathutils_rna_array_cb = {
- (BaseMathCheckFunc) mathutils_rna_generic_check,
- (BaseMathGetFunc) mathutils_rna_vector_get,
- (BaseMathSetFunc) mathutils_rna_vector_set,
- (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
- (BaseMathSetIndexFunc) mathutils_rna_vector_set_index,
+ (BaseMathCheckFunc)mathutils_rna_generic_check,
+ (BaseMathGetFunc)mathutils_rna_vector_get,
+ (BaseMathSetFunc)mathutils_rna_vector_set,
+ (BaseMathGetIndexFunc)mathutils_rna_vector_get_index,
+ (BaseMathSetIndexFunc)mathutils_rna_vector_set_index,
};
-
/* bpyrna matrix callbacks */
static unsigned char mathutils_rna_matrix_cb_index = -1; /* index for our callbacks */
static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- if (self->prop == NULL) {
- return -1;
- }
+ if (self->prop == NULL) {
+ return -1;
+ }
- RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
- return 0;
+ RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
+ return 0;
}
static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
{
- BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
+ BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- if (self->prop == NULL) {
- return -1;
- }
+ if (self->prop == NULL) {
+ return -1;
+ }
-#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
+# ifdef USE_PEDANTIC_WRITE
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return -1;
+ }
+# endif /* USE_PEDANTIC_WRITE */
- if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_prop \"%.200s.%.200s\" is read-only",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
- return -1;
- }
+ if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_prop \"%.200s.%.200s\" is read-only",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop));
+ return -1;
+ }
- /* can ignore clamping here */
- RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
+ /* can ignore clamping here */
+ RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
- if (RNA_property_update_check(self->prop)) {
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
- }
- return 0;
+ if (RNA_property_update_check(self->prop)) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ }
+ return 0;
}
static Mathutils_Callback mathutils_rna_matrix_cb = {
- mathutils_rna_generic_check,
- mathutils_rna_matrix_get,
- mathutils_rna_matrix_set,
- NULL,
- NULL,
+ mathutils_rna_generic_check,
+ mathutils_rna_matrix_get,
+ mathutils_rna_matrix_set,
+ NULL,
+ NULL,
};
-static short pyrna_rotation_euler_order_get(
- PointerRNA *ptr, const short order_fallback,
- PropertyRNA **r_prop_eul_order)
+static short pyrna_rotation_euler_order_get(PointerRNA *ptr,
+ const short order_fallback,
+ PropertyRNA **r_prop_eul_order)
{
- /* attempt to get order */
- if (*r_prop_eul_order == NULL) {
- *r_prop_eul_order = RNA_struct_find_property(ptr, "rotation_mode");
- }
+ /* attempt to get order */
+ if (*r_prop_eul_order == NULL) {
+ *r_prop_eul_order = RNA_struct_find_property(ptr, "rotation_mode");
+ }
- if (*r_prop_eul_order) {
- short order = RNA_property_enum_get(ptr, *r_prop_eul_order);
- /* could be quat or axisangle */
- if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) {
- return order;
- }
- }
+ if (*r_prop_eul_order) {
+ short order = RNA_property_enum_get(ptr, *r_prop_eul_order);
+ /* could be quat or axisangle */
+ if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) {
+ return order;
+ }
+ }
- return order_fallback;
+ return order_fallback;
}
-#endif /* USE_MATHUTILS */
+#endif /* USE_MATHUTILS */
/* note that PROP_NONE is included as a vector subtype. this is because its handy to
* have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
-#define PROP_ALL_VECTOR_SUBTYPES \
- PROP_COORDS: \
- case PROP_TRANSLATION: \
- case PROP_DIRECTION: \
- case PROP_VELOCITY: \
- case PROP_ACCELERATION: \
- case PROP_XYZ: \
- case PROP_XYZ_LENGTH \
-
+#define PROP_ALL_VECTOR_SUBTYPES \
+ PROP_COORDS: \
+ case PROP_TRANSLATION: \
+ case PROP_DIRECTION: \
+ case PROP_VELOCITY: \
+ case PROP_ACCELERATION: \
+ case PROP_XYZ: \
+ case PROP_XYZ_LENGTH
PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
{
- PyObject *ret = NULL;
+ PyObject *ret = NULL;
#ifdef USE_MATHUTILS
- int subtype, totdim;
- int len;
- const int flag = RNA_property_flag(prop);
- const int type = RNA_property_type(prop);
- const bool is_thick = (flag & PROP_THICK_WRAP) != 0;
-
- /* disallow dynamic sized arrays to be wrapped since the size could change
- * to a size mathutils does not support */
- if (flag & PROP_DYNAMIC) {
- return NULL;
- }
-
- len = RNA_property_array_length(ptr, prop);
- if (type == PROP_FLOAT) {
- /* pass */
- }
- else if (type == PROP_INT) {
- if (is_thick) {
- goto thick_wrap_slice;
- }
- else {
- return NULL;
- }
- }
- else {
- return NULL;
- }
-
- subtype = RNA_property_subtype(prop);
- totdim = RNA_property_array_dimension(ptr, prop, NULL);
-
- if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
- if (!is_thick) {
- /* owned by the mathutils PyObject */
- ret = pyrna_prop_CreatePyObject(ptr, prop);
- }
-
- switch (subtype) {
- case PROP_ALL_VECTOR_SUBTYPES:
- if (len >= 2 && len <= 4) {
- if (is_thick) {
- ret = Vector_CreatePyObject(NULL, len, NULL);
- RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
- }
- else {
- PyObject *vec_cb = Vector_CreatePyObject_cb(
- ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
- Py_DECREF(ret); /* the vector owns now */
- ret = vec_cb; /* return the vector instead */
- }
- }
- break;
- case PROP_MATRIX:
- if (len == 16) {
- if (is_thick) {
- ret = Matrix_CreatePyObject(NULL, 4, 4, NULL);
- RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
- }
- else {
- PyObject *mat_cb = Matrix_CreatePyObject_cb(
- ret, 4, 4, mathutils_rna_matrix_cb_index, 0);
- Py_DECREF(ret); /* the matrix owns now */
- ret = mat_cb; /* return the matrix instead */
- }
- }
- else if (len == 9) {
- if (is_thick) {
- ret = Matrix_CreatePyObject(NULL, 3, 3, NULL);
- RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
- }
- else {
- PyObject *mat_cb = Matrix_CreatePyObject_cb(
- ret, 3, 3, mathutils_rna_matrix_cb_index, 0);
- Py_DECREF(ret); /* the matrix owns now */
- ret = mat_cb; /* return the matrix instead */
- }
- }
- break;
- case PROP_EULER:
- case PROP_QUATERNION:
- if (len == 3) { /* euler */
- if (is_thick) {
- /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
- PropertyRNA *prop_eul_order = NULL;
- short order = pyrna_rotation_euler_order_get(ptr, EULER_ORDER_XYZ, &prop_eul_order);
-
- ret = Euler_CreatePyObject(NULL, order, NULL); /* TODO, get order from RNA */
- RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
- }
- else {
- /* order will be updated from callback on use */
- // TODO, get order from RNA
- PyObject *eul_cb = Euler_CreatePyObject_cb(
- ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL);
- Py_DECREF(ret); /* the euler owns now */
- ret = eul_cb; /* return the euler instead */
- }
- }
- else if (len == 4) {
- if (is_thick) {
- ret = Quaternion_CreatePyObject(NULL, NULL);
- RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
- }
- else {
- PyObject *quat_cb = Quaternion_CreatePyObject_cb(
- ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
- Py_DECREF(ret); /* the quat owns now */
- ret = quat_cb; /* return the quat instead */
- }
- }
- break;
- case PROP_COLOR:
- case PROP_COLOR_GAMMA:
- if (len == 3) { /* color */
- if (is_thick) {
- ret = Color_CreatePyObject(NULL, NULL);
- RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
- }
- else {
- PyObject *col_cb = Color_CreatePyObject_cb(
- ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
- Py_DECREF(ret); /* the color owns now */
- ret = col_cb; /* return the color instead */
- }
- }
- break;
- default:
- break;
- }
- }
-
- if (ret == NULL) {
- if (is_thick) {
- /* this is an array we cant reference (since its not thin wrappable)
- * and cannot be coerced into a mathutils type, so return as a list */
-thick_wrap_slice:
- ret = pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
- }
- else {
- ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
- }
- }
+ int subtype, totdim;
+ int len;
+ const int flag = RNA_property_flag(prop);
+ const int type = RNA_property_type(prop);
+ const bool is_thick = (flag & PROP_THICK_WRAP) != 0;
+
+ /* disallow dynamic sized arrays to be wrapped since the size could change
+ * to a size mathutils does not support */
+ if (flag & PROP_DYNAMIC) {
+ return NULL;
+ }
+
+ len = RNA_property_array_length(ptr, prop);
+ if (type == PROP_FLOAT) {
+ /* pass */
+ }
+ else if (type == PROP_INT) {
+ if (is_thick) {
+ goto thick_wrap_slice;
+ }
+ else {
+ return NULL;
+ }
+ }
+ else {
+ return NULL;
+ }
+
+ subtype = RNA_property_subtype(prop);
+ totdim = RNA_property_array_dimension(ptr, prop, NULL);
+
+ if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
+ if (!is_thick) {
+ /* owned by the mathutils PyObject */
+ ret = pyrna_prop_CreatePyObject(ptr, prop);
+ }
+
+ switch (subtype) {
+ case PROP_ALL_VECTOR_SUBTYPES:
+ if (len >= 2 && len <= 4) {
+ if (is_thick) {
+ ret = Vector_CreatePyObject(NULL, len, NULL);
+ RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
+ }
+ else {
+ PyObject *vec_cb = Vector_CreatePyObject_cb(
+ ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
+ Py_DECREF(ret); /* the vector owns now */
+ ret = vec_cb; /* return the vector instead */
+ }
+ }
+ break;
+ case PROP_MATRIX:
+ if (len == 16) {
+ if (is_thick) {
+ ret = Matrix_CreatePyObject(NULL, 4, 4, NULL);
+ RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
+ }
+ else {
+ PyObject *mat_cb = Matrix_CreatePyObject_cb(
+ ret, 4, 4, mathutils_rna_matrix_cb_index, 0);
+ Py_DECREF(ret); /* the matrix owns now */
+ ret = mat_cb; /* return the matrix instead */
+ }
+ }
+ else if (len == 9) {
+ if (is_thick) {
+ ret = Matrix_CreatePyObject(NULL, 3, 3, NULL);
+ RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
+ }
+ else {
+ PyObject *mat_cb = Matrix_CreatePyObject_cb(
+ ret, 3, 3, mathutils_rna_matrix_cb_index, 0);
+ Py_DECREF(ret); /* the matrix owns now */
+ ret = mat_cb; /* return the matrix instead */
+ }
+ }
+ break;
+ case PROP_EULER:
+ case PROP_QUATERNION:
+ if (len == 3) { /* euler */
+ if (is_thick) {
+ /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
+ PropertyRNA *prop_eul_order = NULL;
+ short order = pyrna_rotation_euler_order_get(ptr, EULER_ORDER_XYZ, &prop_eul_order);
+
+ ret = Euler_CreatePyObject(NULL, order, NULL); /* TODO, get order from RNA */
+ RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
+ }
+ else {
+ /* order will be updated from callback on use */
+ // TODO, get order from RNA
+ PyObject *eul_cb = Euler_CreatePyObject_cb(
+ ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL);
+ Py_DECREF(ret); /* the euler owns now */
+ ret = eul_cb; /* return the euler instead */
+ }
+ }
+ else if (len == 4) {
+ if (is_thick) {
+ ret = Quaternion_CreatePyObject(NULL, NULL);
+ RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
+ }
+ else {
+ PyObject *quat_cb = Quaternion_CreatePyObject_cb(
+ ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
+ Py_DECREF(ret); /* the quat owns now */
+ ret = quat_cb; /* return the quat instead */
+ }
+ }
+ break;
+ case PROP_COLOR:
+ case PROP_COLOR_GAMMA:
+ if (len == 3) { /* color */
+ if (is_thick) {
+ ret = Color_CreatePyObject(NULL, NULL);
+ RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
+ }
+ else {
+ PyObject *col_cb = Color_CreatePyObject_cb(
+ ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
+ Py_DECREF(ret); /* the color owns now */
+ ret = col_cb; /* return the color instead */
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (ret == NULL) {
+ if (is_thick) {
+ /* this is an array we cant reference (since its not thin wrappable)
+ * and cannot be coerced into a mathutils type, so return as a list */
+ thick_wrap_slice:
+ ret = pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
+ }
+ else {
+ ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
+ }
+ }
#else /* USE_MATHUTILS */
- (void)ptr;
- (void)prop;
-#endif /* USE_MATHUTILS */
+ (void)ptr;
+ (void)prop;
+#endif /* USE_MATHUTILS */
- return ret;
+ return ret;
}
/* same as RNA_enum_value_from_id but raises an exception */
-int pyrna_enum_value_from_id(
- const EnumPropertyItem *item, const char *identifier, int *r_value,
- const char *error_prefix)
+int pyrna_enum_value_from_id(const EnumPropertyItem *item,
+ const char *identifier,
+ int *r_value,
+ const char *error_prefix)
{
- if (RNA_enum_value_from_id(item, identifier, r_value) == 0) {
- const char *enum_str = BPy_enum_as_string(item);
- PyErr_Format(PyExc_ValueError,
- "%s: '%.200s' not found in (%s)",
- error_prefix, identifier, enum_str);
- MEM_freeN((void *)enum_str);
- return -1;
- }
+ if (RNA_enum_value_from_id(item, identifier, r_value) == 0) {
+ const char *enum_str = BPy_enum_as_string(item);
+ PyErr_Format(
+ PyExc_ValueError, "%s: '%.200s' not found in (%s)", error_prefix, identifier, enum_str);
+ MEM_freeN((void *)enum_str);
+ return -1;
+ }
- return 0;
+ return 0;
}
/* note on __cmp__:
@@ -797,325 +802,315 @@ int pyrna_enum_value_from_id(
static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
{
- return (((a->ptr.data == b->ptr.data) &&
- (a->ptr.type == b->ptr.type)) ? 0 : -1);
+ return (((a->ptr.data == b->ptr.data) && (a->ptr.type == b->ptr.type)) ? 0 : -1);
}
static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
{
- return (((a->prop == b->prop) &&
- (a->ptr.data == b->ptr.data) &&
- (a->ptr.type == b->ptr.type)) ? 0 : -1);
+ return (((a->prop == b->prop) && (a->ptr.data == b->ptr.data) && (a->ptr.type == b->ptr.type)) ?
+ 0 :
+ -1);
}
static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
+ PyObject *res;
+ int ok = -1; /* zero is true */
- if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
- ok = pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
- }
+ if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
+ ok = pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
+ }
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
- return Py_INCREF_RET(res);
+ return Py_INCREF_RET(res);
}
static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
+ PyObject *res;
+ int ok = -1; /* zero is true */
- if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
- ok = pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
- }
+ if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
+ ok = pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
+ }
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
- return Py_INCREF_RET(res);
+ return Py_INCREF_RET(res);
}
/*----------------------repr--------------------------------------------*/
static PyObject *pyrna_struct_str(BPy_StructRNA *self)
{
- PyObject *ret;
- const char *name;
+ PyObject *ret;
+ const char *name;
- if (!PYRNA_STRUCT_IS_VALID(self)) {
- return PyUnicode_FromFormat("<bpy_struct, %.200s invalid>",
- Py_TYPE(self)->tp_name);
- }
+ if (!PYRNA_STRUCT_IS_VALID(self)) {
+ return PyUnicode_FromFormat("<bpy_struct, %.200s invalid>", Py_TYPE(self)->tp_name);
+ }
- /* print name if available */
- name = RNA_struct_name_get_alloc(&self->ptr, NULL, 0, NULL);
- if (name) {
- ret = PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>",
- RNA_struct_identifier(self->ptr.type),
- name);
- MEM_freeN((void *)name);
- return ret;
- }
+ /* print name if available */
+ name = RNA_struct_name_get_alloc(&self->ptr, NULL, 0, NULL);
+ if (name) {
+ ret = PyUnicode_FromFormat(
+ "<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
+ MEM_freeN((void *)name);
+ return ret;
+ }
- return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>",
- RNA_struct_identifier(self->ptr.type),
- self->ptr.data);
+ return PyUnicode_FromFormat(
+ "<bpy_struct, %.200s at %p>", RNA_struct_identifier(self->ptr.type), self->ptr.data);
}
static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
{
- ID *id = self->ptr.id.data;
- PyObject *tmp_str;
- PyObject *ret;
-
- if (id == NULL || !PYRNA_STRUCT_IS_VALID(self)) {
- /* fallback */
- return pyrna_struct_str(self);
- }
-
- tmp_str = PyUnicode_FromString(id->name + 2);
-
- if (RNA_struct_is_ID(self->ptr.type)) {
- ret = PyUnicode_FromFormat("bpy.data.%s[%R]",
- BKE_idcode_to_name_plural(GS(id->name)),
- tmp_str);
- }
- else {
- const char *path;
- path = RNA_path_from_ID_to_struct(&self->ptr);
- if (path) {
- if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
- ret = PyUnicode_FromFormat("bpy.data...%s",
- path);
- }
- else {
- ret = PyUnicode_FromFormat("bpy.data.%s[%R].%s",
- BKE_idcode_to_name_plural(GS(id->name)),
- tmp_str,
- path);
- }
-
- MEM_freeN((void *)path);
- }
- else { /* cant find, print something sane */
- ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
- BKE_idcode_to_name_plural(GS(id->name)),
- tmp_str,
- RNA_struct_identifier(self->ptr.type));
- }
- }
-
- Py_DECREF(tmp_str);
-
- return ret;
+ ID *id = self->ptr.id.data;
+ PyObject *tmp_str;
+ PyObject *ret;
+
+ if (id == NULL || !PYRNA_STRUCT_IS_VALID(self)) {
+ /* fallback */
+ return pyrna_struct_str(self);
+ }
+
+ tmp_str = PyUnicode_FromString(id->name + 2);
+
+ if (RNA_struct_is_ID(self->ptr.type)) {
+ ret = PyUnicode_FromFormat(
+ "bpy.data.%s[%R]", BKE_idcode_to_name_plural(GS(id->name)), tmp_str);
+ }
+ else {
+ const char *path;
+ path = RNA_path_from_ID_to_struct(&self->ptr);
+ if (path) {
+ if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
+ ret = PyUnicode_FromFormat("bpy.data...%s", path);
+ }
+ else {
+ ret = PyUnicode_FromFormat(
+ "bpy.data.%s[%R].%s", BKE_idcode_to_name_plural(GS(id->name)), tmp_str, path);
+ }
+
+ MEM_freeN((void *)path);
+ }
+ else { /* cant find, print something sane */
+ ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
+ BKE_idcode_to_name_plural(GS(id->name)),
+ tmp_str,
+ RNA_struct_identifier(self->ptr.type));
+ }
+ }
+
+ Py_DECREF(tmp_str);
+
+ return ret;
}
static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
{
- PyObject *ret;
- PointerRNA ptr;
- const char *name;
- const char *type_id = NULL;
- char type_fmt[64] = "";
- int type;
-
- PYRNA_PROP_CHECK_OBJ(self);
-
- type = RNA_property_type(self->prop);
-
- if (RNA_enum_id_from_value(rna_enum_property_type_items, type, &type_id) == 0) {
- PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
- return NULL;
- }
- else {
- /* this should never fail */
- int len = -1;
- char *c = type_fmt;
-
- while ((*c++ = tolower(*type_id++))) {}
-
- if (type == PROP_COLLECTION) {
- len = pyrna_prop_collection_length(self);
- }
- else if (RNA_property_array_check(self->prop)) {
- len = pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
- }
-
- if (len != -1) {
- sprintf(--c, "[%d]", len);
- }
- }
-
- /* if a pointer, try to print name of pointer target too */
- if (type == PROP_POINTER) {
- ptr = RNA_property_pointer_get(&self->ptr, self->prop);
- name = RNA_struct_name_get_alloc(&ptr, NULL, 0, NULL);
-
- if (name) {
- ret = PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
- type_fmt,
- RNA_struct_identifier(self->ptr.type),
- RNA_property_identifier(self->prop),
- name);
- MEM_freeN((void *)name);
- return ret;
- }
- }
- if (type == PROP_COLLECTION) {
- PointerRNA r_ptr;
- if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
- return PyUnicode_FromFormat("<bpy_%.200s, %.200s>",
- type_fmt,
- RNA_struct_identifier(r_ptr.type));
- }
- }
-
- return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
- type_fmt,
- RNA_struct_identifier(self->ptr.type),
- RNA_property_identifier(self->prop));
-}
-
-static PyObject *pyrna_prop_repr_ex(
- BPy_PropertyRNA *self,
- const int index_dim, const int index)
-{
- ID *id = self->ptr.id.data;
- PyObject *tmp_str;
- PyObject *ret;
- const char *path;
-
- PYRNA_PROP_CHECK_OBJ(self);
-
- if (id == NULL) {
- /* fallback */
- return pyrna_prop_str(self);
- }
-
- tmp_str = PyUnicode_FromString(id->name + 2);
-
- path = RNA_path_from_ID_to_property_index(&self->ptr, self->prop, index_dim, index);
-
- if (path) {
- const char *data_delim = (path[0] == '[') ? "" : ".";
- if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
- ret = PyUnicode_FromFormat("bpy.data...%s",
- path);
- }
- else {
- ret = PyUnicode_FromFormat("bpy.data.%s[%R]%s%s",
- BKE_idcode_to_name_plural(GS(id->name)),
- tmp_str,
- data_delim, path);
- }
-
- MEM_freeN((void *)path);
- }
- else { /* cant find, print something sane */
- ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
- BKE_idcode_to_name_plural(GS(id->name)),
- tmp_str,
- RNA_property_identifier(self->prop));
- }
-
- Py_DECREF(tmp_str);
-
- return ret;
+ PyObject *ret;
+ PointerRNA ptr;
+ const char *name;
+ const char *type_id = NULL;
+ char type_fmt[64] = "";
+ int type;
+
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ type = RNA_property_type(self->prop);
+
+ if (RNA_enum_id_from_value(rna_enum_property_type_items, type, &type_id) == 0) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "could not use property type, internal error"); /* should never happen */
+ return NULL;
+ }
+ else {
+ /* this should never fail */
+ int len = -1;
+ char *c = type_fmt;
+
+ while ((*c++ = tolower(*type_id++))) {
+ }
+
+ if (type == PROP_COLLECTION) {
+ len = pyrna_prop_collection_length(self);
+ }
+ else if (RNA_property_array_check(self->prop)) {
+ len = pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
+ }
+
+ if (len != -1) {
+ sprintf(--c, "[%d]", len);
+ }
+ }
+
+ /* if a pointer, try to print name of pointer target too */
+ if (type == PROP_POINTER) {
+ ptr = RNA_property_pointer_get(&self->ptr, self->prop);
+ name = RNA_struct_name_get_alloc(&ptr, NULL, 0, NULL);
+
+ if (name) {
+ ret = PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
+ type_fmt,
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop),
+ name);
+ MEM_freeN((void *)name);
+ return ret;
+ }
+ }
+ if (type == PROP_COLLECTION) {
+ PointerRNA r_ptr;
+ if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
+ return PyUnicode_FromFormat(
+ "<bpy_%.200s, %.200s>", type_fmt, RNA_struct_identifier(r_ptr.type));
+ }
+ }
+
+ return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
+ type_fmt,
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop));
+}
+
+static PyObject *pyrna_prop_repr_ex(BPy_PropertyRNA *self, const int index_dim, const int index)
+{
+ ID *id = self->ptr.id.data;
+ PyObject *tmp_str;
+ PyObject *ret;
+ const char *path;
+
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ if (id == NULL) {
+ /* fallback */
+ return pyrna_prop_str(self);
+ }
+
+ tmp_str = PyUnicode_FromString(id->name + 2);
+
+ path = RNA_path_from_ID_to_property_index(&self->ptr, self->prop, index_dim, index);
+
+ if (path) {
+ const char *data_delim = (path[0] == '[') ? "" : ".";
+ if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
+ ret = PyUnicode_FromFormat("bpy.data...%s", path);
+ }
+ else {
+ ret = PyUnicode_FromFormat("bpy.data.%s[%R]%s%s",
+ BKE_idcode_to_name_plural(GS(id->name)),
+ tmp_str,
+ data_delim,
+ path);
+ }
+
+ MEM_freeN((void *)path);
+ }
+ else { /* cant find, print something sane */
+ ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
+ BKE_idcode_to_name_plural(GS(id->name)),
+ tmp_str,
+ RNA_property_identifier(self->prop));
+ }
+
+ Py_DECREF(tmp_str);
+
+ return ret;
}
static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
{
- return pyrna_prop_repr_ex(self, 0, -1);
+ return pyrna_prop_repr_ex(self, 0, -1);
}
static PyObject *pyrna_prop_array_repr(BPy_PropertyArrayRNA *self)
{
- return pyrna_prop_repr_ex((BPy_PropertyRNA *)self, self->arraydim, self->arrayoffset);
+ return pyrna_prop_repr_ex((BPy_PropertyRNA *)self, self->arraydim, self->arrayoffset);
}
static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
{
- return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
- Py_TYPE(self)->tp_name,
- RNA_struct_identifier(self->ptr.type),
- RNA_function_identifier(self->func));
+ return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
+ Py_TYPE(self)->tp_name,
+ RNA_struct_identifier(self->ptr.type),
+ RNA_function_identifier(self->func));
}
-
static Py_hash_t pyrna_struct_hash(BPy_StructRNA *self)
{
- return _Py_HashPointer(self->ptr.data);
+ return _Py_HashPointer(self->ptr.data);
}
/* from python's meth_hash v3.1.2 */
static long pyrna_prop_hash(BPy_PropertyRNA *self)
{
- long x, y;
- if (self->ptr.data == NULL) {
- x = 0;
- }
- else {
- x = _Py_HashPointer(self->ptr.data);
- if (x == -1) {
- return -1;
- }
- }
- y = _Py_HashPointer((void *)(self->prop));
- if (y == -1) {
- return -1;
- }
- x ^= y;
- if (x == -1) {
- x = -2;
- }
- return x;
+ long x, y;
+ if (self->ptr.data == NULL) {
+ x = 0;
+ }
+ else {
+ x = _Py_HashPointer(self->ptr.data);
+ if (x == -1) {
+ return -1;
+ }
+ }
+ y = _Py_HashPointer((void *)(self->prop));
+ if (y == -1) {
+ return -1;
+ }
+ x ^= y;
+ if (x == -1) {
+ x = -2;
+ }
+ return x;
}
#ifdef USE_PYRNA_STRUCT_REFERENCE
static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
{
- Py_VISIT(self->reference);
- return 0;
+ Py_VISIT(self->reference);
+ return 0;
}
static int pyrna_struct_clear(BPy_StructRNA *self)
{
- Py_CLEAR(self->reference);
- return 0;
+ Py_CLEAR(self->reference);
+ return 0;
}
#endif /* !USE_PYRNA_STRUCT_REFERENCE */
@@ -1123,44 +1118,44 @@ static int pyrna_struct_clear(BPy_StructRNA *self)
static void pyrna_struct_dealloc(BPy_StructRNA *self)
{
#ifdef PYRNA_FREE_SUPPORT
- if (self->freeptr && self->ptr.data) {
- IDP_FreeProperty(self->ptr.data);
- MEM_freeN(self->ptr.data);
- self->ptr.data = NULL;
- }
+ if (self->freeptr && self->ptr.data) {
+ IDP_FreeProperty(self->ptr.data);
+ MEM_freeN(self->ptr.data);
+ self->ptr.data = NULL;
+ }
#endif /* PYRNA_FREE_SUPPORT */
#ifdef USE_WEAKREFS
- if (self->in_weakreflist != NULL) {
- PyObject_ClearWeakRefs((PyObject *)self);
- }
+ if (self->in_weakreflist != NULL) {
+ PyObject_ClearWeakRefs((PyObject *)self);
+ }
#endif
#ifdef USE_PYRNA_STRUCT_REFERENCE
- if (self->reference) {
- PyObject_GC_UnTrack(self);
- pyrna_struct_clear(self);
- }
+ if (self->reference) {
+ PyObject_GC_UnTrack(self);
+ pyrna_struct_clear(self);
+ }
#endif /* !USE_PYRNA_STRUCT_REFERENCE */
- /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
- Py_TYPE(self)->tp_free(self);
+ /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
+ Py_TYPE(self)->tp_free(self);
}
#ifdef USE_PYRNA_STRUCT_REFERENCE
static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
{
- if (self->reference) {
-// PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED ? */
- pyrna_struct_clear(self);
- }
- /* reference is now NULL */
+ if (self->reference) {
+ // PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED ? */
+ pyrna_struct_clear(self);
+ }
+ /* reference is now NULL */
- if (reference) {
- self->reference = reference;
- Py_INCREF(reference);
-// PyObject_GC_Track(self); /* INITIALIZED TRACKED ? */
- }
+ if (reference) {
+ self->reference = reference;
+ Py_INCREF(reference);
+ // PyObject_GC_Track(self); /* INITIALIZED TRACKED ? */
+ }
}
#endif /* !USE_PYRNA_STRUCT_REFERENCE */
@@ -1168,71 +1163,72 @@ static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
{
#ifdef USE_WEAKREFS
- if (self->in_weakreflist != NULL) {
- PyObject_ClearWeakRefs((PyObject *)self);
- }
+ if (self->in_weakreflist != NULL) {
+ PyObject_ClearWeakRefs((PyObject *)self);
+ }
#endif
- /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
- Py_TYPE(self)->tp_free(self);
+ /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
+ Py_TYPE(self)->tp_free(self);
}
static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
{
#ifdef USE_WEAKREFS
- if (self->in_weakreflist != NULL) {
- PyObject_ClearWeakRefs((PyObject *)self);
- }
+ if (self->in_weakreflist != NULL) {
+ PyObject_ClearWeakRefs((PyObject *)self);
+ }
#endif
- /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
- Py_TYPE(self)->tp_free(self);
+ /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
+ Py_TYPE(self)->tp_free(self);
}
static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
{
- const EnumPropertyItem *item;
- const char *result;
- bool free = false;
+ const EnumPropertyItem *item;
+ const char *result;
+ bool free = false;
- RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
- if (item) {
- result = BPy_enum_as_string(item);
- }
- else {
- result = "";
- }
+ RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
+ if (item) {
+ result = BPy_enum_as_string(item);
+ }
+ else {
+ result = "";
+ }
- if (free) {
- MEM_freeN((void *)item);
- }
+ if (free) {
+ MEM_freeN((void *)item);
+ }
- return result;
+ return result;
}
-
static int pyrna_string_to_enum(
- PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *r_value,
- const char *error_prefix)
-{
- const char *param = _PyUnicode_AsString(item);
-
- if (param == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected a string enum, not %.200s",
- error_prefix, Py_TYPE(item)->tp_name);
- return -1;
- }
- else {
- if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, r_value)) {
- const char *enum_str = pyrna_enum_as_string(ptr, prop);
- PyErr_Format(PyExc_TypeError,
- "%.200s enum \"%.200s\" not found in (%s)",
- error_prefix, param, enum_str);
- MEM_freeN((void *)enum_str);
- return -1;
- }
- }
-
- return 0;
+ PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *r_value, const char *error_prefix)
+{
+ const char *param = _PyUnicode_AsString(item);
+
+ if (param == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected a string enum, not %.200s",
+ error_prefix,
+ Py_TYPE(item)->tp_name);
+ return -1;
+ }
+ else {
+ if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, r_value)) {
+ const char *enum_str = pyrna_enum_as_string(ptr, prop);
+ PyErr_Format(PyExc_TypeError,
+ "%.200s enum \"%.200s\" not found in (%s)",
+ error_prefix,
+ param,
+ enum_str);
+ MEM_freeN((void *)enum_str);
+ return -1;
+ }
+ }
+
+ return 0;
}
/**
@@ -1243,1112 +1239,1150 @@ static int pyrna_string_to_enum(
* \param type_convert_sign: Maps signed to unsigned range,
* needed when we want to use the full range of a signed short/char.
*/
-BLI_bitmap *pyrna_set_to_enum_bitmap(
- const EnumPropertyItem *items, PyObject *value,
- int type_size, bool type_convert_sign,
- int bitmap_size,
- const char *error_prefix)
-{
- /* set looping */
- Py_ssize_t pos = 0;
- Py_ssize_t hash = 0;
- PyObject *key;
-
- BLI_bitmap *bitmap = BLI_BITMAP_NEW(bitmap_size, __func__);
-
- while (_PySet_NextEntry(value, &pos, &key, &hash)) {
- const char *param = _PyUnicode_AsString(key);
- if (param == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected a string, not %.200s",
- error_prefix, Py_TYPE(key)->tp_name);
- goto error;
- }
-
- int ret;
- if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
- goto error;
- }
-
- int index = ret;
-
- if (type_convert_sign) {
- if (type_size == 2) {
- union { signed short as_signed; unsigned short as_unsigned; } ret_convert;
- ret_convert.as_signed = (signed short)ret;
- index = (int)ret_convert.as_unsigned;
- }
- else if (type_size == 1) {
- union { signed char as_signed; unsigned char as_unsigned; } ret_convert;
- ret_convert.as_signed = (signed char)ret;
- index = (int)ret_convert.as_unsigned;
- }
- else {
- BLI_assert(0);
- }
- }
- BLI_assert(index < bitmap_size);
- BLI_BITMAP_ENABLE(bitmap, index);
- }
-
- return bitmap;
+BLI_bitmap *pyrna_set_to_enum_bitmap(const EnumPropertyItem *items,
+ PyObject *value,
+ int type_size,
+ bool type_convert_sign,
+ int bitmap_size,
+ const char *error_prefix)
+{
+ /* set looping */
+ Py_ssize_t pos = 0;
+ Py_ssize_t hash = 0;
+ PyObject *key;
+
+ BLI_bitmap *bitmap = BLI_BITMAP_NEW(bitmap_size, __func__);
+
+ while (_PySet_NextEntry(value, &pos, &key, &hash)) {
+ const char *param = _PyUnicode_AsString(key);
+ if (param == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected a string, not %.200s",
+ error_prefix,
+ Py_TYPE(key)->tp_name);
+ goto error;
+ }
+
+ int ret;
+ if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
+ goto error;
+ }
+
+ int index = ret;
+
+ if (type_convert_sign) {
+ if (type_size == 2) {
+ union {
+ signed short as_signed;
+ unsigned short as_unsigned;
+ } ret_convert;
+ ret_convert.as_signed = (signed short)ret;
+ index = (int)ret_convert.as_unsigned;
+ }
+ else if (type_size == 1) {
+ union {
+ signed char as_signed;
+ unsigned char as_unsigned;
+ } ret_convert;
+ ret_convert.as_signed = (signed char)ret;
+ index = (int)ret_convert.as_unsigned;
+ }
+ else {
+ BLI_assert(0);
+ }
+ }
+ BLI_assert(index < bitmap_size);
+ BLI_BITMAP_ENABLE(bitmap, index);
+ }
+
+ return bitmap;
error:
- MEM_freeN(bitmap);
- return NULL;
+ MEM_freeN(bitmap);
+ return NULL;
}
/* 'value' _must_ be a set type, error check before calling */
-int pyrna_set_to_enum_bitfield(
- const EnumPropertyItem *items, PyObject *value, int *r_value,
- const char *error_prefix)
+int pyrna_set_to_enum_bitfield(const EnumPropertyItem *items,
+ PyObject *value,
+ int *r_value,
+ const char *error_prefix)
{
- /* set of enum items, concatenate all values with OR */
- int ret, flag = 0;
+ /* set of enum items, concatenate all values with OR */
+ int ret, flag = 0;
- /* set looping */
- Py_ssize_t pos = 0;
- Py_ssize_t hash = 0;
- PyObject *key;
+ /* set looping */
+ Py_ssize_t pos = 0;
+ Py_ssize_t hash = 0;
+ PyObject *key;
- *r_value = 0;
+ *r_value = 0;
- while (_PySet_NextEntry(value, &pos, &key, &hash)) {
- const char *param = _PyUnicode_AsString(key);
+ while (_PySet_NextEntry(value, &pos, &key, &hash)) {
+ const char *param = _PyUnicode_AsString(key);
- if (param == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected a string, not %.200s",
- error_prefix, Py_TYPE(key)->tp_name);
- return -1;
- }
+ if (param == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s expected a string, not %.200s",
+ error_prefix,
+ Py_TYPE(key)->tp_name);
+ return -1;
+ }
- if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
- return -1;
- }
+ if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
+ return -1;
+ }
- flag |= ret;
- }
+ flag |= ret;
+ }
- *r_value = flag;
- return 0;
+ *r_value = flag;
+ return 0;
}
static int pyrna_prop_to_enum_bitfield(
- PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value,
- const char *error_prefix)
-{
- const EnumPropertyItem *item;
- int ret;
- bool free = false;
-
- *r_value = 0;
-
- if (!PyAnySet_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s, %.200s.%.200s expected a set, not a %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- return -1;
- }
-
- RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
-
- if (item) {
- ret = pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
- }
- else {
- if (PySet_GET_SIZE(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: empty enum \"%.200s\" could not have any values assigned",
- error_prefix, RNA_property_identifier(prop));
- ret = -1;
- }
- else {
- ret = 0;
- }
- }
-
- if (free) {
- MEM_freeN((void *)item);
- }
-
- return ret;
+ PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
+{
+ const EnumPropertyItem *item;
+ int ret;
+ bool free = false;
+
+ *r_value = 0;
+
+ if (!PyAnySet_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s, %.200s.%.200s expected a set, not a %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
+
+ if (item) {
+ ret = pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
+ }
+ else {
+ if (PySet_GET_SIZE(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: empty enum \"%.200s\" could not have any values assigned",
+ error_prefix,
+ RNA_property_identifier(prop));
+ ret = -1;
+ }
+ else {
+ ret = 0;
+ }
+ }
+
+ if (free) {
+ MEM_freeN((void *)item);
+ }
+
+ return ret;
}
PyObject *pyrna_enum_bitfield_to_py(const EnumPropertyItem *items, int value)
{
- PyObject *ret = PySet_New(NULL);
- const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
+ PyObject *ret = PySet_New(NULL);
+ const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
- if (RNA_enum_bitflag_identifiers(items, value, identifier)) {
- PyObject *item;
- int index;
- for (index = 0; identifier[index]; index++) {
- item = PyUnicode_FromString(identifier[index]);
- PySet_Add(ret, item);
- Py_DECREF(item);
- }
- }
+ if (RNA_enum_bitflag_identifiers(items, value, identifier)) {
+ PyObject *item;
+ int index;
+ for (index = 0; identifier[index]; index++) {
+ item = PyUnicode_FromString(identifier[index]);
+ PySet_Add(ret, item);
+ Py_DECREF(item);
+ }
+ }
- return ret;
+ return ret;
}
static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
{
- PyObject *item, *ret = NULL;
-
- if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
- const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
-
- ret = PySet_New(NULL);
-
- if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
- int index;
-
- for (index = 0; identifier[index]; index++) {
- item = PyUnicode_FromString(identifier[index]);
- PySet_Add(ret, item);
- Py_DECREF(item);
- }
-
- }
- }
- else {
- const char *identifier;
- if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
- ret = PyUnicode_FromString(identifier);
- }
- else {
- /* Static, no need to free. */
- const EnumPropertyItem *enum_item;
- bool free_dummy;
- RNA_property_enum_items_ex(NULL, ptr, prop, true, &enum_item, NULL, &free_dummy);
- BLI_assert(!free_dummy);
-
- /* Do not print warning in case of DummyRNA_NULL_items, this one will never match any value... */
- if (enum_item != DummyRNA_NULL_items) {
- const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
-
- /* prefer not fail silently in case of api errors, maybe disable it later */
- CLOG_WARN(BPY_LOG_RNA,
- "current value '%d' "
- "matches no enum in '%s', '%s', '%s'",
- val, RNA_struct_identifier(ptr->type),
- ptr_name, RNA_property_identifier(prop));
-
-#if 0 /* gives python decoding errors while generating docs :( */
- char error_str[256];
- BLI_snprintf(error_str, sizeof(error_str),
- "RNA Warning: Current value \"%d\" "
- "matches no enum in '%s', '%s', '%s'",
- val, RNA_struct_identifier(ptr->type),
- ptr_name, RNA_property_identifier(prop));
-
- PyErr_Warn(PyExc_RuntimeWarning, error_str);
+ PyObject *item, *ret = NULL;
+
+ if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
+ const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
+
+ ret = PySet_New(NULL);
+
+ if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
+ int index;
+
+ for (index = 0; identifier[index]; index++) {
+ item = PyUnicode_FromString(identifier[index]);
+ PySet_Add(ret, item);
+ Py_DECREF(item);
+ }
+ }
+ }
+ else {
+ const char *identifier;
+ if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
+ ret = PyUnicode_FromString(identifier);
+ }
+ else {
+ /* Static, no need to free. */
+ const EnumPropertyItem *enum_item;
+ bool free_dummy;
+ RNA_property_enum_items_ex(NULL, ptr, prop, true, &enum_item, NULL, &free_dummy);
+ BLI_assert(!free_dummy);
+
+ /* Do not print warning in case of DummyRNA_NULL_items, this one will never match any value... */
+ if (enum_item != DummyRNA_NULL_items) {
+ const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
+
+ /* prefer not fail silently in case of api errors, maybe disable it later */
+ CLOG_WARN(BPY_LOG_RNA,
+ "current value '%d' "
+ "matches no enum in '%s', '%s', '%s'",
+ val,
+ RNA_struct_identifier(ptr->type),
+ ptr_name,
+ RNA_property_identifier(prop));
+
+#if 0 /* gives python decoding errors while generating docs :( */
+ char error_str[256];
+ BLI_snprintf(error_str, sizeof(error_str),
+ "RNA Warning: Current value \"%d\" "
+ "matches no enum in '%s', '%s', '%s'",
+ val, RNA_struct_identifier(ptr->type),
+ ptr_name, RNA_property_identifier(prop));
+
+ PyErr_Warn(PyExc_RuntimeWarning, error_str);
#endif
- if (ptr_name) {
- MEM_freeN((void *)ptr_name);
- }
- }
+ if (ptr_name) {
+ MEM_freeN((void *)ptr_name);
+ }
+ }
- ret = PyUnicode_FromString("");
+ ret = PyUnicode_FromString("");
#if 0
- PyErr_Format(PyExc_AttributeError,
- "RNA Error: Current value \"%d\" matches no enum", val);
- ret = NULL;
+ PyErr_Format(PyExc_AttributeError,
+ "RNA Error: Current value \"%d\" matches no enum", val);
+ ret = NULL;
#endif
- }
- }
+ }
+ }
- return ret;
+ return ret;
}
PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
{
- PyObject *ret;
- const int type = RNA_property_type(prop);
-
- if (RNA_property_array_check(prop)) {
- return pyrna_py_from_array(ptr, prop);
- }
-
- /* see if we can coerce into a python type - PropertyType */
- switch (type) {
- case PROP_BOOLEAN:
- ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
- break;
- case PROP_INT:
- ret = PyLong_FromLong(RNA_property_int_get(ptr, prop));
- break;
- case PROP_FLOAT:
- ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
- break;
- case PROP_STRING:
- {
- const int subtype = RNA_property_subtype(prop);
- const char *buf;
- int buf_len;
- char buf_fixed[32];
-
- buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
+ PyObject *ret;
+ const int type = RNA_property_type(prop);
+
+ if (RNA_property_array_check(prop)) {
+ return pyrna_py_from_array(ptr, prop);
+ }
+
+ /* see if we can coerce into a python type - PropertyType */
+ switch (type) {
+ case PROP_BOOLEAN:
+ ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
+ break;
+ case PROP_INT:
+ ret = PyLong_FromLong(RNA_property_int_get(ptr, prop));
+ break;
+ case PROP_FLOAT:
+ ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
+ break;
+ case PROP_STRING: {
+ const int subtype = RNA_property_subtype(prop);
+ const char *buf;
+ int buf_len;
+ char buf_fixed[32];
+
+ buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
#ifdef USE_STRING_COERCE
- /* only file paths get special treatment, they may contain non utf-8 chars */
- if (subtype == PROP_BYTESTRING) {
- ret = PyBytes_FromStringAndSize(buf, buf_len);
- }
- else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
- ret = PyC_UnicodeFromByteAndSize(buf, buf_len);
- }
- else {
- ret = PyUnicode_FromStringAndSize(buf, buf_len);
- }
+ /* only file paths get special treatment, they may contain non utf-8 chars */
+ if (subtype == PROP_BYTESTRING) {
+ ret = PyBytes_FromStringAndSize(buf, buf_len);
+ }
+ else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
+ ret = PyC_UnicodeFromByteAndSize(buf, buf_len);
+ }
+ else {
+ ret = PyUnicode_FromStringAndSize(buf, buf_len);
+ }
#else /* USE_STRING_COERCE */
- if (subtype == PROP_BYTESTRING) {
- ret = PyBytes_FromStringAndSize(buf, buf_len);
- }
- else {
- ret = PyUnicode_FromStringAndSize(buf, buf_len);
- }
-#endif /* USE_STRING_COERCE */
- if (buf_fixed != buf) {
- MEM_freeN((void *)buf);
- }
- break;
- }
- case PROP_ENUM:
- {
- ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
- break;
- }
- case PROP_POINTER:
- {
- PointerRNA newptr;
- newptr = RNA_property_pointer_get(ptr, prop);
- if (newptr.data) {
- ret = pyrna_struct_CreatePyObject(&newptr);
- }
- else {
- ret = Py_None;
- Py_INCREF(ret);
- }
- break;
- }
- case PROP_COLLECTION:
- ret = pyrna_prop_CreatePyObject(ptr, prop);
- break;
- default:
- PyErr_Format(PyExc_TypeError,
- "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
- ret = NULL;
- break;
- }
-
- return ret;
+ if (subtype == PROP_BYTESTRING) {
+ ret = PyBytes_FromStringAndSize(buf, buf_len);
+ }
+ else {
+ ret = PyUnicode_FromStringAndSize(buf, buf_len);
+ }
+#endif /* USE_STRING_COERCE */
+ if (buf_fixed != buf) {
+ MEM_freeN((void *)buf);
+ }
+ break;
+ }
+ case PROP_ENUM: {
+ ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
+ break;
+ }
+ case PROP_POINTER: {
+ PointerRNA newptr;
+ newptr = RNA_property_pointer_get(ptr, prop);
+ if (newptr.data) {
+ ret = pyrna_struct_CreatePyObject(&newptr);
+ }
+ else {
+ ret = Py_None;
+ Py_INCREF(ret);
+ }
+ break;
+ }
+ case PROP_COLLECTION:
+ ret = pyrna_prop_CreatePyObject(ptr, prop);
+ break;
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)",
+ type);
+ ret = NULL;
+ break;
+ }
+
+ return ret;
}
/**
* This function is used by operators and converting dicts into collections.
* Its takes keyword args and fills them with property values
*/
-int pyrna_pydict_to_props(
- PointerRNA *ptr, PyObject *kw, const bool all_args,
- const char *error_prefix)
-{
- int error_val = 0;
- int totkw;
- const char *arg_name = NULL;
- PyObject *item;
-
- totkw = kw ? PyDict_Size(kw) : 0;
-
- RNA_STRUCT_BEGIN (ptr, prop)
- {
- arg_name = RNA_property_identifier(prop);
-
- if (STREQ(arg_name, "rna_type")) {
- continue;
- }
-
- if (kw == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: no keywords, expected \"%.200s\"",
- error_prefix, arg_name ? arg_name : "<UNKNOWN>");
- error_val = -1;
- break;
- }
-
- item = PyDict_GetItemString(kw, arg_name); /* wont set an error */
-
- if (item == NULL) {
- if (all_args) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" missing",
- error_prefix, arg_name ? arg_name : "<UNKNOWN>");
- error_val = -1; /* pyrna_py_to_prop sets the error */
- break;
- }
- }
- else {
- if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
- error_val = -1;
- break;
- }
- totkw--;
- }
- }
- RNA_STRUCT_END;
-
- if (error_val == 0 && totkw > 0) { /* some keywords were given that were not used :/ */
- PyObject *key, *value;
- Py_ssize_t pos = 0;
-
- while (PyDict_Next(kw, &pos, &key, &value)) {
- arg_name = _PyUnicode_AsString(key);
- if (RNA_struct_find_property(ptr, arg_name) == NULL) {
- break;
- }
- arg_name = NULL;
- }
-
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" unrecognized",
- error_prefix, arg_name ? arg_name : "<UNKNOWN>");
- error_val = -1;
- }
-
- return error_val;
+int pyrna_pydict_to_props(PointerRNA *ptr,
+ PyObject *kw,
+ const bool all_args,
+ const char *error_prefix)
+{
+ int error_val = 0;
+ int totkw;
+ const char *arg_name = NULL;
+ PyObject *item;
+
+ totkw = kw ? PyDict_Size(kw) : 0;
+
+ RNA_STRUCT_BEGIN (ptr, prop) {
+ arg_name = RNA_property_identifier(prop);
+
+ if (STREQ(arg_name, "rna_type")) {
+ continue;
+ }
+
+ if (kw == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: no keywords, expected \"%.200s\"",
+ error_prefix,
+ arg_name ? arg_name : "<UNKNOWN>");
+ error_val = -1;
+ break;
+ }
+
+ item = PyDict_GetItemString(kw, arg_name); /* wont set an error */
+
+ if (item == NULL) {
+ if (all_args) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" missing",
+ error_prefix,
+ arg_name ? arg_name : "<UNKNOWN>");
+ error_val = -1; /* pyrna_py_to_prop sets the error */
+ break;
+ }
+ }
+ else {
+ if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
+ error_val = -1;
+ break;
+ }
+ totkw--;
+ }
+ }
+ RNA_STRUCT_END;
+
+ if (error_val == 0 && totkw > 0) { /* some keywords were given that were not used :/ */
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+
+ while (PyDict_Next(kw, &pos, &key, &value)) {
+ arg_name = _PyUnicode_AsString(key);
+ if (RNA_struct_find_property(ptr, arg_name) == NULL) {
+ break;
+ }
+ arg_name = NULL;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: keyword \"%.200s\" unrecognized",
+ error_prefix,
+ arg_name ? arg_name : "<UNKNOWN>");
+ error_val = -1;
+ }
+
+ return error_val;
}
-
static PyObject *pyrna_func_to_py(const PointerRNA *ptr, FunctionRNA *func)
{
- BPy_FunctionRNA *pyfunc = (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
- pyfunc->ptr = *ptr;
- pyfunc->func = func;
- return (PyObject *)pyfunc;
+ BPy_FunctionRNA *pyfunc = (BPy_FunctionRNA *)PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
+ pyfunc->ptr = *ptr;
+ pyfunc->func = func;
+ return (PyObject *)pyfunc;
}
-
static int pyrna_py_to_prop(
- PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value,
- const char *error_prefix)
-{
- /* XXX hard limits should be checked here */
- const int type = RNA_property_type(prop);
-
-
- if (RNA_property_array_check(prop)) {
- /* done getting the length */
- if (pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
- return -1;
- }
- }
- else {
- /* Normal Property (not an array) */
-
- /* see if we can coerce into a python type - PropertyType */
- switch (type) {
- case PROP_BOOLEAN:
- {
- int param;
- /* prefer not to have an exception here
- * however so many poll functions return None or a valid Object.
- * its a hassle to convert these into a bool before returning, */
- if (RNA_parameter_flag(prop) & PARM_OUTPUT) {
- param = PyObject_IsTrue(value);
- }
- else {
- param = PyC_Long_AsI32(value);
-
- if (UNLIKELY(param & ~1)) { /* only accept 0/1 */
- param = -1; /* error out below */
- }
- }
-
- if (param == -1) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- if (data) {
- *((bool *)data) = param;
- }
- else {
- RNA_property_boolean_set(ptr, prop, param);
- }
- }
- break;
- }
- case PROP_INT:
- {
- int overflow;
- long param = PyLong_AsLongAndOverflow(value, &overflow);
- if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
- PyErr_Format(PyExc_ValueError,
- "%.200s %.200s.%.200s value not in 'int' range "
- "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- return -1;
- }
- else if (param == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected an int type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- int param_i = (int)param;
- if (data) {
- RNA_property_int_clamp(ptr, prop, &param_i);
- *((int *)data) = param_i;
- }
- else {
- RNA_property_int_set(ptr, prop, param_i);
- }
- }
- break;
- }
- case PROP_FLOAT:
- {
- float param = PyFloat_AsDouble(value);
- if (PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a float type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- return -1;
- }
- else {
- if (data) {
- RNA_property_float_clamp(ptr, prop, (float *)&param);
- *((float *)data) = param;
- }
- else {
- RNA_property_float_set(ptr, prop, param);
- }
- }
- break;
- }
- case PROP_STRING:
- {
- const int subtype = RNA_property_subtype(prop);
- const char *param;
-
- if (value == Py_None) {
- if ((RNA_property_flag(prop) & PROP_NEVER_NULL) == 0) {
- if (data) {
- *((char **)data) = (char *)NULL;
- }
- else {
- RNA_property_string_set(ptr, prop, NULL);
- }
- }
- else {
- PyC_Err_Format_Prefix(
- PyExc_TypeError,
- "%.200s %.200s.%.200s doesn't support None from string types",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- return -1;
- }
- }
- else if (subtype == PROP_BYTESTRING) {
-
- /* Byte String */
-
- param = PyBytes_AsString(value);
-
- if (param == NULL) {
- if (PyBytes_Check(value)) {
- /* there was an error assigning a string type,
- * rather than setting a new error, prefix the existing one
- */
- PyC_Err_Format_Prefix(PyExc_TypeError,
- "%.200s %.200s.%.200s error assigning bytes",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a bytes type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- }
-
- return -1;
- }
- else {
- if (data) {
- *((char **)data) = (char *)param;
- }
- else {
- RNA_property_string_set_bytes(ptr, prop, param, PyBytes_Size(value));
- }
- }
- }
- else {
- /* Unicode String */
+ PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
+{
+ /* XXX hard limits should be checked here */
+ const int type = RNA_property_type(prop);
+
+ if (RNA_property_array_check(prop)) {
+ /* done getting the length */
+ if (pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
+ return -1;
+ }
+ }
+ else {
+ /* Normal Property (not an array) */
+
+ /* see if we can coerce into a python type - PropertyType */
+ switch (type) {
+ case PROP_BOOLEAN: {
+ int param;
+ /* prefer not to have an exception here
+ * however so many poll functions return None or a valid Object.
+ * its a hassle to convert these into a bool before returning, */
+ if (RNA_parameter_flag(prop) & PARM_OUTPUT) {
+ param = PyObject_IsTrue(value);
+ }
+ else {
+ param = PyC_Long_AsI32(value);
+
+ if (UNLIKELY(param & ~1)) { /* only accept 0/1 */
+ param = -1; /* error out below */
+ }
+ }
+
+ if (param == -1) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ if (data) {
+ *((bool *)data) = param;
+ }
+ else {
+ RNA_property_boolean_set(ptr, prop, param);
+ }
+ }
+ break;
+ }
+ case PROP_INT: {
+ int overflow;
+ long param = PyLong_AsLongAndOverflow(value, &overflow);
+ if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s %.200s.%.200s value not in 'int' range "
+ "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ return -1;
+ }
+ else if (param == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected an int type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ int param_i = (int)param;
+ if (data) {
+ RNA_property_int_clamp(ptr, prop, &param_i);
+ *((int *)data) = param_i;
+ }
+ else {
+ RNA_property_int_set(ptr, prop, param_i);
+ }
+ }
+ break;
+ }
+ case PROP_FLOAT: {
+ float param = PyFloat_AsDouble(value);
+ if (PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a float type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else {
+ if (data) {
+ RNA_property_float_clamp(ptr, prop, (float *)&param);
+ *((float *)data) = param;
+ }
+ else {
+ RNA_property_float_set(ptr, prop, param);
+ }
+ }
+ break;
+ }
+ case PROP_STRING: {
+ const int subtype = RNA_property_subtype(prop);
+ const char *param;
+
+ if (value == Py_None) {
+ if ((RNA_property_flag(prop) & PROP_NEVER_NULL) == 0) {
+ if (data) {
+ *((char **)data) = (char *)NULL;
+ }
+ else {
+ RNA_property_string_set(ptr, prop, NULL);
+ }
+ }
+ else {
+ PyC_Err_Format_Prefix(PyExc_TypeError,
+ "%.200s %.200s.%.200s doesn't support None from string types",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ return -1;
+ }
+ }
+ else if (subtype == PROP_BYTESTRING) {
+
+ /* Byte String */
+
+ param = PyBytes_AsString(value);
+
+ if (param == NULL) {
+ if (PyBytes_Check(value)) {
+ /* there was an error assigning a string type,
+ * rather than setting a new error, prefix the existing one
+ */
+ PyC_Err_Format_Prefix(PyExc_TypeError,
+ "%.200s %.200s.%.200s error assigning bytes",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a bytes type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ }
+
+ return -1;
+ }
+ else {
+ if (data) {
+ *((char **)data) = (char *)param;
+ }
+ else {
+ RNA_property_string_set_bytes(ptr, prop, param, PyBytes_Size(value));
+ }
+ }
+ }
+ else {
+ /* Unicode String */
#ifdef USE_STRING_COERCE
- PyObject *value_coerce = NULL;
- if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
- /* TODO, get size */
- param = PyC_UnicodeAsByte(value, &value_coerce);
- }
- else {
- param = _PyUnicode_AsString(value);
- }
+ PyObject *value_coerce = NULL;
+ if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
+ /* TODO, get size */
+ param = PyC_UnicodeAsByte(value, &value_coerce);
+ }
+ else {
+ param = _PyUnicode_AsString(value);
+ }
#else /* USE_STRING_COERCE */
- param = _PyUnicode_AsString(value);
-#endif /* USE_STRING_COERCE */
-
- if (param == NULL) {
- if (PyUnicode_Check(value)) {
- /* there was an error assigning a string type,
- * rather than setting a new error, prefix the existing one
- */
- PyC_Err_Format_Prefix(PyExc_TypeError,
- "%.200s %.200s.%.200s error assigning string",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a string type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- }
-
- return -1;
- }
- else {
- /* same as bytes */
- /* XXX, this is suspect but needed for function calls, need to see if theres a better way */
- if (data) {
- *((char **)data) = (char *)param;
- }
- else {
- RNA_property_string_set(ptr, prop, param);
- }
- }
+ param = _PyUnicode_AsString(value);
+#endif /* USE_STRING_COERCE */
+
+ if (param == NULL) {
+ if (PyUnicode_Check(value)) {
+ /* there was an error assigning a string type,
+ * rather than setting a new error, prefix the existing one
+ */
+ PyC_Err_Format_Prefix(PyExc_TypeError,
+ "%.200s %.200s.%.200s error assigning string",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a string type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ }
+
+ return -1;
+ }
+ else {
+ /* same as bytes */
+ /* XXX, this is suspect but needed for function calls, need to see if theres a better way */
+ if (data) {
+ *((char **)data) = (char *)param;
+ }
+ else {
+ RNA_property_string_set(ptr, prop, param);
+ }
+ }
#ifdef USE_STRING_COERCE
- Py_XDECREF(value_coerce);
-#endif /* USE_STRING_COERCE */
- }
- break;
- }
- case PROP_ENUM:
- {
- int val = 0;
-
- /* type checkins is done by each function */
- if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
- /* set of enum items, concatenate all values with OR */
- if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) == -1) {
- return -1;
- }
- }
- else {
- /* simple enum string */
- if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) == -1) {
- return -1;
- }
- }
-
- if (data) {
- *((int *)data) = val;
- }
- else {
- RNA_property_enum_set(ptr, prop, val);
- }
-
- break;
- }
- case PROP_POINTER:
- {
- PyObject *value_new = NULL;
-
- StructRNA *ptr_type = RNA_property_pointer_type(ptr, prop);
- int flag = RNA_property_flag(prop);
- int flag_parameter = RNA_parameter_flag(prop);
-
- /* this is really nasty!, so we can fake the operator having direct properties eg:
- * layout.prop(self, "filepath")
- * ... which in fact should be
- * layout.prop(self.properties, "filepath")
- *
- * we need to do this trick.
- * if the prop is not an operator type and the pyobject is an operator,
- * use its properties in place of its self.
- *
- * this is so bad that its almost a good reason to do away with fake 'self.properties -> self'
- * class mixing if this causes problems in the future it should be removed.
- */
- if ((ptr_type == &RNA_AnyType) &&
- (BPy_StructRNA_Check(value)))
- {
- const StructRNA *base_type =
- RNA_struct_base_child_of(((const BPy_StructRNA *)value)->ptr.type, NULL);
- if (ELEM(base_type, &RNA_Operator, &RNA_Gizmo)) {
- value = PyObject_GetAttr(value, bpy_intern_str_properties);
- value_new = value;
- }
- }
-
- /* if property is an OperatorProperties/GizmoProperties pointer and value is a map,
- * forward back to pyrna_pydict_to_props */
- if (PyDict_Check(value)) {
- const StructRNA *base_type = RNA_struct_base_child_of(ptr_type, NULL);
- if (base_type == &RNA_OperatorProperties) {
- PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
- return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
- }
- else if (base_type == &RNA_GizmoProperties) {
- PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
- return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
- }
- }
-
- /* another exception, allow to pass a collection as an RNA property */
- if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
- PointerRNA c_ptr;
- BPy_PropertyRNA *value_prop = (BPy_PropertyRNA *)value;
- if (RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
- value = pyrna_struct_CreatePyObject(&c_ptr);
- value_new = value;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s collection has no type, "
- "cant be used as a %.200s type",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
- return -1;
- }
- }
-
- if (!BPy_StructRNA_Check(value) && value != Py_None) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
- Py_TYPE(value)->tp_name);
- Py_XDECREF(value_new); return -1;
- }
- else if ((flag & PROP_NEVER_NULL) && value == Py_None) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
- Py_XDECREF(value_new); return -1;
- }
- else if ((value != Py_None) &&
- ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA *)value)->ptr.id.data))
- {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s ID type does not support assignment to its self",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- Py_XDECREF(value_new); return -1;
- }
- else {
- BPy_StructRNA *param = (BPy_StructRNA *)value;
- bool raise_error = false;
- if (data) {
-
- if (flag_parameter & PARM_RNAPTR) {
- if (flag & PROP_THICK_WRAP) {
- if (value == Py_None) {
- memset(data, 0, sizeof(PointerRNA));
- }
- else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
- *((PointerRNA *)data) = param->ptr;
- }
- else {
- raise_error = true;
- }
- }
- else {
- /* for function calls, we sometimes want to pass the 'ptr' directly,
- * watch out that it remains valid!, possibly we could support this later if needed */
- BLI_assert(value_new == NULL);
- if (value == Py_None) {
- *((void **)data) = NULL;
- }
- else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
- *((PointerRNA **)data) = &param->ptr;
- }
- else {
- raise_error = true;
- }
- }
- }
- else if (value == Py_None) {
- *((void **)data) = NULL;
- }
- else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
- *((void **)data) = param->ptr.data;
- }
- else {
- raise_error = true;
- }
- }
- else {
- /* data == NULL, assign to RNA */
- if (value == Py_None || RNA_struct_is_a(param->ptr.type, ptr_type)) {
- RNA_property_pointer_set(ptr, prop, value == Py_None ? PointerRNA_NULL : param->ptr);
- }
- else {
- raise_error = true;
- }
- }
-
- if (raise_error) {
- if (pyrna_struct_validity_check(param) == -1) {
- /* error set */
- }
- else {
- PointerRNA tmp;
- RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
- RNA_struct_identifier(param->ptr.type));
- }
- Py_XDECREF(value_new); return -1;
- }
- }
-
- Py_XDECREF(value_new);
-
- break;
- }
- case PROP_COLLECTION:
- {
- Py_ssize_t seq_len, i;
- PyObject *item;
- PointerRNA itemptr;
- ListBase *lb;
- CollectionPointerLink *link;
-
- lb = (data) ? (ListBase *)data : NULL;
-
- /* convert a sequence of dict's into a collection */
- if (!PySequence_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
- return -1;
- }
-
- seq_len = PySequence_Size(value);
- for (i = 0; i < seq_len; i++) {
- item = PySequence_GetItem(value, i);
-
- if (item == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), i);
- Py_XDECREF(item);
- return -1;
- }
-
- if (PyDict_Check(item) == 0) {
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s expected a each sequence "
- "member to be a dict for an RNA collection, not %.200s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
- Py_XDECREF(item);
- return -1;
- }
-
- if (lb) {
- link = MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
- link->ptr = itemptr;
- BLI_addtail(lb, link);
- }
- else {
- RNA_property_collection_add(ptr, prop, &itemptr);
- }
-
- if (pyrna_pydict_to_props(
- &itemptr, item, true,
- "Converting a python list to an RNA collection") == -1)
- {
- PyObject *msg = PyC_ExceptionBuffer();
- const char *msg_char = _PyUnicode_AsString(msg);
-
- PyErr_Format(PyExc_TypeError,
- "%.200s %.200s.%.200s error converting a member of a collection "
- "from a dicts into an RNA collection, failed with: %s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), msg_char);
-
- Py_DECREF(item);
- Py_DECREF(msg);
- return -1;
- }
- Py_DECREF(item);
- }
-
- break;
- }
- default:
- PyErr_Format(PyExc_AttributeError,
- "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop));
- return -1;
- }
- }
-
- /* Run rna property functions */
- if (RNA_property_update_check(prop)) {
- RNA_property_update(BPy_GetContext(), ptr, prop);
- }
-
- return 0;
+ Py_XDECREF(value_coerce);
+#endif /* USE_STRING_COERCE */
+ }
+ break;
+ }
+ case PROP_ENUM: {
+ int val = 0;
+
+ /* type checkins is done by each function */
+ if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
+ /* set of enum items, concatenate all values with OR */
+ if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) == -1) {
+ return -1;
+ }
+ }
+ else {
+ /* simple enum string */
+ if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) == -1) {
+ return -1;
+ }
+ }
+
+ if (data) {
+ *((int *)data) = val;
+ }
+ else {
+ RNA_property_enum_set(ptr, prop, val);
+ }
+
+ break;
+ }
+ case PROP_POINTER: {
+ PyObject *value_new = NULL;
+
+ StructRNA *ptr_type = RNA_property_pointer_type(ptr, prop);
+ int flag = RNA_property_flag(prop);
+ int flag_parameter = RNA_parameter_flag(prop);
+
+ /* this is really nasty!, so we can fake the operator having direct properties eg:
+ * layout.prop(self, "filepath")
+ * ... which in fact should be
+ * layout.prop(self.properties, "filepath")
+ *
+ * we need to do this trick.
+ * if the prop is not an operator type and the pyobject is an operator,
+ * use its properties in place of its self.
+ *
+ * this is so bad that its almost a good reason to do away with fake 'self.properties -> self'
+ * class mixing if this causes problems in the future it should be removed.
+ */
+ if ((ptr_type == &RNA_AnyType) && (BPy_StructRNA_Check(value))) {
+ const StructRNA *base_type = RNA_struct_base_child_of(
+ ((const BPy_StructRNA *)value)->ptr.type, NULL);
+ if (ELEM(base_type, &RNA_Operator, &RNA_Gizmo)) {
+ value = PyObject_GetAttr(value, bpy_intern_str_properties);
+ value_new = value;
+ }
+ }
+
+ /* if property is an OperatorProperties/GizmoProperties pointer and value is a map,
+ * forward back to pyrna_pydict_to_props */
+ if (PyDict_Check(value)) {
+ const StructRNA *base_type = RNA_struct_base_child_of(ptr_type, NULL);
+ if (base_type == &RNA_OperatorProperties) {
+ PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
+ return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
+ }
+ else if (base_type == &RNA_GizmoProperties) {
+ PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
+ return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
+ }
+ }
+
+ /* another exception, allow to pass a collection as an RNA property */
+ if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
+ PointerRNA c_ptr;
+ BPy_PropertyRNA *value_prop = (BPy_PropertyRNA *)value;
+ if (RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
+ value = pyrna_struct_CreatePyObject(&c_ptr);
+ value_new = value;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s collection has no type, "
+ "cant be used as a %.200s type",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ RNA_struct_identifier(ptr_type));
+ return -1;
+ }
+ }
+
+ if (!BPy_StructRNA_Check(value) && value != Py_None) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ RNA_struct_identifier(ptr_type),
+ Py_TYPE(value)->tp_name);
+ Py_XDECREF(value_new);
+ return -1;
+ }
+ else if ((flag & PROP_NEVER_NULL) && value == Py_None) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ RNA_struct_identifier(ptr_type));
+ Py_XDECREF(value_new);
+ return -1;
+ }
+ else if ((value != Py_None) && ((flag & PROP_ID_SELF_CHECK) &&
+ ptr->id.data == ((BPy_StructRNA *)value)->ptr.id.data)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s ID type does not support assignment to its self",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ Py_XDECREF(value_new);
+ return -1;
+ }
+ else {
+ BPy_StructRNA *param = (BPy_StructRNA *)value;
+ bool raise_error = false;
+ if (data) {
+
+ if (flag_parameter & PARM_RNAPTR) {
+ if (flag & PROP_THICK_WRAP) {
+ if (value == Py_None) {
+ memset(data, 0, sizeof(PointerRNA));
+ }
+ else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
+ *((PointerRNA *)data) = param->ptr;
+ }
+ else {
+ raise_error = true;
+ }
+ }
+ else {
+ /* for function calls, we sometimes want to pass the 'ptr' directly,
+ * watch out that it remains valid!, possibly we could support this later if needed */
+ BLI_assert(value_new == NULL);
+ if (value == Py_None) {
+ *((void **)data) = NULL;
+ }
+ else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
+ *((PointerRNA **)data) = &param->ptr;
+ }
+ else {
+ raise_error = true;
+ }
+ }
+ }
+ else if (value == Py_None) {
+ *((void **)data) = NULL;
+ }
+ else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
+ *((void **)data) = param->ptr.data;
+ }
+ else {
+ raise_error = true;
+ }
+ }
+ else {
+ /* data == NULL, assign to RNA */
+ if (value == Py_None || RNA_struct_is_a(param->ptr.type, ptr_type)) {
+ RNA_property_pointer_set(ptr, prop, value == Py_None ? PointerRNA_NULL : param->ptr);
+ }
+ else {
+ raise_error = true;
+ }
+ }
+
+ if (raise_error) {
+ if (pyrna_struct_validity_check(param) == -1) {
+ /* error set */
+ }
+ else {
+ PointerRNA tmp;
+ RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ RNA_struct_identifier(tmp.type),
+ RNA_struct_identifier(param->ptr.type));
+ }
+ Py_XDECREF(value_new);
+ return -1;
+ }
+ }
+
+ Py_XDECREF(value_new);
+
+ break;
+ }
+ case PROP_COLLECTION: {
+ Py_ssize_t seq_len, i;
+ PyObject *item;
+ PointerRNA itemptr;
+ ListBase *lb;
+ CollectionPointerLink *link;
+
+ lb = (data) ? (ListBase *)data : NULL;
+
+ /* convert a sequence of dict's into a collection */
+ if (!PySequence_Check(value)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ seq_len = PySequence_Size(value);
+ for (i = 0; i < seq_len; i++) {
+ item = PySequence_GetItem(value, i);
+
+ if (item == NULL) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ i);
+ Py_XDECREF(item);
+ return -1;
+ }
+
+ if (PyDict_Check(item) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s expected a each sequence "
+ "member to be a dict for an RNA collection, not %.200s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ Py_TYPE(item)->tp_name);
+ Py_XDECREF(item);
+ return -1;
+ }
+
+ if (lb) {
+ link = MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
+ link->ptr = itemptr;
+ BLI_addtail(lb, link);
+ }
+ else {
+ RNA_property_collection_add(ptr, prop, &itemptr);
+ }
+
+ if (pyrna_pydict_to_props(
+ &itemptr, item, true, "Converting a python list to an RNA collection") == -1) {
+ PyObject *msg = PyC_ExceptionBuffer();
+ const char *msg_char = _PyUnicode_AsString(msg);
+
+ PyErr_Format(PyExc_TypeError,
+ "%.200s %.200s.%.200s error converting a member of a collection "
+ "from a dicts into an RNA collection, failed with: %s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ msg_char);
+
+ Py_DECREF(item);
+ Py_DECREF(msg);
+ return -1;
+ }
+ Py_DECREF(item);
+ }
+
+ break;
+ }
+ default:
+ PyErr_Format(PyExc_AttributeError,
+ "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ return -1;
+ }
+ }
+
+ /* Run rna property functions */
+ if (RNA_property_update_check(prop)) {
+ RNA_property_update(BPy_GetContext(), ptr, prop);
+ }
+
+ return 0;
}
static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
{
- PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
- return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
+ PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
+ return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
}
static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
{
- int ret = 0;
- PointerRNA *ptr = &self->ptr;
- PropertyRNA *prop = self->prop;
-
- const int totdim = RNA_property_array_dimension(ptr, prop, NULL);
-
- if (totdim > 1) {
- /* char error_str[512]; */
- if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
- /* error is set */
- ret = -1;
- }
- }
- else {
- /* see if we can coerce into a python type - PropertyType */
- switch (RNA_property_type(prop)) {
- case PROP_BOOLEAN:
- {
- int param = PyC_Long_AsBool(value);
-
- if (param == -1) {
- /* error is set */
- ret = -1;
- }
- else {
- RNA_property_boolean_set_index(ptr, prop, index, param);
- }
- break;
- }
- case PROP_INT:
- {
- int param = PyC_Long_AsI32(value);
- if (param == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected an int type");
- ret = -1;
- }
- else {
- RNA_property_int_clamp(ptr, prop, &param);
- RNA_property_int_set_index(ptr, prop, index, param);
- }
- break;
- }
- case PROP_FLOAT:
- {
- float param = PyFloat_AsDouble(value);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "expected a float type");
- ret = -1;
- }
- else {
- RNA_property_float_clamp(ptr, prop, &param);
- RNA_property_float_set_index(ptr, prop, index, param);
- }
- break;
- }
- default:
- PyErr_SetString(PyExc_AttributeError, "not an array type");
- ret = -1;
- break;
- }
- }
-
- /* Run rna property functions */
- if (RNA_property_update_check(prop)) {
- RNA_property_update(BPy_GetContext(), ptr, prop);
- }
-
- return ret;
+ int ret = 0;
+ PointerRNA *ptr = &self->ptr;
+ PropertyRNA *prop = self->prop;
+
+ const int totdim = RNA_property_array_dimension(ptr, prop, NULL);
+
+ if (totdim > 1) {
+ /* char error_str[512]; */
+ if (pyrna_py_to_array_index(
+ &self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
+ /* error is set */
+ ret = -1;
+ }
+ }
+ else {
+ /* see if we can coerce into a python type - PropertyType */
+ switch (RNA_property_type(prop)) {
+ case PROP_BOOLEAN: {
+ int param = PyC_Long_AsBool(value);
+
+ if (param == -1) {
+ /* error is set */
+ ret = -1;
+ }
+ else {
+ RNA_property_boolean_set_index(ptr, prop, index, param);
+ }
+ break;
+ }
+ case PROP_INT: {
+ int param = PyC_Long_AsI32(value);
+ if (param == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected an int type");
+ ret = -1;
+ }
+ else {
+ RNA_property_int_clamp(ptr, prop, &param);
+ RNA_property_int_set_index(ptr, prop, index, param);
+ }
+ break;
+ }
+ case PROP_FLOAT: {
+ float param = PyFloat_AsDouble(value);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "expected a float type");
+ ret = -1;
+ }
+ else {
+ RNA_property_float_clamp(ptr, prop, &param);
+ RNA_property_float_set_index(ptr, prop, index, param);
+ }
+ break;
+ }
+ default:
+ PyErr_SetString(PyExc_AttributeError, "not an array type");
+ ret = -1;
+ break;
+ }
+ }
+
+ /* Run rna property functions */
+ if (RNA_property_update_check(prop)) {
+ RNA_property_update(BPy_GetContext(), ptr, prop);
+ }
+
+ return ret;
}
/* ---------------sequence------------------------------------------- */
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
{
- PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
+ PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
- if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1) {
- return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
- }
- else {
- return RNA_property_array_length(&self->ptr, self->prop);
- }
+ if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1) {
+ return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
+ }
+ else {
+ return RNA_property_array_length(&self->ptr, self->prop);
+ }
}
static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
{
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- return RNA_property_collection_length(&self->ptr, self->prop);
+ return RNA_property_collection_length(&self->ptr, self->prop);
}
/* bool functions are for speed, so we can avoid getting the length
* of 1000's of items in a linked list for eg. */
static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
{
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
+ return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
}
static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
{
- /* no callback defined, just iterate and find the nth item */
- CollectionPropertyIterator iter;
- int test;
+ /* no callback defined, just iterate and find the nth item */
+ CollectionPropertyIterator iter;
+ int test;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- RNA_property_collection_begin(&self->ptr, self->prop, &iter);
- test = iter.valid;
- RNA_property_collection_end(&iter);
- return test;
+ RNA_property_collection_begin(&self->ptr, self->prop, &iter);
+ test = iter.valid;
+ RNA_property_collection_end(&iter);
+ return test;
}
-
/* notice getting the length of the collection is avoided unless negative
* index is used or to detect internal error with a valid index.
* This is done for faster lookups. */
-#define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err) \
- if (keynum < 0) { \
- keynum_abs += RNA_property_collection_length(&self->ptr, self->prop); \
- if (keynum_abs < 0) { \
- PyErr_Format(PyExc_IndexError, \
- "bpy_prop_collection[%d]: out of range.", keynum); \
- return ret_err; \
- } \
- } (void)0
-
+#define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err) \
+ if (keynum < 0) { \
+ keynum_abs += RNA_property_collection_length(&self->ptr, self->prop); \
+ if (keynum_abs < 0) { \
+ PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum); \
+ return ret_err; \
+ } \
+ } \
+ (void)0
/* internal use only */
static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
{
- PointerRNA newptr;
- Py_ssize_t keynum_abs = keynum;
-
- PYRNA_PROP_CHECK_OBJ(self);
-
- PYRNA_PROP_COLLECTION_ABS_INDEX(NULL);
-
- if (RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
- return pyrna_struct_CreatePyObject(&newptr);
- }
- else {
- const int len = RNA_property_collection_length(&self->ptr, self->prop);
- if (keynum_abs >= len) {
- PyErr_Format(PyExc_IndexError,
- "bpy_prop_collection[index]: "
- "index %d out of range, size %d", keynum, len);
- }
- else {
- PyErr_Format(PyExc_RuntimeError,
- "bpy_prop_collection[index]: internal error, "
- "valid index %d given in %d sized collection but value not found",
- keynum_abs, len);
- }
-
- return NULL;
- }
+ PointerRNA newptr;
+ Py_ssize_t keynum_abs = keynum;
+
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ PYRNA_PROP_COLLECTION_ABS_INDEX(NULL);
+
+ if (RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
+ return pyrna_struct_CreatePyObject(&newptr);
+ }
+ else {
+ const int len = RNA_property_collection_length(&self->ptr, self->prop);
+ if (keynum_abs >= len) {
+ PyErr_Format(PyExc_IndexError,
+ "bpy_prop_collection[index]: "
+ "index %d out of range, size %d",
+ keynum,
+ len);
+ }
+ else {
+ PyErr_Format(PyExc_RuntimeError,
+ "bpy_prop_collection[index]: internal error, "
+ "valid index %d given in %d sized collection but value not found",
+ keynum_abs,
+ len);
+ }
+
+ return NULL;
+ }
}
/* values type must have been already checked */
-static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum, PyObject *value)
+static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self,
+ Py_ssize_t keynum,
+ PyObject *value)
{
- Py_ssize_t keynum_abs = keynum;
- const PointerRNA *ptr = (value == Py_None) ? (&PointerRNA_NULL) : &((BPy_StructRNA *)value)->ptr;
+ Py_ssize_t keynum_abs = keynum;
+ const PointerRNA *ptr = (value == Py_None) ? (&PointerRNA_NULL) : &((BPy_StructRNA *)value)->ptr;
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- PYRNA_PROP_COLLECTION_ABS_INDEX(-1);
+ PYRNA_PROP_COLLECTION_ABS_INDEX(-1);
- if (RNA_property_collection_assign_int(&self->ptr, self->prop, keynum_abs, ptr) == 0) {
- const int len = RNA_property_collection_length(&self->ptr, self->prop);
- if (keynum_abs >= len) {
- PyErr_Format(PyExc_IndexError,
- "bpy_prop_collection[index] = value: "
- "index %d out of range, size %d", keynum, len);
- }
- else {
+ if (RNA_property_collection_assign_int(&self->ptr, self->prop, keynum_abs, ptr) == 0) {
+ const int len = RNA_property_collection_length(&self->ptr, self->prop);
+ if (keynum_abs >= len) {
+ PyErr_Format(PyExc_IndexError,
+ "bpy_prop_collection[index] = value: "
+ "index %d out of range, size %d",
+ keynum,
+ len);
+ }
+ else {
- PyErr_Format(PyExc_IndexError,
- "bpy_prop_collection[index] = value: "
- "failed assignment (unknown reason)", keynum);
- }
- return -1;
- }
+ PyErr_Format(PyExc_IndexError,
+ "bpy_prop_collection[index] = value: "
+ "failed assignment (unknown reason)",
+ keynum);
+ }
+ return -1;
+ }
- return 0;
+ return 0;
}
static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
{
- int len;
+ int len;
- PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
+ PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
- len = pyrna_prop_array_length(self);
+ len = pyrna_prop_array_length(self);
- if (keynum < 0) {
- keynum += len;
- }
+ if (keynum < 0) {
+ keynum += len;
+ }
- if (keynum >= 0 && keynum < len) {
- return pyrna_prop_array_to_py_index(self, keynum);
- }
+ if (keynum >= 0 && keynum < len) {
+ return pyrna_prop_array_to_py_index(self, keynum);
+ }
- PyErr_Format(PyExc_IndexError,
- "bpy_prop_array[index]: index %d out of range", keynum);
- return NULL;
+ PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
+ return NULL;
}
static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
{
- PointerRNA newptr;
+ PointerRNA newptr;
- PYRNA_PROP_CHECK_OBJ(self);
+ PYRNA_PROP_CHECK_OBJ(self);
- if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr)) {
- return pyrna_struct_CreatePyObject(&newptr);
- }
+ if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr)) {
+ return pyrna_struct_CreatePyObject(&newptr);
+ }
- PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
- return NULL;
+ PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
+ return NULL;
}
/* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
@@ -2363,482 +2397,498 @@ static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, cons
* - 0: not found
* - 1: found
*/
-static int pyrna_prop_collection_subscript_str_lib_pair_ptr(
- BPy_PropertyRNA *self, PyObject *key,
- const char *err_prefix, const short err_not_found,
- PointerRNA *r_ptr)
-{
- const char *keyname;
-
- /* first validate the args, all we know is that they are a tuple */
- if (PyTuple_GET_SIZE(key) != 2) {
- PyErr_Format(PyExc_KeyError,
- "%s: tuple key must be a pair, not size %d",
- err_prefix, PyTuple_GET_SIZE(key));
- return -1;
- }
- else if (self->ptr.type != &RNA_BlendData) {
- PyErr_Format(PyExc_KeyError,
- "%s: is only valid for bpy.data collections, not %.200s",
- err_prefix, RNA_struct_identifier(self->ptr.type));
- return -1;
- }
- else if ((keyname = _PyUnicode_AsString(PyTuple_GET_ITEM(key, 0))) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "%s: id must be a string, not %.200s",
- err_prefix, Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
- return -1;
- }
- else {
- PyObject *keylib = PyTuple_GET_ITEM(key, 1);
- Library *lib;
- bool found = false;
-
- if (keylib == Py_None) {
- lib = NULL;
- }
- else if (PyUnicode_Check(keylib)) {
- Main *bmain = self->ptr.data;
- const char *keylib_str = _PyUnicode_AsString(keylib);
- lib = BLI_findstring(&bmain->libraries, keylib_str, offsetof(Library, name));
- if (lib == NULL) {
- if (err_not_found) {
- PyErr_Format(PyExc_KeyError,
- "%s: lib name '%.240s' "
- "does not reference a valid library",
- err_prefix, keylib_str);
- return -1;
- }
- else {
- return 0;
- }
-
- }
- }
- else {
- PyErr_Format(PyExc_KeyError,
- "%s: lib must be a string or None, not %.200s",
- err_prefix, Py_TYPE(keylib)->tp_name);
- return -1;
- }
-
- /* lib is either a valid pointer or NULL,
- * either way can do direct comparison with id.lib */
-
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- ID *id = itemptr.data; /* always an ID */
- if (id->lib == lib && (STREQLEN(keyname, id->name + 2, sizeof(id->name) - 2))) {
- found = true;
- if (r_ptr) {
- *r_ptr = itemptr;
- }
- break;
- }
- }
- RNA_PROP_END;
-
- /* we may want to fail silently as with collection.get() */
- if ((found == false) && err_not_found) {
- /* only runs for getitem access so use fixed string */
- PyErr_SetString(PyExc_KeyError,
- "bpy_prop_collection[key, lib]: not found");
- return -1;
- }
- else {
- return found; /* 1 / 0, no exception */
- }
- }
-}
-
-static PyObject *pyrna_prop_collection_subscript_str_lib_pair(
- BPy_PropertyRNA *self, PyObject *key,
- const char *err_prefix, const bool err_not_found)
-{
- PointerRNA ptr;
- const int contains = pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key, err_prefix, err_not_found, &ptr);
-
- if (contains == 1) {
- return pyrna_struct_CreatePyObject(&ptr);
- }
- else {
- return NULL;
- }
-}
-
-
-static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
-{
- CollectionPropertyIterator rna_macro_iter;
- int count;
-
- PyObject *list;
- PyObject *item;
-
- PYRNA_PROP_CHECK_OBJ(self);
-
- list = PyList_New(0);
-
- /* skip to start */
- RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter);
- RNA_property_collection_skip(&rna_macro_iter, start);
-
- /* add items until stop */
- for (count = start; rna_macro_iter.valid;
- RNA_property_collection_next(&rna_macro_iter))
- {
- item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
- PyList_APPEND(list, item);
-
- count++;
- if (count == stop) {
- break;
- }
- }
-
- RNA_property_collection_end(&rna_macro_iter);
-
- return list;
+static int pyrna_prop_collection_subscript_str_lib_pair_ptr(BPy_PropertyRNA *self,
+ PyObject *key,
+ const char *err_prefix,
+ const short err_not_found,
+ PointerRNA *r_ptr)
+{
+ const char *keyname;
+
+ /* first validate the args, all we know is that they are a tuple */
+ if (PyTuple_GET_SIZE(key) != 2) {
+ PyErr_Format(PyExc_KeyError,
+ "%s: tuple key must be a pair, not size %d",
+ err_prefix,
+ PyTuple_GET_SIZE(key));
+ return -1;
+ }
+ else if (self->ptr.type != &RNA_BlendData) {
+ PyErr_Format(PyExc_KeyError,
+ "%s: is only valid for bpy.data collections, not %.200s",
+ err_prefix,
+ RNA_struct_identifier(self->ptr.type));
+ return -1;
+ }
+ else if ((keyname = _PyUnicode_AsString(PyTuple_GET_ITEM(key, 0))) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "%s: id must be a string, not %.200s",
+ err_prefix,
+ Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
+ return -1;
+ }
+ else {
+ PyObject *keylib = PyTuple_GET_ITEM(key, 1);
+ Library *lib;
+ bool found = false;
+
+ if (keylib == Py_None) {
+ lib = NULL;
+ }
+ else if (PyUnicode_Check(keylib)) {
+ Main *bmain = self->ptr.data;
+ const char *keylib_str = _PyUnicode_AsString(keylib);
+ lib = BLI_findstring(&bmain->libraries, keylib_str, offsetof(Library, name));
+ if (lib == NULL) {
+ if (err_not_found) {
+ PyErr_Format(PyExc_KeyError,
+ "%s: lib name '%.240s' "
+ "does not reference a valid library",
+ err_prefix,
+ keylib_str);
+ return -1;
+ }
+ else {
+ return 0;
+ }
+ }
+ }
+ else {
+ PyErr_Format(PyExc_KeyError,
+ "%s: lib must be a string or None, not %.200s",
+ err_prefix,
+ Py_TYPE(keylib)->tp_name);
+ return -1;
+ }
+
+ /* lib is either a valid pointer or NULL,
+ * either way can do direct comparison with id.lib */
+
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ ID *id = itemptr.data; /* always an ID */
+ if (id->lib == lib && (STREQLEN(keyname, id->name + 2, sizeof(id->name) - 2))) {
+ found = true;
+ if (r_ptr) {
+ *r_ptr = itemptr;
+ }
+ break;
+ }
+ }
+ RNA_PROP_END;
+
+ /* we may want to fail silently as with collection.get() */
+ if ((found == false) && err_not_found) {
+ /* only runs for getitem access so use fixed string */
+ PyErr_SetString(PyExc_KeyError, "bpy_prop_collection[key, lib]: not found");
+ return -1;
+ }
+ else {
+ return found; /* 1 / 0, no exception */
+ }
+ }
+}
+
+static PyObject *pyrna_prop_collection_subscript_str_lib_pair(BPy_PropertyRNA *self,
+ PyObject *key,
+ const char *err_prefix,
+ const bool err_not_found)
+{
+ PointerRNA ptr;
+ const int contains = pyrna_prop_collection_subscript_str_lib_pair_ptr(
+ self, key, err_prefix, err_not_found, &ptr);
+
+ if (contains == 1) {
+ return pyrna_struct_CreatePyObject(&ptr);
+ }
+ else {
+ return NULL;
+ }
+}
+
+static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self,
+ Py_ssize_t start,
+ Py_ssize_t stop)
+{
+ CollectionPropertyIterator rna_macro_iter;
+ int count;
+
+ PyObject *list;
+ PyObject *item;
+
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ list = PyList_New(0);
+
+ /* skip to start */
+ RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter);
+ RNA_property_collection_skip(&rna_macro_iter, start);
+
+ /* add items until stop */
+ for (count = start; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
+ item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
+ PyList_APPEND(list, item);
+
+ count++;
+ if (count == stop) {
+ break;
+ }
+ }
+
+ RNA_property_collection_end(&rna_macro_iter);
+
+ return list;
}
/* TODO - dimensions
* note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
* since at the moment it reads (and even allocates) the entire array for each index.
*/
-static PyObject *pyrna_prop_array_subscript_slice(
- BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
- Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
-{
- int count, totdim;
- PyObject *tuple;
-
- /* isn't needed, internal use only */
- // PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
-
- tuple = PyTuple_New(stop - start);
-
- totdim = RNA_property_array_dimension(ptr, prop, NULL);
-
- if (totdim > 1) {
- for (count = start; count < stop; count++) {
- PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
- }
- }
- else {
- switch (RNA_property_type(prop)) {
- case PROP_FLOAT:
- {
- float values_stack[PYRNA_STACK_ARRAY];
- float *values;
- if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(float) * length); }
- else { values = values_stack; }
- RNA_property_float_get_array(ptr, prop, values);
-
- for (count = start; count < stop; count++) {
- PyTuple_SET_ITEM(tuple, count - start, PyFloat_FromDouble(values[count]));
- }
-
- if (values != values_stack) {
- PyMem_FREE(values);
- }
- break;
- }
- case PROP_BOOLEAN:
- {
- bool values_stack[PYRNA_STACK_ARRAY];
- bool *values;
- if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(bool) * length); }
- else { values = values_stack; }
-
- RNA_property_boolean_get_array(ptr, prop, values);
- for (count = start; count < stop; count++) {
- PyTuple_SET_ITEM(tuple, count - start, PyBool_FromLong(values[count]));
- }
-
- if (values != values_stack) {
- PyMem_FREE(values);
- }
- break;
- }
- case PROP_INT:
- {
- int values_stack[PYRNA_STACK_ARRAY];
- int *values;
- if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
- else { values = values_stack; }
-
- RNA_property_int_get_array(ptr, prop, values);
- for (count = start; count < stop; count++) {
- PyTuple_SET_ITEM(tuple, count - start, PyLong_FromLong(values[count]));
- }
-
- if (values != values_stack) {
- PyMem_FREE(values);
- }
- break;
- }
- default:
- BLI_assert(!"Invalid array type");
-
- PyErr_SetString(PyExc_TypeError, "not an array type");
- Py_DECREF(tuple);
- tuple = NULL;
- break;
- }
- }
- return tuple;
+static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ Py_ssize_t start,
+ Py_ssize_t stop,
+ Py_ssize_t length)
+{
+ int count, totdim;
+ PyObject *tuple;
+
+ /* isn't needed, internal use only */
+ // PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
+
+ tuple = PyTuple_New(stop - start);
+
+ totdim = RNA_property_array_dimension(ptr, prop, NULL);
+
+ if (totdim > 1) {
+ for (count = start; count < stop; count++) {
+ PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
+ }
+ }
+ else {
+ switch (RNA_property_type(prop)) {
+ case PROP_FLOAT: {
+ float values_stack[PYRNA_STACK_ARRAY];
+ float *values;
+ if (length > PYRNA_STACK_ARRAY) {
+ values = PyMem_MALLOC(sizeof(float) * length);
+ }
+ else {
+ values = values_stack;
+ }
+ RNA_property_float_get_array(ptr, prop, values);
+
+ for (count = start; count < stop; count++) {
+ PyTuple_SET_ITEM(tuple, count - start, PyFloat_FromDouble(values[count]));
+ }
+
+ if (values != values_stack) {
+ PyMem_FREE(values);
+ }
+ break;
+ }
+ case PROP_BOOLEAN: {
+ bool values_stack[PYRNA_STACK_ARRAY];
+ bool *values;
+ if (length > PYRNA_STACK_ARRAY) {
+ values = PyMem_MALLOC(sizeof(bool) * length);
+ }
+ else {
+ values = values_stack;
+ }
+
+ RNA_property_boolean_get_array(ptr, prop, values);
+ for (count = start; count < stop; count++) {
+ PyTuple_SET_ITEM(tuple, count - start, PyBool_FromLong(values[count]));
+ }
+
+ if (values != values_stack) {
+ PyMem_FREE(values);
+ }
+ break;
+ }
+ case PROP_INT: {
+ int values_stack[PYRNA_STACK_ARRAY];
+ int *values;
+ if (length > PYRNA_STACK_ARRAY) {
+ values = PyMem_MALLOC(sizeof(int) * length);
+ }
+ else {
+ values = values_stack;
+ }
+
+ RNA_property_int_get_array(ptr, prop, values);
+ for (count = start; count < stop; count++) {
+ PyTuple_SET_ITEM(tuple, count - start, PyLong_FromLong(values[count]));
+ }
+
+ if (values != values_stack) {
+ PyMem_FREE(values);
+ }
+ break;
+ }
+ default:
+ BLI_assert(!"Invalid array type");
+
+ PyErr_SetString(PyExc_TypeError, "not an array type");
+ Py_DECREF(tuple);
+ tuple = NULL;
+ break;
+ }
+ }
+ return tuple;
}
static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
{
- PYRNA_PROP_CHECK_OBJ(self);
-
- if (PyUnicode_Check(key)) {
- return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
- }
- else if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
-
- return pyrna_prop_collection_subscript_int(self, i);
- }
- else if (PySlice_Check(key)) {
- PySliceObject *key_slice = (PySliceObject *)key;
- Py_ssize_t step = 1;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
- }
- else {
- Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
-
- /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
- if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
- return NULL;
- }
- if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
- return NULL;
- }
-
- if (start < 0 || stop < 0) {
- /* only get the length for negative values */
- Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
- if (start < 0) {
- start += len;
- }
- if (stop < 0) {
- stop += len;
- }
- }
-
- if (stop - start <= 0) {
- return PyList_New(0);
- }
- else {
- return pyrna_prop_collection_subscript_slice(self, start, stop);
- }
- }
- }
- else if (PyTuple_Check(key)) {
- /* special case, for ID datablocks we */
- return pyrna_prop_collection_subscript_str_lib_pair(self, key,
- "bpy_prop_collection[id, lib]", true);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key]: invalid key, "
- "must be a string or an int, not %.200s",
- Py_TYPE(key)->tp_name);
- return NULL;
- }
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ if (PyUnicode_Check(key)) {
+ return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
+ }
+ else if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+
+ return pyrna_prop_collection_subscript_int(self, i);
+ }
+ else if (PySlice_Check(key)) {
+ PySliceObject *key_slice = (PySliceObject *)key;
+ Py_ssize_t step = 1;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ }
+ else {
+ Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
+
+ /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
+ if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
+ return NULL;
+ }
+ if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
+ return NULL;
+ }
+
+ if (start < 0 || stop < 0) {
+ /* only get the length for negative values */
+ Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
+ if (start < 0) {
+ start += len;
+ }
+ if (stop < 0) {
+ stop += len;
+ }
+ }
+
+ if (stop - start <= 0) {
+ return PyList_New(0);
+ }
+ else {
+ return pyrna_prop_collection_subscript_slice(self, start, stop);
+ }
+ }
+ }
+ else if (PyTuple_Check(key)) {
+ /* special case, for ID datablocks we */
+ return pyrna_prop_collection_subscript_str_lib_pair(
+ self, key, "bpy_prop_collection[id, lib]", true);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key]: invalid key, "
+ "must be a string or an int, not %.200s",
+ Py_TYPE(key)->tp_name);
+ return NULL;
+ }
}
/* generic check to see if a PyObject is compatible with a collection
* -1 on failure, 0 on success, sets the error */
static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
{
- StructRNA *prop_srna;
-
- if (value == Py_None) {
- if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key] = value: invalid, "
- "this collection doesn't support None assignment");
- return -1;
- }
- else {
- return 0; /* None is OK */
- }
- }
- else if (BPy_StructRNA_Check(value) == 0) {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key] = value: invalid, "
- "expected a StructRNA type or None, not a %.200s",
- Py_TYPE(value)->tp_name);
- return -1;
- }
- else if ((prop_srna = RNA_property_pointer_type(&self->ptr, self->prop))) {
- StructRNA *value_srna = ((BPy_StructRNA *)value)->ptr.type;
- if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key] = value: invalid, "
- "expected a '%.200s' type or None, not a '%.200s'",
- RNA_struct_identifier(prop_srna),
- RNA_struct_identifier(value_srna)
- );
- return -1;
- }
- else {
- return 0; /* OK, this is the correct type!*/
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key] = value: internal error, "
- "failed to get the collection type");
- return -1;
+ StructRNA *prop_srna;
+
+ if (value == Py_None) {
+ if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key] = value: invalid, "
+ "this collection doesn't support None assignment");
+ return -1;
+ }
+ else {
+ return 0; /* None is OK */
+ }
+ }
+ else if (BPy_StructRNA_Check(value) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key] = value: invalid, "
+ "expected a StructRNA type or None, not a %.200s",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ else if ((prop_srna = RNA_property_pointer_type(&self->ptr, self->prop))) {
+ StructRNA *value_srna = ((BPy_StructRNA *)value)->ptr.type;
+ if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key] = value: invalid, "
+ "expected a '%.200s' type or None, not a '%.200s'",
+ RNA_struct_identifier(prop_srna),
+ RNA_struct_identifier(value_srna));
+ return -1;
+ }
+ else {
+ return 0; /* OK, this is the correct type!*/
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key] = value: internal error, "
+ "failed to get the collection type");
+ return -1;
}
/* note: currently this is a copy of 'pyrna_prop_collection_subscript' with
* large blocks commented, we may support slice/key indices later */
-static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *key, PyObject *value)
+static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self,
+ PyObject *key,
+ PyObject *value)
{
- PYRNA_PROP_CHECK_INT(self);
+ PYRNA_PROP_CHECK_INT(self);
- /* validate the assigned value */
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "del bpy_prop_collection[key]: not supported");
- return -1;
- }
- else if (pyrna_prop_collection_type_check(self, value) == -1) {
- return -1; /* exception is set */
- }
+ /* validate the assigned value */
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError, "del bpy_prop_collection[key]: not supported");
+ return -1;
+ }
+ else if (pyrna_prop_collection_type_check(self, value) == -1) {
+ return -1; /* exception is set */
+ }
#if 0
- if (PyUnicode_Check(key)) {
- return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
- }
- else
+ if (PyUnicode_Check(key)) {
+ return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
+ }
+ else
#endif
- if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return -1;
- }
-
- return pyrna_prop_collection_ass_subscript_int(self, i, value);
- }
+ if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+
+ return pyrna_prop_collection_ass_subscript_int(self, i, value);
+ }
#if 0 /* TODO, fake slice assignment */
- else if (PySlice_Check(key)) {
- PySliceObject *key_slice = (PySliceObject *)key;
- Py_ssize_t step = 1;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
- }
- else {
- Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
-
- /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
- if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
- if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) return NULL;
-
- if (start < 0 || stop < 0) {
- /* only get the length for negative values */
- Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
- if (start < 0) start += len;
- if (stop < 0) stop += len;
- }
-
- if (stop - start <= 0) {
- return PyList_New(0);
- }
- else {
- return pyrna_prop_collection_subscript_slice(self, start, stop);
- }
- }
- }
+ else if (PySlice_Check(key)) {
+ PySliceObject *key_slice = (PySliceObject *)key;
+ Py_ssize_t step = 1;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ }
+ else {
+ Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
+
+ /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
+ if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
+ if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) return NULL;
+
+ if (start < 0 || stop < 0) {
+ /* only get the length for negative values */
+ Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
+ if (start < 0) start += len;
+ if (stop < 0) stop += len;
+ }
+
+ if (stop - start <= 0) {
+ return PyList_New(0);
+ }
+ else {
+ return pyrna_prop_collection_subscript_slice(self, start, stop);
+ }
+ }
+ }
#endif
- else {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop_collection[key]: invalid key, "
- "must be a string or an int, not %.200s",
- Py_TYPE(key)->tp_name);
- return -1;
- }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop_collection[key]: invalid key, "
+ "must be a string or an int, not %.200s",
+ Py_TYPE(key)->tp_name);
+ return -1;
+ }
}
static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
{
- PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
+ PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
#if 0
- if (PyUnicode_Check(key)) {
- return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
- }
- else
+ if (PyUnicode_Check(key)) {
+ return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
+ }
+ else
#endif
- if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- return pyrna_prop_array_subscript_int(self, i);
- }
- else if (PySlice_Check(key)) {
- Py_ssize_t step = 1;
- PySliceObject *key_slice = (PySliceObject *)key;
-
- if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
- return NULL;
- }
- else if (step != 1) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
- return NULL;
- }
- else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
- /* note, no significant advantage with optimizing [:] slice as with collections
- * but include here for consistency with collection slice func */
- Py_ssize_t len = (Py_ssize_t)pyrna_prop_array_length(self);
- return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
- }
- else {
- int len = pyrna_prop_array_length(self);
- Py_ssize_t start, stop, slicelength;
-
- if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else {
- return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
- }
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
- return NULL;
- }
+ if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ return pyrna_prop_array_subscript_int(self, i);
+ }
+ else if (PySlice_Check(key)) {
+ Py_ssize_t step = 1;
+ PySliceObject *key_slice = (PySliceObject *)key;
+
+ if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
+ return NULL;
+ }
+ else if (step != 1) {
+ PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
+ return NULL;
+ }
+ else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
+ /* note, no significant advantage with optimizing [:] slice as with collections
+ * but include here for consistency with collection slice func */
+ Py_ssize_t len = (Py_ssize_t)pyrna_prop_array_length(self);
+ return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
+ }
+ else {
+ int len = pyrna_prop_array_length(self);
+ Py_ssize_t start, stop, slicelength;
+
+ if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else {
+ return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
+ return NULL;
+ }
}
/**
@@ -2847,1041 +2897,1043 @@ static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject
static PyObject *prop_subscript_ass_array_slice__as_seq_fast(PyObject *value, int length)
{
- PyObject *value_fast;
- if (!(value_fast = PySequence_Fast(
- value,
- "bpy_prop_array[slice] = value: "
- "element in assignment is not a sequence type")))
- {
- return NULL;
- }
- else if (PySequence_Fast_GET_SIZE(value_fast) != length) {
- Py_DECREF(value_fast);
- PyErr_SetString(
- PyExc_ValueError,
- "bpy_prop_array[slice] = value: "
- "re-sizing bpy_struct element in arrays isn't supported");
-
- return NULL;
- }
- else {
- return value_fast;
- }
+ PyObject *value_fast;
+ if (!(value_fast = PySequence_Fast(value,
+ "bpy_prop_array[slice] = value: "
+ "element in assignment is not a sequence type"))) {
+ return NULL;
+ }
+ else if (PySequence_Fast_GET_SIZE(value_fast) != length) {
+ Py_DECREF(value_fast);
+ PyErr_SetString(PyExc_ValueError,
+ "bpy_prop_array[slice] = value: "
+ "re-sizing bpy_struct element in arrays isn't supported");
+
+ return NULL;
+ }
+ else {
+ return value_fast;
+ }
}
static int prop_subscript_ass_array_slice__float_recursive(
- PyObject **value_items, float *value,
- int totdim, const int dimsize[],
- const float range[2])
-{
- const int length = dimsize[0];
- if (totdim > 1) {
- int index = 0;
- int i;
- for (i = 0; i != length; i++) {
- PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
- if (UNLIKELY(subvalue == NULL)) {
- return 0;
- }
-
- index += prop_subscript_ass_array_slice__float_recursive(
- PySequence_Fast_ITEMS(subvalue), &value[index],
- totdim - 1, &dimsize[1], range);
-
- Py_DECREF(subvalue);
- }
- return index;
- }
- else {
- BLI_assert(totdim == 1);
- const float min = range[0], max = range[1];
- int i;
- for (i = 0; i != length; i++) {
- float v = PyFloat_AsDouble(value_items[i]);
- CLAMP(v, min, max);
- value[i] = v;
- }
- return i;
- }
+ PyObject **value_items, float *value, int totdim, const int dimsize[], const float range[2])
+{
+ const int length = dimsize[0];
+ if (totdim > 1) {
+ int index = 0;
+ int i;
+ for (i = 0; i != length; i++) {
+ PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
+ if (UNLIKELY(subvalue == NULL)) {
+ return 0;
+ }
+
+ index += prop_subscript_ass_array_slice__float_recursive(
+ PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1], range);
+
+ Py_DECREF(subvalue);
+ }
+ return index;
+ }
+ else {
+ BLI_assert(totdim == 1);
+ const float min = range[0], max = range[1];
+ int i;
+ for (i = 0; i != length; i++) {
+ float v = PyFloat_AsDouble(value_items[i]);
+ CLAMP(v, min, max);
+ value[i] = v;
+ }
+ return i;
+ }
}
static int prop_subscript_ass_array_slice__int_recursive(
- PyObject **value_items, int *value,
- int totdim, const int dimsize[],
- const int range[2])
-{
- const int length = dimsize[0];
- if (totdim > 1) {
- int index = 0;
- int i;
- for (i = 0; i != length; i++) {
- PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
- if (UNLIKELY(subvalue == NULL)) {
- return 0;
- }
-
- index += prop_subscript_ass_array_slice__int_recursive(
- PySequence_Fast_ITEMS(subvalue), &value[index],
- totdim - 1, &dimsize[1], range);
-
- Py_DECREF(subvalue);
- }
- return index;
- }
- else {
- BLI_assert(totdim == 1);
- const int min = range[0], max = range[1];
- int i;
- for (i = 0; i != length; i++) {
- int v = PyLong_AsLong(value_items[i]);
- CLAMP(v, min, max);
- value[i] = v;
- }
- return i;
- }
-}
-
-static int prop_subscript_ass_array_slice__bool_recursive(
- PyObject **value_items, bool *value,
- int totdim, const int dimsize[])
-{
- const int length = dimsize[0];
- if (totdim > 1) {
- int index = 0;
- int i;
- for (i = 0; i != length; i++) {
- PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
- if (UNLIKELY(subvalue == NULL)) {
- return 0;
- }
-
- index += prop_subscript_ass_array_slice__bool_recursive(
- PySequence_Fast_ITEMS(subvalue), &value[index],
- totdim - 1, &dimsize[1]);
-
- Py_DECREF(subvalue);
- }
- return index;
- }
- else {
- BLI_assert(totdim == 1);
- int i;
- for (i = 0; i != length; i++) {
- int v = PyLong_AsLong(value_items[i]);
- value[i] = v;
- }
- return i;
- }
+ PyObject **value_items, int *value, int totdim, const int dimsize[], const int range[2])
+{
+ const int length = dimsize[0];
+ if (totdim > 1) {
+ int index = 0;
+ int i;
+ for (i = 0; i != length; i++) {
+ PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
+ if (UNLIKELY(subvalue == NULL)) {
+ return 0;
+ }
+
+ index += prop_subscript_ass_array_slice__int_recursive(
+ PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1], range);
+
+ Py_DECREF(subvalue);
+ }
+ return index;
+ }
+ else {
+ BLI_assert(totdim == 1);
+ const int min = range[0], max = range[1];
+ int i;
+ for (i = 0; i != length; i++) {
+ int v = PyLong_AsLong(value_items[i]);
+ CLAMP(v, min, max);
+ value[i] = v;
+ }
+ return i;
+ }
+}
+
+static int prop_subscript_ass_array_slice__bool_recursive(PyObject **value_items,
+ bool *value,
+ int totdim,
+ const int dimsize[])
+{
+ const int length = dimsize[0];
+ if (totdim > 1) {
+ int index = 0;
+ int i;
+ for (i = 0; i != length; i++) {
+ PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
+ if (UNLIKELY(subvalue == NULL)) {
+ return 0;
+ }
+
+ index += prop_subscript_ass_array_slice__bool_recursive(
+ PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1]);
+
+ Py_DECREF(subvalue);
+ }
+ return index;
+ }
+ else {
+ BLI_assert(totdim == 1);
+ int i;
+ for (i = 0; i != length; i++) {
+ int v = PyLong_AsLong(value_items[i]);
+ value[i] = v;
+ }
+ return i;
+ }
}
/* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
-static int prop_subscript_ass_array_slice(
- PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset,
- int start, int stop, int length, PyObject *value_orig)
-{
- const int length_flat = RNA_property_array_length(ptr, prop);
- PyObject *value;
- PyObject **value_items;
- void *values_alloc = NULL;
- int ret = 0;
-
- if (value_orig == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
- return -1;
- }
-
- if (!(value = PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
- return -1;
- }
-
- if (PySequence_Fast_GET_SIZE(value) != stop - start) {
- Py_DECREF(value);
- PyErr_SetString(PyExc_TypeError,
- "bpy_prop_array[slice] = value: re-sizing bpy_struct arrays isn't supported");
- return -1;
- }
-
- int dimsize[3];
- int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
- if (totdim > 1) {
- BLI_assert(dimsize[arraydim] == length);
- }
-
- int span = 1;
- if (totdim > 1) {
- for (int i = arraydim + 1; i < totdim; i++) {
- span *= dimsize[i];
- }
- }
-
- value_items = PySequence_Fast_ITEMS(value);
- switch (RNA_property_type(prop)) {
- case PROP_FLOAT:
- {
- float values_stack[PYRNA_STACK_ARRAY];
- float *values = (length_flat > PYRNA_STACK_ARRAY) ?
- (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) : values_stack;
- if (start != 0 || stop != length) {
- /* partial assignment? - need to get the array */
- RNA_property_float_get_array(ptr, prop, values);
- }
-
- float range[2];
- RNA_property_float_range(ptr, prop, &range[0], &range[1]);
-
- dimsize[arraydim] = stop - start;
- prop_subscript_ass_array_slice__float_recursive(
- value_items, &values[arrayoffset + (start * span)],
- totdim - arraydim, &dimsize[arraydim],
- range);
-
- if (PyErr_Occurred()) {
- ret = -1;
- }
- else {
- RNA_property_float_set_array(ptr, prop, values);
- }
- break;
- }
- case PROP_INT:
- {
- int values_stack[PYRNA_STACK_ARRAY];
- int *values = (length_flat > PYRNA_STACK_ARRAY) ?
- (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) : values_stack;
- if (start != 0 || stop != length) {
- /* partial assignment? - need to get the array */
- RNA_property_int_get_array(ptr, prop, values);
- }
-
- int range[2];
- RNA_property_int_range(ptr, prop, &range[0], &range[1]);
-
- dimsize[arraydim] = stop - start;
- prop_subscript_ass_array_slice__int_recursive(
- value_items, &values[arrayoffset + (start * span)],
- totdim - arraydim, &dimsize[arraydim],
- range);
-
- if (PyErr_Occurred()) {
- ret = -1;
- }
- else {
- RNA_property_int_set_array(ptr, prop, values);
- }
- break;
- }
- case PROP_BOOLEAN:
- {
- bool values_stack[PYRNA_STACK_ARRAY];
- bool *values = (length_flat > PYRNA_STACK_ARRAY) ?
- (values_alloc = PyMem_MALLOC(sizeof(bool) * length_flat)) : values_stack;
-
- if (start != 0 || stop != length) {
- /* partial assignment? - need to get the array */
- RNA_property_boolean_get_array(ptr, prop, values);
- }
-
- dimsize[arraydim] = stop - start;
- prop_subscript_ass_array_slice__bool_recursive(
- value_items, &values[arrayoffset + (start * span)],
- totdim - arraydim, &dimsize[arraydim]);
-
- if (PyErr_Occurred()) {
- ret = -1;
- }
- else {
- RNA_property_boolean_set_array(ptr, prop, values);
- }
- break;
- }
- default:
- PyErr_SetString(PyExc_TypeError, "not an array type");
- ret = -1;
- break;
- }
-
- Py_DECREF(value);
-
- if (values_alloc) {
- PyMem_FREE(values_alloc);
- }
-
- return ret;
-
-}
-
-static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
-{
- int len;
-
- PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
-
- len = pyrna_prop_array_length(self);
-
- if (keynum < 0) {
- keynum += len;
- }
-
- if (keynum >= 0 && keynum < len) {
- return pyrna_py_to_prop_array_index(self, keynum, value);
- }
-
- PyErr_SetString(PyExc_IndexError,
- "bpy_prop_array[index] = value: index out of range");
- return -1;
-}
-
-static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
-{
- /* char *keyname = NULL; */ /* not supported yet */
- int ret = -1;
-
- PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
-
- if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
- RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
- ret = -1;
- }
-
- else if (PyIndex_Check(key)) {
- Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- ret = -1;
- }
- else {
- ret = prop_subscript_ass_array_int(self, i, value);
- }
- }
- else if (PySlice_Check(key)) {
- Py_ssize_t len = pyrna_prop_array_length(self);
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0) {
- ret = -1;
- }
- else if (slicelength <= 0) {
- ret = 0; /* do nothing */
- }
- else if (step == 1) {
- ret = prop_subscript_ass_array_slice(
- &self->ptr, self->prop, self->arraydim, self->arrayoffset,
- start, stop, len, value);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
- ret = -1;
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
- ret = -1;
- }
-
- if (ret != -1) {
- if (RNA_property_update_check(self->prop)) {
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
- }
- }
-
- return ret;
+static int prop_subscript_ass_array_slice(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int arraydim,
+ int arrayoffset,
+ int start,
+ int stop,
+ int length,
+ PyObject *value_orig)
+{
+ const int length_flat = RNA_property_array_length(ptr, prop);
+ PyObject *value;
+ PyObject **value_items;
+ void *values_alloc = NULL;
+ int ret = 0;
+
+ if (value_orig == NULL) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
+ return -1;
+ }
+
+ if (!(value = PySequence_Fast(
+ value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
+ return -1;
+ }
+
+ if (PySequence_Fast_GET_SIZE(value) != stop - start) {
+ Py_DECREF(value);
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_prop_array[slice] = value: re-sizing bpy_struct arrays isn't supported");
+ return -1;
+ }
+
+ int dimsize[3];
+ int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
+ if (totdim > 1) {
+ BLI_assert(dimsize[arraydim] == length);
+ }
+
+ int span = 1;
+ if (totdim > 1) {
+ for (int i = arraydim + 1; i < totdim; i++) {
+ span *= dimsize[i];
+ }
+ }
+
+ value_items = PySequence_Fast_ITEMS(value);
+ switch (RNA_property_type(prop)) {
+ case PROP_FLOAT: {
+ float values_stack[PYRNA_STACK_ARRAY];
+ float *values = (length_flat > PYRNA_STACK_ARRAY) ?
+ (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) :
+ values_stack;
+ if (start != 0 || stop != length) {
+ /* partial assignment? - need to get the array */
+ RNA_property_float_get_array(ptr, prop, values);
+ }
+
+ float range[2];
+ RNA_property_float_range(ptr, prop, &range[0], &range[1]);
+
+ dimsize[arraydim] = stop - start;
+ prop_subscript_ass_array_slice__float_recursive(value_items,
+ &values[arrayoffset + (start * span)],
+ totdim - arraydim,
+ &dimsize[arraydim],
+ range);
+
+ if (PyErr_Occurred()) {
+ ret = -1;
+ }
+ else {
+ RNA_property_float_set_array(ptr, prop, values);
+ }
+ break;
+ }
+ case PROP_INT: {
+ int values_stack[PYRNA_STACK_ARRAY];
+ int *values = (length_flat > PYRNA_STACK_ARRAY) ?
+ (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) :
+ values_stack;
+ if (start != 0 || stop != length) {
+ /* partial assignment? - need to get the array */
+ RNA_property_int_get_array(ptr, prop, values);
+ }
+
+ int range[2];
+ RNA_property_int_range(ptr, prop, &range[0], &range[1]);
+
+ dimsize[arraydim] = stop - start;
+ prop_subscript_ass_array_slice__int_recursive(value_items,
+ &values[arrayoffset + (start * span)],
+ totdim - arraydim,
+ &dimsize[arraydim],
+ range);
+
+ if (PyErr_Occurred()) {
+ ret = -1;
+ }
+ else {
+ RNA_property_int_set_array(ptr, prop, values);
+ }
+ break;
+ }
+ case PROP_BOOLEAN: {
+ bool values_stack[PYRNA_STACK_ARRAY];
+ bool *values = (length_flat > PYRNA_STACK_ARRAY) ?
+ (values_alloc = PyMem_MALLOC(sizeof(bool) * length_flat)) :
+ values_stack;
+
+ if (start != 0 || stop != length) {
+ /* partial assignment? - need to get the array */
+ RNA_property_boolean_get_array(ptr, prop, values);
+ }
+
+ dimsize[arraydim] = stop - start;
+ prop_subscript_ass_array_slice__bool_recursive(value_items,
+ &values[arrayoffset + (start * span)],
+ totdim - arraydim,
+ &dimsize[arraydim]);
+
+ if (PyErr_Occurred()) {
+ ret = -1;
+ }
+ else {
+ RNA_property_boolean_set_array(ptr, prop, values);
+ }
+ break;
+ }
+ default:
+ PyErr_SetString(PyExc_TypeError, "not an array type");
+ ret = -1;
+ break;
+ }
+
+ Py_DECREF(value);
+
+ if (values_alloc) {
+ PyMem_FREE(values_alloc);
+ }
+
+ return ret;
+}
+
+static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self,
+ Py_ssize_t keynum,
+ PyObject *value)
+{
+ int len;
+
+ PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
+
+ len = pyrna_prop_array_length(self);
+
+ if (keynum < 0) {
+ keynum += len;
+ }
+
+ if (keynum >= 0 && keynum < len) {
+ return pyrna_py_to_prop_array_index(self, keynum, value);
+ }
+
+ PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
+ return -1;
+}
+
+static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self,
+ PyObject *key,
+ PyObject *value)
+{
+ /* char *keyname = NULL; */ /* not supported yet */
+ int ret = -1;
+
+ PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
+
+ if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
+ RNA_property_identifier(self->prop),
+ RNA_struct_identifier(self->ptr.type));
+ ret = -1;
+ }
+
+ else if (PyIndex_Check(key)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ ret = -1;
+ }
+ else {
+ ret = prop_subscript_ass_array_int(self, i, value);
+ }
+ }
+ else if (PySlice_Check(key)) {
+ Py_ssize_t len = pyrna_prop_array_length(self);
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0) {
+ ret = -1;
+ }
+ else if (slicelength <= 0) {
+ ret = 0; /* do nothing */
+ }
+ else if (step == 1) {
+ ret = prop_subscript_ass_array_slice(
+ &self->ptr, self->prop, self->arraydim, self->arrayoffset, start, stop, len, value);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
+ ret = -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
+ ret = -1;
+ }
+
+ if (ret != -1) {
+ if (RNA_property_update_check(self->prop)) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ }
+ }
+
+ return ret;
}
/* for slice only */
static PyMappingMethods pyrna_prop_array_as_mapping = {
- (lenfunc) pyrna_prop_array_length, /* mp_length */
- (binaryfunc) pyrna_prop_array_subscript, /* mp_subscript */
- (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
+ (lenfunc)pyrna_prop_array_length, /* mp_length */
+ (binaryfunc)pyrna_prop_array_subscript, /* mp_subscript */
+ (objobjargproc)pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
};
static PyMappingMethods pyrna_prop_collection_as_mapping = {
- (lenfunc) pyrna_prop_collection_length, /* mp_length */
- (binaryfunc) pyrna_prop_collection_subscript, /* mp_subscript */
- (objobjargproc) pyrna_prop_collection_ass_subscript, /* mp_ass_subscript */
+ (lenfunc)pyrna_prop_collection_length, /* mp_length */
+ (binaryfunc)pyrna_prop_collection_subscript, /* mp_subscript */
+ (objobjargproc)pyrna_prop_collection_ass_subscript, /* mp_ass_subscript */
};
/* only for fast bool's, large structs, assign nb_bool on init */
static PyNumberMethods pyrna_prop_array_as_number = {
- NULL, /* nb_add */
- NULL, /* nb_subtract */
- NULL, /* nb_multiply */
- NULL, /* nb_remainder */
- NULL, /* nb_divmod */
- NULL, /* nb_power */
- NULL, /* nb_negative */
- NULL, /* nb_positive */
- NULL, /* nb_absolute */
- (inquiry) pyrna_prop_array_bool, /* nb_bool */
+ NULL, /* nb_add */
+ NULL, /* nb_subtract */
+ NULL, /* nb_multiply */
+ NULL, /* nb_remainder */
+ NULL, /* nb_divmod */
+ NULL, /* nb_power */
+ NULL, /* nb_negative */
+ NULL, /* nb_positive */
+ NULL, /* nb_absolute */
+ (inquiry)pyrna_prop_array_bool, /* nb_bool */
};
static PyNumberMethods pyrna_prop_collection_as_number = {
- NULL, /* nb_add */
- NULL, /* nb_subtract */
- NULL, /* nb_multiply */
- NULL, /* nb_remainder */
- NULL, /* nb_divmod */
- NULL, /* nb_power */
- NULL, /* nb_negative */
- NULL, /* nb_positive */
- NULL, /* nb_absolute */
- (inquiry) pyrna_prop_collection_bool, /* nb_bool */
+ NULL, /* nb_add */
+ NULL, /* nb_subtract */
+ NULL, /* nb_multiply */
+ NULL, /* nb_remainder */
+ NULL, /* nb_divmod */
+ NULL, /* nb_power */
+ NULL, /* nb_negative */
+ NULL, /* nb_positive */
+ NULL, /* nb_absolute */
+ (inquiry)pyrna_prop_collection_bool, /* nb_bool */
};
static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
{
- return pyrna_array_contains_py(&self->ptr, self->prop, value);
+ return pyrna_array_contains_py(&self->ptr, self->prop, value);
}
static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *key)
{
- PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
+ PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
- if (PyTuple_Check(key)) {
- /* special case, for ID datablocks we */
- return pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key,
- "(id, lib) in bpy_prop_collection", false, NULL);
- }
- else {
+ if (PyTuple_Check(key)) {
+ /* special case, for ID datablocks we */
+ return pyrna_prop_collection_subscript_str_lib_pair_ptr(
+ self, key, "(id, lib) in bpy_prop_collection", false, NULL);
+ }
+ else {
- /* key in dict style check */
- const char *keyname = _PyUnicode_AsString(key);
+ /* key in dict style check */
+ const char *keyname = _PyUnicode_AsString(key);
- if (keyname == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "bpy_prop_collection.__contains__: expected a string or a tuple of strings");
- return -1;
- }
+ if (keyname == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_prop_collection.__contains__: expected a string or a tuple of strings");
+ return -1;
+ }
- if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr)) {
- return 1;
- }
+ if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr)) {
+ return 1;
+ }
- return 0;
- }
+ return 0;
+ }
}
static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
{
- IDProperty *group;
- const char *name = _PyUnicode_AsString(value);
+ IDProperty *group;
+ const char *name = _PyUnicode_AsString(value);
- PYRNA_STRUCT_CHECK_INT(self);
+ PYRNA_STRUCT_CHECK_INT(self);
- if (!name) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
- return -1;
- }
+ if (!name) {
+ PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
+ return -1;
+ }
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
- return -1;
- }
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
+ return -1;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
+ group = RNA_struct_idprops(&self->ptr, 0);
- if (!group) {
- return 0;
- }
+ if (!group) {
+ return 0;
+ }
- return IDP_GetPropertyFromGroup(group, name) ? 1 : 0;
+ return IDP_GetPropertyFromGroup(group, name) ? 1 : 0;
}
static PySequenceMethods pyrna_prop_array_as_sequence = {
- (lenfunc)pyrna_prop_array_length,
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* sq_slice */
- (ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)pyrna_prop_array_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)pyrna_prop_array_length,
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ (ssizeargfunc)pyrna_prop_array_subscript_int,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* sq_slice */
+ (ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)pyrna_prop_array_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PySequenceMethods pyrna_prop_collection_as_sequence = {
- (lenfunc)pyrna_prop_collection_length,
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* *was* sq_slice */
- (ssizeobjargproc)/* pyrna_prop_collection_ass_subscript_int */ NULL /* let mapping take this one */, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)pyrna_prop_collection_length,
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ (ssizeargfunc)pyrna_prop_collection_subscript_int,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* *was* sq_slice */
+ (ssizeobjargproc) /* pyrna_prop_collection_ass_subscript_int */
+ NULL /* let mapping take this one */, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PySequenceMethods pyrna_struct_as_sequence = {
- NULL, /* Cant set the len otherwise it can evaluate as false */
- NULL, /* sq_concat */
- NULL, /* sq_repeat */
- NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
- NULL, /* *was* sq_slice */
- NULL, /* sq_ass_item */
- NULL, /* *was* sq_ass_slice */
- (objobjproc)pyrna_struct_contains, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ NULL, /* Cant set the len otherwise it can evaluate as false */
+ NULL, /* sq_concat */
+ NULL, /* sq_repeat */
+ NULL,
+ /* sq_item */ /* Only set this so PySequence_Check() returns True */
+ NULL, /* *was* sq_slice */
+ NULL, /* sq_ass_item */
+ NULL, /* *was* sq_ass_slice */
+ (objobjproc)pyrna_struct_contains, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
{
- /* mostly copied from BPy_IDGroup_Map_GetItem */
- IDProperty *group, *idprop;
- const char *name = _PyUnicode_AsString(key);
+ /* mostly copied from BPy_IDGroup_Map_GetItem */
+ IDProperty *group, *idprop;
+ const char *name = _PyUnicode_AsString(key);
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
- return NULL;
- }
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
+ return NULL;
+ }
- if (name == NULL) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
- return NULL;
- }
+ if (name == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_struct[key]: only strings are allowed as keys of ID properties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
+ group = RNA_struct_idprops(&self->ptr, 0);
- if (group == NULL) {
- PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
- return NULL;
- }
+ if (group == NULL) {
+ PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
+ return NULL;
+ }
- idprop = IDP_GetPropertyFromGroup(group, name);
+ idprop = IDP_GetPropertyFromGroup(group, name);
- if (idprop == NULL) {
- PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
- return NULL;
- }
+ if (idprop == NULL) {
+ PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
+ return NULL;
+ }
- return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
+ return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
}
static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
{
- IDProperty *group;
+ IDProperty *group;
- PYRNA_STRUCT_CHECK_INT(self);
+ PYRNA_STRUCT_CHECK_INT(self);
- group = RNA_struct_idprops(&self->ptr, 1);
+ group = RNA_struct_idprops(&self->ptr, 1);
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
-
- if (group == NULL) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct[key] = val: id properties not supported for this type");
- return -1;
- }
-
- if (value && BPy_StructRNA_Check(value)) {
- BPy_StructRNA *val = (BPy_StructRNA *)value;
- if (val && self->ptr.type && val->ptr.type) {
- if (!RNA_struct_idprops_datablock_allowed(self->ptr.type) &&
- RNA_struct_idprops_contains_datablock(val->ptr.type))
- {
- PyErr_SetString(
- PyExc_TypeError,
- "bpy_struct[key] = val: datablock id properties not supported for this type");
- return -1;
- }
- }
- }
-
- return BPy_Wrap_SetMapItem(group, key, value);
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
+ return -1;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
+ if (group == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_struct[key] = val: id properties not supported for this type");
+ return -1;
+ }
+
+ if (value && BPy_StructRNA_Check(value)) {
+ BPy_StructRNA *val = (BPy_StructRNA *)value;
+ if (val && self->ptr.type && val->ptr.type) {
+ if (!RNA_struct_idprops_datablock_allowed(self->ptr.type) &&
+ RNA_struct_idprops_contains_datablock(val->ptr.type)) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "bpy_struct[key] = val: datablock id properties not supported for this type");
+ return -1;
+ }
+ }
+ }
+
+ return BPy_Wrap_SetMapItem(group, key, value);
}
static PyMappingMethods pyrna_struct_as_mapping = {
- (lenfunc) NULL, /* mp_length */
- (binaryfunc) pyrna_struct_subscript, /* mp_subscript */
- (objobjargproc) pyrna_struct_ass_subscript, /* mp_ass_subscript */
+ (lenfunc)NULL, /* mp_length */
+ (binaryfunc)pyrna_struct_subscript, /* mp_subscript */
+ (objobjargproc)pyrna_struct_ass_subscript, /* mp_ass_subscript */
};
PyDoc_STRVAR(pyrna_struct_keys_doc,
-".. method:: keys()\n"
-"\n"
-" Returns the keys of this objects custom properties (matches pythons\n"
-" dictionary function of the same name).\n"
-"\n"
-" :return: custom property keys.\n"
-" :rtype: list of strings\n"
-"\n"
-BPY_DOC_ID_PROP_TYPE_NOTE
-);
+ ".. method:: keys()\n"
+ "\n"
+ " Returns the keys of this objects custom properties (matches pythons\n"
+ " dictionary function of the same name).\n"
+ "\n"
+ " :return: custom property keys.\n"
+ " :rtype: list of strings\n"
+ "\n" BPY_DOC_ID_PROP_TYPE_NOTE);
static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
{
- IDProperty *group;
+ IDProperty *group;
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
- return NULL;
- }
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
+ group = RNA_struct_idprops(&self->ptr, 0);
- if (group == NULL) {
- return PyList_New(0);
- }
+ if (group == NULL) {
+ return PyList_New(0);
+ }
- return BPy_Wrap_GetKeys(group);
+ return BPy_Wrap_GetKeys(group);
}
PyDoc_STRVAR(pyrna_struct_items_doc,
-".. method:: items()\n"
-"\n"
-" Returns the items of this objects custom properties (matches pythons\n"
-" dictionary function of the same name).\n"
-"\n"
-" :return: custom property key, value pairs.\n"
-" :rtype: list of key, value tuples\n"
-"\n"
-BPY_DOC_ID_PROP_TYPE_NOTE
-);
+ ".. method:: items()\n"
+ "\n"
+ " Returns the items of this objects custom properties (matches pythons\n"
+ " dictionary function of the same name).\n"
+ "\n"
+ " :return: custom property key, value pairs.\n"
+ " :rtype: list of key, value tuples\n"
+ "\n" BPY_DOC_ID_PROP_TYPE_NOTE);
static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
{
- IDProperty *group;
+ IDProperty *group;
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
- return NULL;
- }
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
+ group = RNA_struct_idprops(&self->ptr, 0);
- if (group == NULL) {
- return PyList_New(0);
- }
+ if (group == NULL) {
+ return PyList_New(0);
+ }
- return BPy_Wrap_GetItems(self->ptr.id.data, group);
+ return BPy_Wrap_GetItems(self->ptr.id.data, group);
}
PyDoc_STRVAR(pyrna_struct_values_doc,
-".. method:: values()\n"
-"\n"
-" Returns the values of this objects custom properties (matches pythons\n"
-" dictionary function of the same name).\n"
-"\n"
-" :return: custom property values.\n"
-" :rtype: list\n"
-"\n"
-BPY_DOC_ID_PROP_TYPE_NOTE
-);
+ ".. method:: values()\n"
+ "\n"
+ " Returns the values of this objects custom properties (matches pythons\n"
+ " dictionary function of the same name).\n"
+ "\n"
+ " :return: custom property values.\n"
+ " :rtype: list\n"
+ "\n" BPY_DOC_ID_PROP_TYPE_NOTE);
static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
{
- IDProperty *group;
+ IDProperty *group;
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
- return NULL;
- }
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_struct.values(): this type doesn't support IDProperties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
+ group = RNA_struct_idprops(&self->ptr, 0);
- if (group == NULL) {
- return PyList_New(0);
- }
+ if (group == NULL) {
+ return PyList_New(0);
+ }
- return BPy_Wrap_GetValues(self->ptr.id.data, group);
+ return BPy_Wrap_GetValues(self->ptr.id.data, group);
}
-
PyDoc_STRVAR(pyrna_struct_is_property_set_doc,
-".. method:: is_property_set(property)\n"
-"\n"
-" Check if a property is set, use for testing operator properties.\n"
-"\n"
-" :return: True when the property has been set.\n"
-" :rtype: boolean\n"
-);
+ ".. method:: is_property_set(property)\n"
+ "\n"
+ " Check if a property is set, use for testing operator properties.\n"
+ "\n"
+ " :return: True when the property has been set.\n"
+ " :rtype: boolean\n");
static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
+ PropertyRNA *prop;
+ const char *name;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s:is_property_set", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:is_property_set", &name)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.is_property_set(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.is_property_set(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- return PyBool_FromLong(RNA_property_is_set(&self->ptr, prop));
+ return PyBool_FromLong(RNA_property_is_set(&self->ptr, prop));
}
PyDoc_STRVAR(pyrna_struct_property_unset_doc,
-".. method:: property_unset(property)\n"
-"\n"
-" Unset a property, will use default value afterward.\n"
-);
+ ".. method:: property_unset(property)\n"
+ "\n"
+ " Unset a property, will use default value afterward.\n");
static PyObject *pyrna_struct_property_unset(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
+ PropertyRNA *prop;
+ const char *name;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s:property_unset", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:property_unset", &name)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.property_unset(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.property_unset(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- RNA_property_unset(&self->ptr, prop);
+ RNA_property_unset(&self->ptr, prop);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyrna_struct_is_property_hidden_doc,
-".. method:: is_property_hidden(property)\n"
-"\n"
-" Check if a property is hidden.\n"
-"\n"
-" :return: True when the property is hidden.\n"
-" :rtype: boolean\n"
-);
+ ".. method:: is_property_hidden(property)\n"
+ "\n"
+ " Check if a property is hidden.\n"
+ "\n"
+ " :return: True when the property is hidden.\n"
+ " :rtype: boolean\n");
static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
+ PropertyRNA *prop;
+ const char *name;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.is_property_hidden(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.is_property_hidden(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
+ return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
}
PyDoc_STRVAR(pyrna_struct_is_property_readonly_doc,
-".. method:: is_property_readonly(property)\n"
-"\n"
-" Check if a property is readonly.\n"
-"\n"
-" :return: True when the property is readonly (not writable).\n"
-" :rtype: boolean\n"
-);
+ ".. method:: is_property_readonly(property)\n"
+ "\n"
+ " Check if a property is readonly.\n"
+ "\n"
+ " :return: True when the property is readonly (not writable).\n"
+ " :rtype: boolean\n");
static PyObject *pyrna_struct_is_property_readonly(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
+ PropertyRNA *prop;
+ const char *name;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s:is_property_readonly", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:is_property_readonly", &name)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.is_property_readonly(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.is_property_readonly(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- return PyBool_FromLong(!RNA_property_editable(&self->ptr, prop));
+ return PyBool_FromLong(!RNA_property_editable(&self->ptr, prop));
}
-
PyDoc_STRVAR(pyrna_struct_is_property_overridable_static_doc,
-".. method:: is_property_overridable_static(property)\n"
-"\n"
-" Check if a property is statically overridable.\n"
-"\n"
-" :return: True when the property is statically overridable.\n"
-" :rtype: boolean\n"
-);
+ ".. method:: is_property_overridable_static(property)\n"
+ "\n"
+ " Check if a property is statically overridable.\n"
+ "\n"
+ " :return: True when the property is statically overridable.\n"
+ " :rtype: boolean\n");
static PyObject *pyrna_struct_is_property_overridable_static(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
+ PropertyRNA *prop;
+ const char *name;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s:is_property_overridable_static", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:is_property_overridable_static", &name)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.is_property_overridable_static(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.is_property_overridable_static(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- return PyBool_FromLong((long)RNA_property_overridable_get(&self->ptr, prop));
+ return PyBool_FromLong((long)RNA_property_overridable_get(&self->ptr, prop));
}
-PyDoc_STRVAR(pyrna_struct_property_overridable_static_set_doc,
-".. method:: property_overridable_static_set(property)\n"
-"\n"
-" Define a property as statically overridable or not (only for custom properties!).\n"
-"\n"
-" :return: True when the overridable status of the property was successfully set.\n"
-" :rtype: boolean\n"
-);
+PyDoc_STRVAR(
+ pyrna_struct_property_overridable_static_set_doc,
+ ".. method:: property_overridable_static_set(property)\n"
+ "\n"
+ " Define a property as statically overridable or not (only for custom properties!).\n"
+ "\n"
+ " :return: True when the overridable status of the property was successfully set.\n"
+ " :rtype: boolean\n");
static PyObject *pyrna_struct_property_overridable_static_set(BPy_StructRNA *self, PyObject *args)
{
- PropertyRNA *prop;
- const char *name;
- int is_overridable;
+ PropertyRNA *prop;
+ const char *name;
+ int is_overridable;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "sp:property_overridable_static_set", &name, &is_overridable)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "sp:property_overridable_static_set", &name, &is_overridable)) {
+ return NULL;
+ }
- if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.property_overridable_static_set(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
+ if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.property_overridable_static_set(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
- return PyBool_FromLong((long)RNA_property_overridable_static_set(&self->ptr, prop, (bool)is_overridable));
+ return PyBool_FromLong(
+ (long)RNA_property_overridable_static_set(&self->ptr, prop, (bool)is_overridable));
}
-
-
PyDoc_STRVAR(pyrna_struct_path_resolve_doc,
-".. method:: path_resolve(path, coerce=True)\n"
-"\n"
-" Returns the property from the path, raise an exception when not found.\n"
-"\n"
-" :arg path: path which this property resolves.\n"
-" :type path: string\n"
-" :arg coerce: optional argument, when True, the property will be converted\n"
-" into its python representation.\n"
-" :type coerce: boolean\n"
-);
+ ".. method:: path_resolve(path, coerce=True)\n"
+ "\n"
+ " Returns the property from the path, raise an exception when not found.\n"
+ "\n"
+ " :arg path: path which this property resolves.\n"
+ " :type path: string\n"
+ " :arg coerce: optional argument, when True, the property will be converted\n"
+ " into its python representation.\n"
+ " :type coerce: boolean\n");
static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
{
- const char *path;
- PyObject *coerce = Py_True;
- PointerRNA r_ptr;
- PropertyRNA *r_prop;
- int index = -1;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce)) {
- return NULL;
- }
-
- if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
- if (r_prop) {
- if (index != -1) {
- if (index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
- PyErr_Format(PyExc_IndexError,
- "%.200s.path_resolve(\"%.200s\") index out of range",
- RNA_struct_identifier(self->ptr.type), path);
- return NULL;
- }
- else {
- return pyrna_array_index(&r_ptr, r_prop, index);
- }
- }
- else {
- if (coerce == Py_False) {
- return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
- }
- else {
- return pyrna_prop_to_py(&r_ptr, r_prop);
- }
- }
- }
- else {
- return pyrna_struct_CreatePyObject(&r_ptr);
- }
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "%.200s.path_resolve(\"%.200s\") could not be resolved",
- RNA_struct_identifier(self->ptr.type), path);
- return NULL;
- }
+ const char *path;
+ PyObject *coerce = Py_True;
+ PointerRNA r_ptr;
+ PropertyRNA *r_prop;
+ int index = -1;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce)) {
+ return NULL;
+ }
+
+ if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
+ if (r_prop) {
+ if (index != -1) {
+ if (index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
+ PyErr_Format(PyExc_IndexError,
+ "%.200s.path_resolve(\"%.200s\") index out of range",
+ RNA_struct_identifier(self->ptr.type),
+ path);
+ return NULL;
+ }
+ else {
+ return pyrna_array_index(&r_ptr, r_prop, index);
+ }
+ }
+ else {
+ if (coerce == Py_False) {
+ return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
+ }
+ else {
+ return pyrna_prop_to_py(&r_ptr, r_prop);
+ }
+ }
+ }
+ else {
+ return pyrna_struct_CreatePyObject(&r_ptr);
+ }
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s.path_resolve(\"%.200s\") could not be resolved",
+ RNA_struct_identifier(self->ptr.type),
+ path);
+ return NULL;
+ }
}
PyDoc_STRVAR(pyrna_struct_path_from_id_doc,
-".. method:: path_from_id(property=\"\")\n"
-"\n"
-" Returns the data path from the ID to this object (string).\n"
-"\n"
-" :arg property: Optional property name which can be used if the path is\n"
-" to a property of this object.\n"
-" :type property: string\n"
-" :return: The path from :class:`bpy.types.bpy_struct.id_data`\n"
-" to this struct and property (when given).\n"
-" :rtype: str\n"
-);
+ ".. method:: path_from_id(property=\"\")\n"
+ "\n"
+ " Returns the data path from the ID to this object (string).\n"
+ "\n"
+ " :arg property: Optional property name which can be used if the path is\n"
+ " to a property of this object.\n"
+ " :type property: string\n"
+ " :return: The path from :class:`bpy.types.bpy_struct.id_data`\n"
+ " to this struct and property (when given).\n"
+ " :rtype: str\n");
static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
{
- const char *name = NULL;
- const char *path;
- PropertyRNA *prop;
- PyObject *ret;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "|s:path_from_id", &name)) {
- return NULL;
- }
-
- if (name) {
- prop = RNA_struct_find_property(&self->ptr, name);
- if (prop == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "%.200s.path_from_id(\"%.200s\") not found",
- RNA_struct_identifier(self->ptr.type), name);
- return NULL;
- }
-
- path = RNA_path_from_ID_to_property(&self->ptr, prop);
- }
- else {
- path = RNA_path_from_ID_to_struct(&self->ptr);
- }
-
- if (path == NULL) {
- if (name) {
- PyErr_Format(PyExc_ValueError,
- "%.200s.path_from_id(\"%s\") found but does not support path creation",
- RNA_struct_identifier(self->ptr.type), name);
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "%.200s.path_from_id() does not support path creation for this type",
- RNA_struct_identifier(self->ptr.type));
- }
- return NULL;
- }
-
- ret = PyUnicode_FromString(path);
- MEM_freeN((void *)path);
-
- return ret;
+ const char *name = NULL;
+ const char *path;
+ PropertyRNA *prop;
+ PyObject *ret;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "|s:path_from_id", &name)) {
+ return NULL;
+ }
+
+ if (name) {
+ prop = RNA_struct_find_property(&self->ptr, name);
+ if (prop == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "%.200s.path_from_id(\"%.200s\") not found",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ return NULL;
+ }
+
+ path = RNA_path_from_ID_to_property(&self->ptr, prop);
+ }
+ else {
+ path = RNA_path_from_ID_to_struct(&self->ptr);
+ }
+
+ if (path == NULL) {
+ if (name) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s.path_from_id(\"%s\") found but does not support path creation",
+ RNA_struct_identifier(self->ptr.type),
+ name);
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s.path_from_id() does not support path creation for this type",
+ RNA_struct_identifier(self->ptr.type));
+ }
+ return NULL;
+ }
+
+ ret = PyUnicode_FromString(path);
+ MEM_freeN((void *)path);
+
+ return ret;
}
PyDoc_STRVAR(pyrna_prop_path_from_id_doc,
-".. method:: path_from_id()\n"
-"\n"
-" Returns the data path from the ID to this property (string).\n"
-"\n"
-" :return: The path from :class:`bpy.types.bpy_struct.id_data` to this property.\n"
-" :rtype: str\n"
-);
+ ".. method:: path_from_id()\n"
+ "\n"
+ " Returns the data path from the ID to this property (string).\n"
+ "\n"
+ " :return: The path from :class:`bpy.types.bpy_struct.id_data` to this property.\n"
+ " :rtype: str\n");
static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
{
- const char *path;
- PropertyRNA *prop = self->prop;
- PyObject *ret;
+ const char *path;
+ PropertyRNA *prop = self->prop;
+ PyObject *ret;
- path = RNA_path_from_ID_to_property(&self->ptr, self->prop);
+ path = RNA_path_from_ID_to_property(&self->ptr, self->prop);
- if (path == NULL) {
- PyErr_Format(PyExc_ValueError,
- "%.200s.%.200s.path_from_id() does not support path creation for this type",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
- return NULL;
- }
+ if (path == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s.%.200s.path_from_id() does not support path creation for this type",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(prop));
+ return NULL;
+ }
- ret = PyUnicode_FromString(path);
- MEM_freeN((void *)path);
+ ret = PyUnicode_FromString(path);
+ MEM_freeN((void *)path);
- return ret;
+ return ret;
}
PyDoc_STRVAR(pyrna_prop_as_bytes_doc,
-".. method:: as_bytes()\n"
-"\n"
-" Returns this string property as a byte rather than a python string.\n"
-"\n"
-" :return: The string as bytes.\n"
-" :rtype: bytes\n"
-);
+ ".. method:: as_bytes()\n"
+ "\n"
+ " Returns this string property as a byte rather than a python string.\n"
+ "\n"
+ " :return: The string as bytes.\n"
+ " :rtype: bytes\n");
static PyObject *pyrna_prop_as_bytes(BPy_PropertyRNA *self)
{
- if (RNA_property_type(self->prop) != PROP_STRING) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.%.200s.as_bytes() must be a string",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
- return NULL;
- }
- else {
- PyObject *ret;
- char buf_fixed[256], *buf;
- int buf_len;
+ if (RNA_property_type(self->prop) != PROP_STRING) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.%.200s.as_bytes() must be a string",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop));
+ return NULL;
+ }
+ else {
+ PyObject *ret;
+ char buf_fixed[256], *buf;
+ int buf_len;
- buf = RNA_property_string_get_alloc(&self->ptr, self->prop, buf_fixed, sizeof(buf_fixed), &buf_len);
+ buf = RNA_property_string_get_alloc(
+ &self->ptr, self->prop, buf_fixed, sizeof(buf_fixed), &buf_len);
- ret = PyBytes_FromStringAndSize(buf, buf_len);
+ ret = PyBytes_FromStringAndSize(buf, buf_len);
- if (buf_fixed != buf) {
- MEM_freeN(buf);
- }
+ if (buf_fixed != buf) {
+ MEM_freeN(buf);
+ }
- return ret;
- }
+ return ret;
+ }
}
PyDoc_STRVAR(pyrna_prop_update_doc,
-".. method:: update()\n"
-"\n"
-" Execute the properties update callback.\n"
-"\n"
-" .. note::\n"
-" This is called when assigning a property,\n"
-" however in rare cases its useful to call explicitly.\n"
-);
+ ".. method:: update()\n"
+ "\n"
+ " Execute the properties update callback.\n"
+ "\n"
+ " .. note::\n"
+ " This is called when assigning a property,\n"
+ " however in rare cases its useful to call explicitly.\n");
static PyObject *pyrna_prop_update(BPy_PropertyRNA *self)
{
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
- Py_RETURN_NONE;
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyrna_struct_type_recast_doc,
-".. method:: type_recast()\n"
-"\n"
-" Return a new instance, this is needed because types\n"
-" such as textures can be changed at runtime.\n"
-"\n"
-" :return: a new instance of this object with the type initialized again.\n"
-" :rtype: subclass of :class:`bpy.types.bpy_struct`\n"
-);
+ ".. method:: type_recast()\n"
+ "\n"
+ " Return a new instance, this is needed because types\n"
+ " such as textures can be changed at runtime.\n"
+ "\n"
+ " :return: a new instance of this object with the type initialized again.\n"
+ " :rtype: subclass of :class:`bpy.types.bpy_struct`\n");
static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
{
- PointerRNA r_ptr;
+ PointerRNA r_ptr;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- RNA_pointer_recast(&self->ptr, &r_ptr);
- return pyrna_struct_CreatePyObject(&r_ptr);
+ RNA_pointer_recast(&self->ptr, &r_ptr);
+ return pyrna_struct_CreatePyObject(&r_ptr);
}
/**
@@ -3889,1441 +3941,1445 @@ static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
*/
static PyObject *pyrna_struct_bl_rna_find_subclass_recursive(PyObject *cls, const char *id)
{
- PyObject *ret_test = NULL;
- PyObject *subclasses = ((PyTypeObject *)cls)->tp_subclasses;
- if (subclasses) {
- /* Unfortunately we can't use the dict key because Python class names
- * don't match the bl_idname used internally. */
- BLI_assert(PyDict_CheckExact(subclasses));
- PyObject *key = NULL;
- Py_ssize_t pos = 0;
- PyObject *value = NULL;
- while (PyDict_Next(subclasses, &pos, &key, &value)) {
- BLI_assert(PyWeakref_CheckRef(value));
- PyObject *subcls = PyWeakref_GET_OBJECT(value);
- if (subcls != Py_None) {
- BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(
- ((PyTypeObject *)subcls)->tp_dict, bpy_intern_str_bl_rna);
- if (py_srna) {
- StructRNA *srna = py_srna->ptr.data;
- if (STREQ(id, RNA_struct_identifier(srna))) {
- ret_test = subcls;
- break;
- }
- }
- ret_test = pyrna_struct_bl_rna_find_subclass_recursive(subcls, id);
- if (ret_test) {
- break;
- }
- }
- }
- }
- return ret_test;
+ PyObject *ret_test = NULL;
+ PyObject *subclasses = ((PyTypeObject *)cls)->tp_subclasses;
+ if (subclasses) {
+ /* Unfortunately we can't use the dict key because Python class names
+ * don't match the bl_idname used internally. */
+ BLI_assert(PyDict_CheckExact(subclasses));
+ PyObject *key = NULL;
+ Py_ssize_t pos = 0;
+ PyObject *value = NULL;
+ while (PyDict_Next(subclasses, &pos, &key, &value)) {
+ BLI_assert(PyWeakref_CheckRef(value));
+ PyObject *subcls = PyWeakref_GET_OBJECT(value);
+ if (subcls != Py_None) {
+ BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)subcls)->tp_dict,
+ bpy_intern_str_bl_rna);
+ if (py_srna) {
+ StructRNA *srna = py_srna->ptr.data;
+ if (STREQ(id, RNA_struct_identifier(srna))) {
+ ret_test = subcls;
+ break;
+ }
+ }
+ ret_test = pyrna_struct_bl_rna_find_subclass_recursive(subcls, id);
+ if (ret_test) {
+ break;
+ }
+ }
+ }
+ }
+ return ret_test;
}
PyDoc_STRVAR(pyrna_struct_bl_rna_get_subclass_py_doc,
-".. classmethod:: bl_rna_get_subclass_py(id, default=None)\n"
-"\n"
-" :arg id: The RNA type identifier.\n"
-" :type id: string\n"
-" :return: The class or default when not found.\n"
-" :rtype: type\n"
-);
+ ".. classmethod:: bl_rna_get_subclass_py(id, default=None)\n"
+ "\n"
+ " :arg id: The RNA type identifier.\n"
+ " :type id: string\n"
+ " :return: The class or default when not found.\n"
+ " :rtype: type\n");
static PyObject *pyrna_struct_bl_rna_get_subclass_py(PyObject *cls, PyObject *args)
{
- char *id;
- PyObject *ret_default = Py_None;
+ char *id;
+ PyObject *ret_default = Py_None;
- if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass_py", &id, &ret_default)) {
- return NULL;
- }
- PyObject *ret = pyrna_struct_bl_rna_find_subclass_recursive(cls, id);
- if (ret == NULL) {
- ret = ret_default;
- }
- return Py_INCREF_RET(ret);
+ if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass_py", &id, &ret_default)) {
+ return NULL;
+ }
+ PyObject *ret = pyrna_struct_bl_rna_find_subclass_recursive(cls, id);
+ if (ret == NULL) {
+ ret = ret_default;
+ }
+ return Py_INCREF_RET(ret);
}
PyDoc_STRVAR(pyrna_struct_bl_rna_get_subclass_doc,
-".. classmethod:: bl_rna_get_subclass(id, default=None)\n"
-"\n"
-" :arg id: The RNA type identifier.\n"
-" :type id: string\n"
-" :return: The RNA type or default when not found.\n"
-" :rtype: :class:`bpy.types.Struct` subclass\n"
-);
+ ".. classmethod:: bl_rna_get_subclass(id, default=None)\n"
+ "\n"
+ " :arg id: The RNA type identifier.\n"
+ " :type id: string\n"
+ " :return: The RNA type or default when not found.\n"
+ " :rtype: :class:`bpy.types.Struct` subclass\n");
static PyObject *pyrna_struct_bl_rna_get_subclass(PyObject *cls, PyObject *args)
{
- char *id;
- PyObject *ret_default = Py_None;
-
- if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass", &id, &ret_default)) {
- return NULL;
- }
-
-
- const BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)cls)->tp_dict, bpy_intern_str_bl_rna);
- if (py_srna == NULL) {
- PyErr_SetString(PyExc_ValueError, "Not a registered class");
- return NULL;
-
- }
- const StructRNA *srna_base = py_srna->ptr.data;
-
- PointerRNA ptr;
- if (srna_base == &RNA_Node) {
- bNodeType *nt = nodeTypeFind(id);
- if (nt) {
- RNA_pointer_create(NULL, &RNA_Struct, nt->ext.srna, &ptr);
- return pyrna_struct_CreatePyObject(&ptr);
- }
- }
- else {
- /* TODO, panels, menus etc. */
- PyErr_Format(PyExc_ValueError, "Class type \"%.200s\" not supported",
- RNA_struct_identifier(srna_base));
- return NULL;
- }
-
- return Py_INCREF_RET(ret_default);
+ char *id;
+ PyObject *ret_default = Py_None;
+
+ if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass", &id, &ret_default)) {
+ return NULL;
+ }
+
+ const BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)cls)->tp_dict,
+ bpy_intern_str_bl_rna);
+ if (py_srna == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Not a registered class");
+ return NULL;
+ }
+ const StructRNA *srna_base = py_srna->ptr.data;
+
+ PointerRNA ptr;
+ if (srna_base == &RNA_Node) {
+ bNodeType *nt = nodeTypeFind(id);
+ if (nt) {
+ RNA_pointer_create(NULL, &RNA_Struct, nt->ext.srna, &ptr);
+ return pyrna_struct_CreatePyObject(&ptr);
+ }
+ }
+ else {
+ /* TODO, panels, menus etc. */
+ PyErr_Format(
+ PyExc_ValueError, "Class type \"%.200s\" not supported", RNA_struct_identifier(srna_base));
+ return NULL;
+ }
+
+ return Py_INCREF_RET(ret_default);
}
static void pyrna_dir_members_py__add_keys(PyObject *list, PyObject *dict)
{
- PyObject *list_tmp;
+ PyObject *list_tmp;
- list_tmp = PyDict_Keys(dict);
- PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
- Py_DECREF(list_tmp);
+ list_tmp = PyDict_Keys(dict);
+ PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
+ Py_DECREF(list_tmp);
}
static void pyrna_dir_members_py(PyObject *list, PyObject *self)
{
- PyObject *dict;
- PyObject **dict_ptr;
+ PyObject *dict;
+ PyObject **dict_ptr;
- dict_ptr = _PyObject_GetDictPtr((PyObject *)self);
+ dict_ptr = _PyObject_GetDictPtr((PyObject *)self);
- if (dict_ptr && (dict = *dict_ptr)) {
- pyrna_dir_members_py__add_keys(list, dict);
- }
+ if (dict_ptr && (dict = *dict_ptr)) {
+ pyrna_dir_members_py__add_keys(list, dict);
+ }
- dict = ((PyTypeObject *)Py_TYPE(self))->tp_dict;
- if (dict) {
- pyrna_dir_members_py__add_keys(list, dict);
- }
+ dict = ((PyTypeObject *)Py_TYPE(self))->tp_dict;
+ if (dict) {
+ pyrna_dir_members_py__add_keys(list, dict);
+ }
- /* since this is least common case, handle it last */
- if (BPy_PropertyRNA_Check(self)) {
- BPy_PropertyRNA *self_prop = (BPy_PropertyRNA *)self;
- if (RNA_property_type(self_prop->prop) == PROP_COLLECTION) {
- PointerRNA r_ptr;
+ /* since this is least common case, handle it last */
+ if (BPy_PropertyRNA_Check(self)) {
+ BPy_PropertyRNA *self_prop = (BPy_PropertyRNA *)self;
+ if (RNA_property_type(self_prop->prop) == PROP_COLLECTION) {
+ PointerRNA r_ptr;
- if (RNA_property_collection_type_get(&self_prop->ptr, self_prop->prop, &r_ptr)) {
- PyObject *cls = pyrna_struct_Subtype(&r_ptr); /* borrows */
- dict = ((PyTypeObject *)cls)->tp_dict;
- pyrna_dir_members_py__add_keys(list, dict);
- Py_DECREF(cls);
- }
- }
- }
+ if (RNA_property_collection_type_get(&self_prop->ptr, self_prop->prop, &r_ptr)) {
+ PyObject *cls = pyrna_struct_Subtype(&r_ptr); /* borrows */
+ dict = ((PyTypeObject *)cls)->tp_dict;
+ pyrna_dir_members_py__add_keys(list, dict);
+ Py_DECREF(cls);
+ }
+ }
+ }
}
static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
{
- const char *idname;
+ const char *idname;
- /* for looping over attrs and funcs */
- PointerRNA tptr;
- PropertyRNA *iterprop;
+ /* for looping over attrs and funcs */
+ PointerRNA tptr;
+ PropertyRNA *iterprop;
- {
- RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
- iterprop = RNA_struct_find_property(&tptr, "functions");
+ {
+ RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
+ iterprop = RNA_struct_find_property(&tptr, "functions");
- RNA_PROP_BEGIN (&tptr, itemptr, iterprop)
- {
- FunctionRNA *func = itemptr.data;
- if (RNA_function_defined(func)) {
- idname = RNA_function_identifier(itemptr.data);
- PyList_APPEND(list, PyUnicode_FromString(idname));
- }
- }
- RNA_PROP_END;
- }
+ RNA_PROP_BEGIN (&tptr, itemptr, iterprop) {
+ FunctionRNA *func = itemptr.data;
+ if (RNA_function_defined(func)) {
+ idname = RNA_function_identifier(itemptr.data);
+ PyList_APPEND(list, PyUnicode_FromString(idname));
+ }
+ }
+ RNA_PROP_END;
+ }
- {
- /*
- * Collect RNA attributes
- */
- char name[256], *nameptr;
- int namelen;
+ {
+ /*
+ * Collect RNA attributes
+ */
+ char name[256], *nameptr;
+ int namelen;
- iterprop = RNA_struct_iterator_property(ptr->type);
+ iterprop = RNA_struct_iterator_property(ptr->type);
- RNA_PROP_BEGIN (ptr, itemptr, iterprop)
- {
- nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
+ RNA_PROP_BEGIN (ptr, itemptr, iterprop) {
+ nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
- if (nameptr) {
- PyList_APPEND(list, PyUnicode_FromStringAndSize(nameptr, namelen));
+ if (nameptr) {
+ PyList_APPEND(list, PyUnicode_FromStringAndSize(nameptr, namelen));
- if (name != nameptr) {
- MEM_freeN(nameptr);
- }
- }
- }
- RNA_PROP_END;
- }
+ if (name != nameptr) {
+ MEM_freeN(nameptr);
+ }
+ }
+ }
+ RNA_PROP_END;
+ }
}
-
static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
{
- PyObject *ret;
+ PyObject *ret;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- /* Include this in case this instance is a subtype of a python class
- * In these instances we may want to return a function or variable provided by the subtype
- * */
- ret = PyList_New(0);
+ /* Include this in case this instance is a subtype of a python class
+ * In these instances we may want to return a function or variable provided by the subtype
+ * */
+ ret = PyList_New(0);
- if (!BPy_StructRNA_CheckExact(self)) {
- pyrna_dir_members_py(ret, (PyObject *)self);
- }
+ if (!BPy_StructRNA_CheckExact(self)) {
+ pyrna_dir_members_py(ret, (PyObject *)self);
+ }
- pyrna_dir_members_rna(ret, &self->ptr);
+ pyrna_dir_members_rna(ret, &self->ptr);
- if (self->ptr.type == &RNA_Context) {
- ListBase lb = CTX_data_dir_get(self->ptr.data);
- LinkData *link;
+ if (self->ptr.type == &RNA_Context) {
+ ListBase lb = CTX_data_dir_get(self->ptr.data);
+ LinkData *link;
- for (link = lb.first; link; link = link->next) {
- PyList_APPEND(ret, PyUnicode_FromString(link->data));
- }
+ for (link = lb.first; link; link = link->next) {
+ PyList_APPEND(ret, PyUnicode_FromString(link->data));
+ }
- BLI_freelistN(&lb);
- }
+ BLI_freelistN(&lb);
+ }
- {
- /* set(), this is needed to remove-doubles because the deferred
- * register-props will be in both the python __dict__ and accessed as RNA */
+ {
+ /* set(), this is needed to remove-doubles because the deferred
+ * register-props will be in both the python __dict__ and accessed as RNA */
- PyObject *set = PySet_New(ret);
+ PyObject *set = PySet_New(ret);
- Py_DECREF(ret);
- ret = PySequence_List(set);
- Py_DECREF(set);
- }
+ Py_DECREF(ret);
+ ret = PySequence_List(set);
+ Py_DECREF(set);
+ }
- return ret;
+ return ret;
}
/* ---------------getattr-------------------------------------------- */
static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
{
- const char *name = _PyUnicode_AsString(pyname);
- PyObject *ret;
- PropertyRNA *prop;
- FunctionRNA *func;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (name == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
- ret = NULL;
- }
- else if (name[0] == '_') { /* rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups */
- /* annoying exception, maybe we need to have different types for this... */
- if (STR_ELEM(name, "__getitem__", "__setitem__") && !RNA_struct_idprops_check(self->ptr.type)) {
- PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
- ret = NULL;
- }
- else {
- ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
- }
- }
- else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
- ret = pyrna_prop_to_py(&self->ptr, prop);
- }
- /* RNA function only if callback is declared (no optional functions) */
- else if ((func = RNA_struct_find_function(self->ptr.type, name)) && RNA_function_defined(func)) {
- ret = pyrna_func_to_py(&self->ptr, func);
- }
- else if (self->ptr.type == &RNA_Context) {
- bContext *C = self->ptr.data;
- if (C == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context",
- name);
- ret = NULL;
- }
- else {
- PointerRNA newptr;
- ListBase newlb;
- short newtype;
-
- int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
-
- if (done == 1) { /* found */
- switch (newtype) {
- case CTX_DATA_TYPE_POINTER:
- if (newptr.data == NULL) {
- ret = Py_None;
- Py_INCREF(ret);
- }
- else {
- ret = pyrna_struct_CreatePyObject(&newptr);
- }
- break;
- case CTX_DATA_TYPE_COLLECTION:
- {
- CollectionPointerLink *link;
-
- ret = PyList_New(0);
-
- for (link = newlb.first; link; link = link->next) {
- PyList_APPEND(ret, pyrna_struct_CreatePyObject(&link->ptr));
- }
- break;
- }
- default:
- /* should never happen */
- BLI_assert(!"Invalid context type");
-
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
- newtype, name);
- ret = NULL;
- break;
- }
- }
- else if (done == -1) { /* found but not set */
- ret = Py_None;
- Py_INCREF(ret);
- }
- else { /* not found in the context */
- /* lookup the subclass. raise an error if its not found */
- ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
- }
-
- BLI_freelistN(&newlb);
- }
- }
- else {
+ const char *name = _PyUnicode_AsString(pyname);
+ PyObject *ret;
+ PropertyRNA *prop;
+ FunctionRNA *func;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (name == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
+ ret = NULL;
+ }
+ else if (
+ name[0] ==
+ '_') { /* rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups */
+ /* annoying exception, maybe we need to have different types for this... */
+ if (STR_ELEM(name, "__getitem__", "__setitem__") &&
+ !RNA_struct_idprops_check(self->ptr.type)) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
+ ret = NULL;
+ }
+ else {
+ ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
+ }
+ }
+ else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
+ ret = pyrna_prop_to_py(&self->ptr, prop);
+ }
+ /* RNA function only if callback is declared (no optional functions) */
+ else if ((func = RNA_struct_find_function(self->ptr.type, name)) && RNA_function_defined(func)) {
+ ret = pyrna_func_to_py(&self->ptr, func);
+ }
+ else if (self->ptr.type == &RNA_Context) {
+ bContext *C = self->ptr.data;
+ if (C == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context",
+ name);
+ ret = NULL;
+ }
+ else {
+ PointerRNA newptr;
+ ListBase newlb;
+ short newtype;
+
+ int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
+
+ if (done == 1) { /* found */
+ switch (newtype) {
+ case CTX_DATA_TYPE_POINTER:
+ if (newptr.data == NULL) {
+ ret = Py_None;
+ Py_INCREF(ret);
+ }
+ else {
+ ret = pyrna_struct_CreatePyObject(&newptr);
+ }
+ break;
+ case CTX_DATA_TYPE_COLLECTION: {
+ CollectionPointerLink *link;
+
+ ret = PyList_New(0);
+
+ for (link = newlb.first; link; link = link->next) {
+ PyList_APPEND(ret, pyrna_struct_CreatePyObject(&link->ptr));
+ }
+ break;
+ }
+ default:
+ /* should never happen */
+ BLI_assert(!"Invalid context type");
+
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
+ newtype,
+ name);
+ ret = NULL;
+ break;
+ }
+ }
+ else if (done == -1) { /* found but not set */
+ ret = Py_None;
+ Py_INCREF(ret);
+ }
+ else { /* not found in the context */
+ /* lookup the subclass. raise an error if its not found */
+ ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
+ }
+
+ BLI_freelistN(&newlb);
+ }
+ }
+ else {
#if 0
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: attribute \"%.200s\" not found",
- name);
- ret = NULL;
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_struct: attribute \"%.200s\" not found",
+ name);
+ ret = NULL;
#endif
- /* Include this in case this instance is a subtype of a python class
- * In these instances we may want to return a function or variable provided by the subtype
- *
- * Also needed to return methods when its not a subtype
- * */
+ /* Include this in case this instance is a subtype of a python class
+ * In these instances we may want to return a function or variable provided by the subtype
+ *
+ * Also needed to return methods when its not a subtype
+ * */
- /* The error raised here will be displayed */
- ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
- }
+ /* The error raised here will be displayed */
+ ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
+ }
- return ret;
+ return ret;
}
#if 0
static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
{
- PyObject *dict = *(_PyObject_GetDictPtr((PyObject *)self));
- if (dict == NULL) /* unlikely */
- return 0;
+ PyObject *dict = *(_PyObject_GetDictPtr((PyObject *)self));
+ if (dict == NULL) /* unlikely */
+ return 0;
- return PyDict_Contains(dict, pyname);
+ return PyDict_Contains(dict, pyname);
}
#endif
/* --------------- setattr------------------------------------------- */
static bool pyrna_is_deferred_prop(const PyObject *value)
{
- return PyTuple_CheckExact(value) &&
- PyTuple_GET_SIZE(value) == 2 &&
- PyCFunction_Check(PyTuple_GET_ITEM(value, 0)) &&
- PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
+ return PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value) == 2 &&
+ PyCFunction_Check(PyTuple_GET_ITEM(value, 0)) &&
+ PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
}
#if 0
static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
{
- PyObject *ret = PyType_Type.tp_getattro(cls, attr);
-
- /* Allows:
- * >>> bpy.types.Scene.foo = BoolProperty()
- * >>> bpy.types.Scene.foo
- * <bpy_struct, BoolProperty("foo")>
- * ...rather than returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
- *
- * Disable for now, this is faking internal behavior in a way that's too tricky to maintain well. */
-#if 0
- if (ret == NULL) { // || pyrna_is_deferred_prop(ret)
- StructRNA *srna = srna_from_self(cls, "StructRNA.__getattr__");
- if (srna) {
- PropertyRNA *prop = RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
- if (prop) {
- PointerRNA tptr;
- PyErr_Clear(); /* clear error from tp_getattro */
- RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
- ret = pyrna_struct_CreatePyObject(&tptr);
- }
- }
- }
-#endif
-
- return ret;
+ PyObject *ret = PyType_Type.tp_getattro(cls, attr);
+
+ /* Allows:
+ * >>> bpy.types.Scene.foo = BoolProperty()
+ * >>> bpy.types.Scene.foo
+ * <bpy_struct, BoolProperty("foo")>
+ * ...rather than returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
+ *
+ * Disable for now, this is faking internal behavior in a way that's too tricky to maintain well. */
+# if 0
+ if (ret == NULL) { // || pyrna_is_deferred_prop(ret)
+ StructRNA *srna = srna_from_self(cls, "StructRNA.__getattr__");
+ if (srna) {
+ PropertyRNA *prop = RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
+ if (prop) {
+ PointerRNA tptr;
+ PyErr_Clear(); /* clear error from tp_getattro */
+ RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
+ ret = pyrna_struct_CreatePyObject(&tptr);
+ }
+ }
+ }
+# endif
+
+ return ret;
}
#endif
static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
{
- StructRNA *srna = srna_from_self(cls, "StructRNA.__setattr__");
- const bool is_deferred_prop = (value && pyrna_is_deferred_prop(value));
- const char *attr_str = _PyUnicode_AsString(attr);
-
- if (srna && !pyrna_write_check() && (is_deferred_prop || RNA_struct_type_find_property(srna, attr_str))) {
- PyErr_Format(PyExc_AttributeError,
- "pyrna_struct_meta_idprop_setattro() "
- "can't set in readonly state '%.200s.%S'",
- ((PyTypeObject *)cls)->tp_name, attr);
- return -1;
- }
-
- if (srna == NULL) {
- /* allow setting on unregistered classes which can be registered later on */
+ StructRNA *srna = srna_from_self(cls, "StructRNA.__setattr__");
+ const bool is_deferred_prop = (value && pyrna_is_deferred_prop(value));
+ const char *attr_str = _PyUnicode_AsString(attr);
+
+ if (srna && !pyrna_write_check() &&
+ (is_deferred_prop || RNA_struct_type_find_property(srna, attr_str))) {
+ PyErr_Format(PyExc_AttributeError,
+ "pyrna_struct_meta_idprop_setattro() "
+ "can't set in readonly state '%.200s.%S'",
+ ((PyTypeObject *)cls)->tp_name,
+ attr);
+ return -1;
+ }
+
+ if (srna == NULL) {
+ /* allow setting on unregistered classes which can be registered later on */
#if 0
- if (value && is_deferred_prop) {
- PyErr_Format(PyExc_AttributeError,
- "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'",
- ((PyTypeObject *)cls)->tp_name);
- return -1;
- }
+ if (value && is_deferred_prop) {
+ PyErr_Format(PyExc_AttributeError,
+ "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'",
+ ((PyTypeObject *)cls)->tp_name);
+ return -1;
+ }
#endif
- /* srna_from_self may set an error */
- PyErr_Clear();
- return PyType_Type.tp_setattro(cls, attr, value);
- }
-
- if (value) {
- /* check if the value is a property */
- if (is_deferred_prop) {
- int ret = deferred_register_prop(srna, attr, value);
- if (ret == -1) {
- /* error set */
- return ret;
- }
-
- /* pass through and assign to the classes __dict__ as well
- * when the value isn't assigned it still creates the RNA property
- * but gets confusing from script writers POV if the assigned value cant be read back. */
- }
- else {
- /* remove existing property if its set or we also end up with confusion */
- RNA_def_property_free_identifier(srna, attr_str); /* ignore on failure */
- }
- }
- else { /* __delattr__ */
- /* first find if this is a registered property */
- const int ret = RNA_def_property_free_identifier(srna, attr_str);
- if (ret == -1) {
- PyErr_Format(PyExc_TypeError,
- "struct_meta_idprop.detattr(): '%s' not a dynamic property",
- attr_str);
- return -1;
- }
- }
-
- /* fallback to standard py, delattr/setattr */
- return PyType_Type.tp_setattro(cls, attr, value);
+ /* srna_from_self may set an error */
+ PyErr_Clear();
+ return PyType_Type.tp_setattro(cls, attr, value);
+ }
+
+ if (value) {
+ /* check if the value is a property */
+ if (is_deferred_prop) {
+ int ret = deferred_register_prop(srna, attr, value);
+ if (ret == -1) {
+ /* error set */
+ return ret;
+ }
+
+ /* pass through and assign to the classes __dict__ as well
+ * when the value isn't assigned it still creates the RNA property
+ * but gets confusing from script writers POV if the assigned value cant be read back. */
+ }
+ else {
+ /* remove existing property if its set or we also end up with confusion */
+ RNA_def_property_free_identifier(srna, attr_str); /* ignore on failure */
+ }
+ }
+ else { /* __delattr__ */
+ /* first find if this is a registered property */
+ const int ret = RNA_def_property_free_identifier(srna, attr_str);
+ if (ret == -1) {
+ PyErr_Format(
+ PyExc_TypeError, "struct_meta_idprop.detattr(): '%s' not a dynamic property", attr_str);
+ return -1;
+ }
+ }
+
+ /* fallback to standard py, delattr/setattr */
+ return PyType_Type.tp_setattro(cls, attr, value);
}
static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject *value)
{
- const char *name = _PyUnicode_AsString(pyname);
- PropertyRNA *prop = NULL;
+ const char *name = _PyUnicode_AsString(pyname);
+ PropertyRNA *prop = NULL;
- PYRNA_STRUCT_CHECK_INT(self);
+ PYRNA_STRUCT_CHECK_INT(self);
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
-
- if (name == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
- return -1;
- }
- else if (name[0] != '_' && (prop = RNA_struct_find_property(&self->ptr, name))) {
- if (!RNA_property_editable_flag(&self->ptr, prop)) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only",
- RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type));
- return -1;
- }
- }
- else if (self->ptr.type == &RNA_Context) {
- /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
- bContext *C = self->ptr.data;
- if (C == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context",
- name);
- return -1;
- }
- else {
- PointerRNA newptr;
- ListBase newlb;
- short newtype;
-
- int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
-
- if (done == 1) {
- PyErr_Format(PyExc_AttributeError,
- "bpy_struct: Context property \"%.200s\" is read-only",
- name);
- BLI_freelistN(&newlb);
- return -1;
- }
-
- BLI_freelistN(&newlb);
- }
- }
-
- /* pyrna_py_to_prop sets its own exceptions */
- if (prop) {
- if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
- return -1;
- }
- return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "bpy_struct: item.attr = val:");
- }
- else {
- return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
- }
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
+ return -1;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
+ if (name == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
+ return -1;
+ }
+ else if (name[0] != '_' && (prop = RNA_struct_find_property(&self->ptr, name))) {
+ if (!RNA_property_editable_flag(&self->ptr, prop)) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only",
+ RNA_property_identifier(prop),
+ RNA_struct_identifier(self->ptr.type));
+ return -1;
+ }
+ }
+ else if (self->ptr.type == &RNA_Context) {
+ /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
+ bContext *C = self->ptr.data;
+ if (C == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context",
+ name);
+ return -1;
+ }
+ else {
+ PointerRNA newptr;
+ ListBase newlb;
+ short newtype;
+
+ int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
+
+ if (done == 1) {
+ PyErr_Format(
+ PyExc_AttributeError, "bpy_struct: Context property \"%.200s\" is read-only", name);
+ BLI_freelistN(&newlb);
+ return -1;
+ }
+
+ BLI_freelistN(&newlb);
+ }
+ }
+
+ /* pyrna_py_to_prop sets its own exceptions */
+ if (prop) {
+ if (value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
+ return -1;
+ }
+ return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "bpy_struct: item.attr = val:");
+ }
+ else {
+ return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
+ }
}
static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
{
- PyObject *ret;
- PointerRNA r_ptr;
+ PyObject *ret;
+ PointerRNA r_ptr;
- /* Include this in case this instance is a subtype of a python class
- * In these instances we may want to return a function or variable provided by the subtype
- * */
- ret = PyList_New(0);
+ /* Include this in case this instance is a subtype of a python class
+ * In these instances we may want to return a function or variable provided by the subtype
+ * */
+ ret = PyList_New(0);
- if (!BPy_PropertyRNA_CheckExact(self)) {
- pyrna_dir_members_py(ret, (PyObject *)self);
- }
+ if (!BPy_PropertyRNA_CheckExact(self)) {
+ pyrna_dir_members_py(ret, (PyObject *)self);
+ }
- if (RNA_property_type(self->prop) == PROP_COLLECTION) {
- if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
- pyrna_dir_members_rna(ret, &r_ptr);
- }
- }
+ if (RNA_property_type(self->prop) == PROP_COLLECTION) {
+ if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
+ pyrna_dir_members_rna(ret, &r_ptr);
+ }
+ }
- return ret;
+ return ret;
}
-
static PyObject *pyrna_prop_array_getattro(BPy_PropertyRNA *self, PyObject *pyname)
{
- return PyObject_GenericGetAttr((PyObject *)self, pyname);
+ return PyObject_GenericGetAttr((PyObject *)self, pyname);
}
static PyObject *pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject *pyname)
{
- const char *name = _PyUnicode_AsString(pyname);
-
- if (name == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
- return NULL;
- }
- else if (name[0] != '_') {
- PyObject *ret;
- PropertyRNA *prop;
- FunctionRNA *func;
-
- PointerRNA r_ptr;
- if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
- if ((prop = RNA_struct_find_property(&r_ptr, name))) {
- ret = pyrna_prop_to_py(&r_ptr, prop);
-
- return ret;
- }
- else if ((func = RNA_struct_find_function(r_ptr.type, name))) {
- PyObject *self_collection = pyrna_struct_CreatePyObject(&r_ptr);
- ret = pyrna_func_to_py(&((BPy_DummyPointerRNA *)self_collection)->ptr, func);
- Py_DECREF(self_collection);
-
- return ret;
- }
- }
- }
+ const char *name = _PyUnicode_AsString(pyname);
+
+ if (name == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
+ return NULL;
+ }
+ else if (name[0] != '_') {
+ PyObject *ret;
+ PropertyRNA *prop;
+ FunctionRNA *func;
+
+ PointerRNA r_ptr;
+ if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
+ if ((prop = RNA_struct_find_property(&r_ptr, name))) {
+ ret = pyrna_prop_to_py(&r_ptr, prop);
+
+ return ret;
+ }
+ else if ((func = RNA_struct_find_function(r_ptr.type, name))) {
+ PyObject *self_collection = pyrna_struct_CreatePyObject(&r_ptr);
+ ret = pyrna_func_to_py(&((BPy_DummyPointerRNA *)self_collection)->ptr, func);
+ Py_DECREF(self_collection);
+
+ return ret;
+ }
+ }
+ }
#if 0
- return PyObject_GenericGetAttr((PyObject *)self, pyname);
+ return PyObject_GenericGetAttr((PyObject *)self, pyname);
#else
- {
- /* Could just do this except for 1 awkward case.
- * PyObject_GenericGetAttr((PyObject *)self, pyname);
- * so as to support 'bpy.data.library.load()'
- * note, this _only_ supports static methods */
-
- PyObject *ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
-
- if (ret == NULL && name[0] != '_') { /* avoid inheriting __call__ and similar */
- /* since this is least common case, handle it last */
- PointerRNA r_ptr;
- if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
- PyObject *cls;
-
- PyObject *error_type, *error_value, *error_traceback;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- PyErr_Clear();
-
- cls = pyrna_struct_Subtype(&r_ptr);
- ret = PyObject_GenericGetAttr(cls, pyname);
- Py_DECREF(cls);
-
- /* restore the original error */
- if (ret == NULL) {
- PyErr_Restore(error_type, error_value, error_traceback);
- }
- }
- }
-
- return ret;
- }
+ {
+ /* Could just do this except for 1 awkward case.
+ * PyObject_GenericGetAttr((PyObject *)self, pyname);
+ * so as to support 'bpy.data.library.load()'
+ * note, this _only_ supports static methods */
+
+ PyObject *ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
+
+ if (ret == NULL && name[0] != '_') { /* avoid inheriting __call__ and similar */
+ /* since this is least common case, handle it last */
+ PointerRNA r_ptr;
+ if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
+ PyObject *cls;
+
+ PyObject *error_type, *error_value, *error_traceback;
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ PyErr_Clear();
+
+ cls = pyrna_struct_Subtype(&r_ptr);
+ ret = PyObject_GenericGetAttr(cls, pyname);
+ Py_DECREF(cls);
+
+ /* restore the original error */
+ if (ret == NULL) {
+ PyErr_Restore(error_type, error_value, error_traceback);
+ }
+ }
+ }
+
+ return ret;
+ }
#endif
}
/* --------------- setattr------------------------------------------- */
static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
{
- const char *name = _PyUnicode_AsString(pyname);
- PropertyRNA *prop;
- PointerRNA r_ptr;
+ const char *name = _PyUnicode_AsString(pyname);
+ PropertyRNA *prop;
+ PointerRNA r_ptr;
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
- return -1;
- }
-#endif /* USE_PEDANTIC_WRITE */
-
- if (name == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
- return -1;
- }
- else if (value == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
- return -1;
- }
- else if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
- if ((prop = RNA_struct_find_property(&r_ptr, name))) {
- /* pyrna_py_to_prop sets its own exceptions */
- return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
- }
- }
-
- PyErr_Format(PyExc_AttributeError,
- "bpy_prop_collection: attribute \"%.200s\" not found",
- name);
- return -1;
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
+ return -1;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
+ if (name == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
+ return -1;
+ }
+ else if (value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
+ return -1;
+ }
+ else if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
+ if ((prop = RNA_struct_find_property(&r_ptr, name))) {
+ /* pyrna_py_to_prop sets its own exceptions */
+ return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
+ }
+ }
+
+ PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" not found", name);
+ return -1;
}
/* odd case, we need to be able return a python method from a tp_getset */
static PyObject *pyrna_prop_collection_idprop_add(BPy_PropertyRNA *self)
{
- PointerRNA r_ptr;
+ PointerRNA r_ptr;
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return NULL;
- }
-#endif /* USE_PEDANTIC_WRITE */
-
- RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
- if (!r_ptr.data) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.add(): not supported for this collection");
- return NULL;
- }
- else {
- return pyrna_struct_CreatePyObject(&r_ptr);
- }
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
+
+ RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
+ if (!r_ptr.data) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_prop_collection.add(): not supported for this collection");
+ return NULL;
+ }
+ else {
+ return pyrna_struct_CreatePyObject(&r_ptr);
+ }
}
static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyObject *value)
{
- int key = PyLong_AsLong(value);
+ int key = PyLong_AsLong(value);
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return NULL;
- }
-#endif /* USE_PEDANTIC_WRITE */
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
- if (key == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
- return NULL;
- }
+ if (key == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
+ return NULL;
+ }
- if (!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove() not supported for this collection");
- return NULL;
- }
+ if (!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_prop_collection.remove() not supported for this collection");
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *pyrna_prop_collection_idprop_clear(BPy_PropertyRNA *self)
{
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return NULL;
- }
-#endif /* USE_PEDANTIC_WRITE */
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
- RNA_property_collection_clear(&self->ptr, self->prop);
+ RNA_property_collection_clear(&self->ptr, self->prop);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObject *args)
{
- int key = 0, pos = 0;
+ int key = 0, pos = 0;
#ifdef USE_PEDANTIC_WRITE
- if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
- return NULL;
- }
-#endif /* USE_PEDANTIC_WRITE */
+ if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
+ return NULL;
+ }
+#endif /* USE_PEDANTIC_WRITE */
- if (!PyArg_ParseTuple(args, "ii", &key, &pos)) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ii", &key, &pos)) {
+ PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
+ return NULL;
+ }
- if (!RNA_property_collection_move(&self->ptr, self->prop, key, pos)) {
- PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move() not supported for this collection");
- return NULL;
- }
+ if (!RNA_property_collection_move(&self->ptr, self->prop, key, pos)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_prop_collection.move() not supported for this collection");
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
-
PyDoc_STRVAR(pyrna_struct_get_id_data_doc,
-"The :class:`bpy.types.ID` object this datablock is from or None, (not available for all data types)"
-);
+ "The :class:`bpy.types.ID` object this datablock is from or None, (not available for "
+ "all data types)");
static PyObject *pyrna_struct_get_id_data(BPy_DummyPointerRNA *self)
{
- /* used for struct and pointer since both have a ptr */
- if (self->ptr.id.data) {
- PointerRNA id_ptr;
- RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
- return pyrna_struct_CreatePyObject(&id_ptr);
- }
+ /* used for struct and pointer since both have a ptr */
+ if (self->ptr.id.data) {
+ PointerRNA id_ptr;
+ RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
+ return pyrna_struct_CreatePyObject(&id_ptr);
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyrna_struct_get_data_doc,
-"The data this property is using, *type* :class:`bpy.types.bpy_struct`"
-);
+ "The data this property is using, *type* :class:`bpy.types.bpy_struct`");
static PyObject *pyrna_struct_get_data(BPy_DummyPointerRNA *self)
{
- return pyrna_struct_CreatePyObject(&self->ptr);
+ return pyrna_struct_CreatePyObject(&self->ptr);
}
-PyDoc_STRVAR(pyrna_struct_get_rna_type_doc,
-"The property type for introspection"
-);
+PyDoc_STRVAR(pyrna_struct_get_rna_type_doc, "The property type for introspection");
static PyObject *pyrna_struct_get_rna_type(BPy_PropertyRNA *self)
{
- PointerRNA tptr;
- RNA_pointer_create(NULL, &RNA_Property, self->prop, &tptr);
- return pyrna_struct_Subtype(&tptr);
+ PointerRNA tptr;
+ RNA_pointer_create(NULL, &RNA_Property, self->prop, &tptr);
+ return pyrna_struct_Subtype(&tptr);
}
-
-
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef pyrna_prop_getseters[] = {
- {(char *)"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, (char *)pyrna_struct_get_id_data_doc, NULL},
- {(char *)"data", (getter)pyrna_struct_get_data, (setter)NULL, (char *)pyrna_struct_get_data_doc, NULL},
- {(char *)"rna_type", (getter)pyrna_struct_get_rna_type, (setter)NULL, (char *)pyrna_struct_get_rna_type_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"id_data",
+ (getter)pyrna_struct_get_id_data,
+ (setter)NULL,
+ (char *)pyrna_struct_get_id_data_doc,
+ NULL},
+ {(char *)"data",
+ (getter)pyrna_struct_get_data,
+ (setter)NULL,
+ (char *)pyrna_struct_get_data_doc,
+ NULL},
+ {(char *)"rna_type",
+ (getter)pyrna_struct_get_rna_type,
+ (setter)NULL,
+ (char *)pyrna_struct_get_rna_type_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyGetSetDef pyrna_struct_getseters[] = {
- {(char *)"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, (char *)pyrna_struct_get_id_data_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"id_data",
+ (getter)pyrna_struct_get_id_data,
+ (setter)NULL,
+ (char *)pyrna_struct_get_id_data_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
static PyObject *pyrna_func_doc_get(BPy_FunctionRNA *self, void *closure);
static PyGetSetDef pyrna_func_getseters[] = {
- {(char *)"__doc__", (getter)pyrna_func_doc_get, (setter)NULL, NULL, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"__doc__", (getter)pyrna_func_doc_get, (setter)NULL, NULL, NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
PyDoc_STRVAR(pyrna_prop_collection_keys_doc,
-".. method:: keys()\n"
-"\n"
-" Return the identifiers of collection members\n"
-" (matching pythons dict.keys() functionality).\n"
-"\n"
-" :return: the identifiers for each member of this collection.\n"
-" :rtype: list of strings\n"
-);
+ ".. method:: keys()\n"
+ "\n"
+ " Return the identifiers of collection members\n"
+ " (matching pythons dict.keys() functionality).\n"
+ "\n"
+ " :return: the identifiers for each member of this collection.\n"
+ " :rtype: list of strings\n");
static PyObject *pyrna_prop_collection_keys(BPy_PropertyRNA *self)
{
- PyObject *ret = PyList_New(0);
- char name[256], *nameptr;
- int namelen;
+ PyObject *ret = PyList_New(0);
+ char name[256], *nameptr;
+ int namelen;
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
- if (nameptr) {
- PyList_APPEND(ret, PyUnicode_FromStringAndSize(nameptr, namelen));
+ if (nameptr) {
+ PyList_APPEND(ret, PyUnicode_FromStringAndSize(nameptr, namelen));
- if (name != nameptr) {
- MEM_freeN(nameptr);
- }
- }
- }
- RNA_PROP_END;
+ if (name != nameptr) {
+ MEM_freeN(nameptr);
+ }
+ }
+ }
+ RNA_PROP_END;
- return ret;
+ return ret;
}
PyDoc_STRVAR(pyrna_prop_collection_items_doc,
-".. method:: items()\n"
-"\n"
-" Return the identifiers of collection members\n"
-" (matching pythons dict.items() functionality).\n"
-"\n"
-" :return: (key, value) pairs for each member of this collection.\n"
-" :rtype: list of tuples\n"
-);
+ ".. method:: items()\n"
+ "\n"
+ " Return the identifiers of collection members\n"
+ " (matching pythons dict.items() functionality).\n"
+ "\n"
+ " :return: (key, value) pairs for each member of this collection.\n"
+ " :rtype: list of tuples\n");
static PyObject *pyrna_prop_collection_items(BPy_PropertyRNA *self)
{
- PyObject *ret = PyList_New(0);
- PyObject *item;
- char name[256], *nameptr;
- int namelen;
- int i = 0;
-
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- if (itemptr.data) {
- /* add to python list */
- item = PyTuple_New(2);
- nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
- if (nameptr) {
- PyTuple_SET_ITEM(item, 0, PyUnicode_FromStringAndSize(nameptr, namelen));
- if (name != nameptr) {
- MEM_freeN(nameptr);
- }
- }
- else {
- /* a bit strange but better then returning an empty list */
- PyTuple_SET_ITEM(item, 0, PyLong_FromLong(i));
- }
- PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
-
- PyList_APPEND(ret, item);
-
- i++;
- }
- }
- RNA_PROP_END;
-
- return ret;
+ PyObject *ret = PyList_New(0);
+ PyObject *item;
+ char name[256], *nameptr;
+ int namelen;
+ int i = 0;
+
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ if (itemptr.data) {
+ /* add to python list */
+ item = PyTuple_New(2);
+ nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
+ if (nameptr) {
+ PyTuple_SET_ITEM(item, 0, PyUnicode_FromStringAndSize(nameptr, namelen));
+ if (name != nameptr) {
+ MEM_freeN(nameptr);
+ }
+ }
+ else {
+ /* a bit strange but better then returning an empty list */
+ PyTuple_SET_ITEM(item, 0, PyLong_FromLong(i));
+ }
+ PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
+
+ PyList_APPEND(ret, item);
+
+ i++;
+ }
+ }
+ RNA_PROP_END;
+
+ return ret;
}
PyDoc_STRVAR(pyrna_prop_collection_values_doc,
-".. method:: values()\n"
-"\n"
-" Return the values of collection\n"
-" (matching pythons dict.values() functionality).\n"
-"\n"
-" :return: the members of this collection.\n"
-" :rtype: list\n"
-);
+ ".. method:: values()\n"
+ "\n"
+ " Return the values of collection\n"
+ " (matching pythons dict.values() functionality).\n"
+ "\n"
+ " :return: the members of this collection.\n"
+ " :rtype: list\n");
static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self)
{
- /* re-use slice*/
- return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
+ /* re-use slice*/
+ return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
}
PyDoc_STRVAR(pyrna_struct_get_doc,
-".. method:: get(key, default=None)\n"
-"\n"
-" Returns the value of the custom property assigned to key or default\n"
-" when not found (matches pythons dictionary function of the same name).\n"
-"\n"
-" :arg key: The key associated with the custom property.\n"
-" :type key: string\n"
-" :arg default: Optional argument for the value to return if\n"
-" *key* is not found.\n"
-" :type default: Undefined\n"
-"\n"
-BPY_DOC_ID_PROP_TYPE_NOTE
-);
+ ".. method:: get(key, default=None)\n"
+ "\n"
+ " Returns the value of the custom property assigned to key or default\n"
+ " when not found (matches pythons dictionary function of the same name).\n"
+ "\n"
+ " :arg key: The key associated with the custom property.\n"
+ " :type key: string\n"
+ " :arg default: Optional argument for the value to return if\n"
+ " *key* is not found.\n"
+ " :type default: Undefined\n"
+ "\n" BPY_DOC_ID_PROP_TYPE_NOTE);
static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
{
- IDProperty *group, *idprop;
+ IDProperty *group, *idprop;
- const char *key;
- PyObject *def = Py_None;
+ const char *key;
+ PyObject *def = Py_None;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
+ return NULL;
+ }
- /* mostly copied from BPy_IDGroup_Map_GetItem */
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
- return NULL;
- }
+ /* mostly copied from BPy_IDGroup_Map_GetItem */
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
- if (group) {
- idprop = IDP_GetPropertyFromGroup(group, key);
+ group = RNA_struct_idprops(&self->ptr, 0);
+ if (group) {
+ idprop = IDP_GetPropertyFromGroup(group, key);
- if (idprop) {
- return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
- }
- }
+ if (idprop) {
+ return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
+ }
+ }
- return Py_INCREF_RET(def);
+ return Py_INCREF_RET(def);
}
PyDoc_STRVAR(pyrna_struct_pop_doc,
-".. method:: pop(key, default=None)\n"
-"\n"
-" Remove and return the value of the custom property assigned to key or default\n"
-" when not found (matches pythons dictionary function of the same name).\n"
-"\n"
-" :arg key: The key associated with the custom property.\n"
-" :type key: string\n"
-" :arg default: Optional argument for the value to return if\n"
-" *key* is not found.\n"
-" :type default: Undefined\n"
-"\n"
-BPY_DOC_ID_PROP_TYPE_NOTE
-);
+ ".. method:: pop(key, default=None)\n"
+ "\n"
+ " Remove and return the value of the custom property assigned to key or default\n"
+ " when not found (matches pythons dictionary function of the same name).\n"
+ "\n"
+ " :arg key: The key associated with the custom property.\n"
+ " :type key: string\n"
+ " :arg default: Optional argument for the value to return if\n"
+ " *key* is not found.\n"
+ " :type default: Undefined\n"
+ "\n" BPY_DOC_ID_PROP_TYPE_NOTE);
static PyObject *pyrna_struct_pop(BPy_StructRNA *self, PyObject *args)
{
- IDProperty *group, *idprop;
+ IDProperty *group, *idprop;
- const char *key;
- PyObject *def = NULL;
+ const char *key;
+ PyObject *def = NULL;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s|O:get", &key, &def)) {
+ return NULL;
+ }
- /* mostly copied from BPy_IDGroup_Map_GetItem */
- if (RNA_struct_idprops_check(self->ptr.type) == 0) {
- PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
- return NULL;
- }
+ /* mostly copied from BPy_IDGroup_Map_GetItem */
+ if (RNA_struct_idprops_check(self->ptr.type) == 0) {
+ PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
+ return NULL;
+ }
- group = RNA_struct_idprops(&self->ptr, 0);
- if (group) {
- idprop = IDP_GetPropertyFromGroup(group, key);
+ group = RNA_struct_idprops(&self->ptr, 0);
+ if (group) {
+ idprop = IDP_GetPropertyFromGroup(group, key);
- if (idprop) {
- PyObject *ret = BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
- IDP_RemoveFromGroup(group, idprop);
- return ret;
- }
- }
+ if (idprop) {
+ PyObject *ret = BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
+ IDP_RemoveFromGroup(group, idprop);
+ return ret;
+ }
+ }
- if (def == NULL) {
- PyErr_SetString(PyExc_KeyError, "key not found");
- return NULL;
- }
- return Py_INCREF_RET(def);
+ if (def == NULL) {
+ PyErr_SetString(PyExc_KeyError, "key not found");
+ return NULL;
+ }
+ return Py_INCREF_RET(def);
}
PyDoc_STRVAR(pyrna_struct_as_pointer_doc,
-".. method:: as_pointer()\n"
-"\n"
-" Returns the memory address which holds a pointer to blenders internal data\n"
-"\n"
-" :return: int (memory address).\n"
-" :rtype: int\n"
-"\n"
-" .. note:: This is intended only for advanced script writers who need to\n"
-" pass blender data to their own C/Python modules.\n"
-);
+ ".. method:: as_pointer()\n"
+ "\n"
+ " Returns the memory address which holds a pointer to blenders internal data\n"
+ "\n"
+ " :return: int (memory address).\n"
+ " :rtype: int\n"
+ "\n"
+ " .. note:: This is intended only for advanced script writers who need to\n"
+ " pass blender data to their own C/Python modules.\n");
static PyObject *pyrna_struct_as_pointer(BPy_StructRNA *self)
{
- return PyLong_FromVoidPtr(self->ptr.data);
+ return PyLong_FromVoidPtr(self->ptr.data);
}
PyDoc_STRVAR(pyrna_prop_collection_get_doc,
-".. method:: get(key, default=None)\n"
-"\n"
-" Returns the value of the item assigned to key or default when not found\n"
-" (matches pythons dictionary function of the same name).\n"
-"\n"
-" :arg key: The identifier for the collection member.\n"
-" :type key: string\n"
-" :arg default: Optional argument for the value to return if\n"
-" *key* is not found.\n"
-" :type default: Undefined\n"
-);
+ ".. method:: get(key, default=None)\n"
+ "\n"
+ " Returns the value of the item assigned to key or default when not found\n"
+ " (matches pythons dictionary function of the same name).\n"
+ "\n"
+ " :arg key: The identifier for the collection member.\n"
+ " :type key: string\n"
+ " :arg default: Optional argument for the value to return if\n"
+ " *key* is not found.\n"
+ " :type default: Undefined\n");
static PyObject *pyrna_prop_collection_get(BPy_PropertyRNA *self, PyObject *args)
{
- PointerRNA newptr;
+ PointerRNA newptr;
- PyObject *key_ob;
- PyObject *def = Py_None;
+ PyObject *key_ob;
+ PyObject *def = Py_None;
- PYRNA_PROP_CHECK_OBJ(self);
+ PYRNA_PROP_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "O|O:get", &key_ob, &def)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O|O:get", &key_ob, &def)) {
+ return NULL;
+ }
- if (PyUnicode_Check(key_ob)) {
- const char *key = _PyUnicode_AsString(key_ob);
+ if (PyUnicode_Check(key_ob)) {
+ const char *key = _PyUnicode_AsString(key_ob);
- if (RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr)) {
- return pyrna_struct_CreatePyObject(&newptr);
- }
- }
- else if (PyTuple_Check(key_ob)) {
- PyObject *ret = pyrna_prop_collection_subscript_str_lib_pair(self, key_ob,
- "bpy_prop_collection.get((id, lib))", false);
- if (ret) {
- return ret;
- }
- }
- else {
- PyErr_Format(PyExc_KeyError,
- "bpy_prop_collection.get(key, ...): key must be a string or tuple, not %.200s",
- Py_TYPE(key_ob)->tp_name);
- }
+ if (RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr)) {
+ return pyrna_struct_CreatePyObject(&newptr);
+ }
+ }
+ else if (PyTuple_Check(key_ob)) {
+ PyObject *ret = pyrna_prop_collection_subscript_str_lib_pair(
+ self, key_ob, "bpy_prop_collection.get((id, lib))", false);
+ if (ret) {
+ return ret;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_KeyError,
+ "bpy_prop_collection.get(key, ...): key must be a string or tuple, not %.200s",
+ Py_TYPE(key_ob)->tp_name);
+ }
- return Py_INCREF_RET(def);
+ return Py_INCREF_RET(def);
}
PyDoc_STRVAR(pyrna_prop_collection_find_doc,
-".. method:: find(key)\n"
-"\n"
-" Returns the index of a key in a collection or -1 when not found\n"
-" (matches pythons string find function of the same name).\n"
-"\n"
-" :arg key: The identifier for the collection member.\n"
-" :type key: string\n"
-" :return: index of the key.\n"
-" :rtype: int\n"
-);
+ ".. method:: find(key)\n"
+ "\n"
+ " Returns the index of a key in a collection or -1 when not found\n"
+ " (matches pythons string find function of the same name).\n"
+ "\n"
+ " :arg key: The identifier for the collection member.\n"
+ " :type key: string\n"
+ " :return: index of the key.\n"
+ " :rtype: int\n");
static PyObject *pyrna_prop_collection_find(BPy_PropertyRNA *self, PyObject *key_ob)
{
- Py_ssize_t key_len_ssize_t;
- const char *key = _PyUnicode_AsStringAndSize(key_ob, &key_len_ssize_t);
- const int key_len = (int)key_len_ssize_t; /* comare with same type */
-
- char name[256], *nameptr;
- int namelen;
- int i = 0;
- int index = -1;
-
- PYRNA_PROP_CHECK_OBJ(self);
-
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
-
- if (nameptr) {
- if ((key_len == namelen) && memcmp(nameptr, key, key_len) == 0) {
- index = i;
- break;
- }
-
- if (name != nameptr) {
- MEM_freeN(nameptr);
- }
- }
-
- i++;
- }
- RNA_PROP_END;
-
- return PyLong_FromLong(index);
-}
-
-static bool foreach_attr_type(
- BPy_PropertyRNA *self, const char *attr,
- /* values to assign */
- RawPropertyType *raw_type, int *attr_tot, bool *attr_signed)
-{
- PropertyRNA *prop;
- bool attr_ok = true;
- *raw_type = PROP_RAW_UNSET;
- *attr_tot = 0;
- *attr_signed = false;
-
- /* note: this is fail with zero length lists, so don't let this get caled in that case */
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- prop = RNA_struct_find_property(&itemptr, attr);
- if (prop) {
- *raw_type = RNA_property_raw_type(prop);
- *attr_tot = RNA_property_array_length(&itemptr, prop);
- *attr_signed = (RNA_property_subtype(prop) != PROP_UNSIGNED);
- }
- else {
- attr_ok = false;
- }
- break;
- }
- RNA_PROP_END;
-
- return attr_ok;
+ Py_ssize_t key_len_ssize_t;
+ const char *key = _PyUnicode_AsStringAndSize(key_ob, &key_len_ssize_t);
+ const int key_len = (int)key_len_ssize_t; /* comare with same type */
+
+ char name[256], *nameptr;
+ int namelen;
+ int i = 0;
+ int index = -1;
+
+ PYRNA_PROP_CHECK_OBJ(self);
+
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
+
+ if (nameptr) {
+ if ((key_len == namelen) && memcmp(nameptr, key, key_len) == 0) {
+ index = i;
+ break;
+ }
+
+ if (name != nameptr) {
+ MEM_freeN(nameptr);
+ }
+ }
+
+ i++;
+ }
+ RNA_PROP_END;
+
+ return PyLong_FromLong(index);
+}
+
+static bool foreach_attr_type(BPy_PropertyRNA *self,
+ const char *attr,
+ /* values to assign */
+ RawPropertyType *raw_type,
+ int *attr_tot,
+ bool *attr_signed)
+{
+ PropertyRNA *prop;
+ bool attr_ok = true;
+ *raw_type = PROP_RAW_UNSET;
+ *attr_tot = 0;
+ *attr_signed = false;
+
+ /* note: this is fail with zero length lists, so don't let this get caled in that case */
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ prop = RNA_struct_find_property(&itemptr, attr);
+ if (prop) {
+ *raw_type = RNA_property_raw_type(prop);
+ *attr_tot = RNA_property_array_length(&itemptr, prop);
+ *attr_signed = (RNA_property_subtype(prop) != PROP_UNSIGNED);
+ }
+ else {
+ attr_ok = false;
+ }
+ break;
+ }
+ RNA_PROP_END;
+
+ return attr_ok;
}
/* pyrna_prop_collection_foreach_get/set both use this */
-static int foreach_parse_args(
- BPy_PropertyRNA *self, PyObject *args,
-
- /* values to assign */
- const char **attr, PyObject **seq, int *tot, int *size,
- RawPropertyType *raw_type, int *attr_tot, bool *attr_signed)
+static int foreach_parse_args(BPy_PropertyRNA *self,
+ PyObject *args,
+
+ /* values to assign */
+ const char **attr,
+ PyObject **seq,
+ int *tot,
+ int *size,
+ RawPropertyType *raw_type,
+ int *attr_tot,
+ bool *attr_signed)
{
#if 0
- int array_tot;
- int target_tot;
+ int array_tot;
+ int target_tot;
#endif
- *size = *attr_tot = 0;
- *attr_signed = false;
- *raw_type = PROP_RAW_UNSET;
-
- if (!PyArg_ParseTuple(args, "sO:foreach_get/set", attr, seq)) {
- return -1;
- }
-
- if (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq)) {
- PyErr_Format(PyExc_TypeError,
- "foreach_get/set expected second argument to be a sequence or buffer, not a %.200s",
- Py_TYPE(*seq)->tp_name);
- return -1;
- }
-
- *tot = PySequence_Size(*seq); /* TODO - buffer may not be a sequence! array.array() is tho. */
-
- if (*tot > 0) {
- if (!foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed)) {
- PyErr_Format(PyExc_AttributeError,
- "foreach_get/set '%.200s.%200s[...]' elements have no attribute '%.200s'",
- RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), *attr);
- return -1;
- }
- *size = RNA_raw_type_sizeof(*raw_type);
-
-#if 0 /* works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks */
- if ((*attr_tot) < 1) {
- *attr_tot = 1;
- }
-
- if (RNA_property_type(self->prop) == PROP_COLLECTION) {
- array_tot = RNA_property_collection_length(&self->ptr, self->prop);
- }
- else {
- array_tot = RNA_property_array_length(&self->ptr, self->prop);
- }
-
-
- target_tot = array_tot * (*attr_tot);
-
- /* rna_access.c - rna_raw_access(...) uses this same method */
- if (target_tot != (*tot)) {
- PyErr_Format(PyExc_TypeError,
- "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d",
- *tot, target_tot);
- return -1;
- }
+ *size = *attr_tot = 0;
+ *attr_signed = false;
+ *raw_type = PROP_RAW_UNSET;
+
+ if (!PyArg_ParseTuple(args, "sO:foreach_get/set", attr, seq)) {
+ return -1;
+ }
+
+ if (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "foreach_get/set expected second argument to be a sequence or buffer, not a %.200s",
+ Py_TYPE(*seq)->tp_name);
+ return -1;
+ }
+
+ *tot = PySequence_Size(*seq); /* TODO - buffer may not be a sequence! array.array() is tho. */
+
+ if (*tot > 0) {
+ if (!foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed)) {
+ PyErr_Format(PyExc_AttributeError,
+ "foreach_get/set '%.200s.%200s[...]' elements have no attribute '%.200s'",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_property_identifier(self->prop),
+ *attr);
+ return -1;
+ }
+ *size = RNA_raw_type_sizeof(*raw_type);
+
+#if 0 /* works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks */
+ if ((*attr_tot) < 1) {
+ *attr_tot = 1;
+ }
+
+ if (RNA_property_type(self->prop) == PROP_COLLECTION) {
+ array_tot = RNA_property_collection_length(&self->ptr, self->prop);
+ }
+ else {
+ array_tot = RNA_property_array_length(&self->ptr, self->prop);
+ }
+
+
+ target_tot = array_tot * (*attr_tot);
+
+ /* rna_access.c - rna_raw_access(...) uses this same method */
+ if (target_tot != (*tot)) {
+ PyErr_Format(PyExc_TypeError,
+ "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d",
+ *tot, target_tot);
+ return -1;
+ }
#endif
- }
+ }
- /* check 'attr_tot' otherwise we don't know if any values were set
- * this isn't ideal because it means running on an empty list may fail silently when its not compatible. */
- if (*size == 0 && *attr_tot != 0) {
- PyErr_SetString(PyExc_AttributeError, "attribute does not support foreach method");
- return -1;
- }
- return 0;
+ /* check 'attr_tot' otherwise we don't know if any values were set
+ * this isn't ideal because it means running on an empty list may fail silently when its not compatible. */
+ if (*size == 0 && *attr_tot != 0) {
+ PyErr_SetString(PyExc_AttributeError, "attribute does not support foreach method");
+ return -1;
+ }
+ return 0;
}
static bool foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
{
- char f = format ? *format : 'B'; /* B is assumed when not set */
-
- switch (raw_type) {
- case PROP_RAW_CHAR:
- if (attr_signed) {
- return (f == 'b') ? 1 : 0;
- }
- else {
- return (f == 'B') ? 1 : 0;
- }
- case PROP_RAW_SHORT:
- if (attr_signed) {
- return (f == 'h') ? 1 : 0;
- }
- else {
- return (f == 'H') ? 1 : 0;
- }
- case PROP_RAW_INT:
- if (attr_signed) {
- return (f == 'i') ? 1 : 0;
- }
- else {
- return (f == 'I') ? 1 : 0;
- }
- case PROP_RAW_BOOLEAN:
- return (f == '?') ? 1 : 0;
- case PROP_RAW_FLOAT:
- return (f == 'f') ? 1 : 0;
- case PROP_RAW_DOUBLE:
- return (f == 'd') ? 1 : 0;
- case PROP_RAW_UNSET:
- return 0;
- }
-
- return 0;
+ char f = format ? *format : 'B'; /* B is assumed when not set */
+
+ switch (raw_type) {
+ case PROP_RAW_CHAR:
+ if (attr_signed) {
+ return (f == 'b') ? 1 : 0;
+ }
+ else {
+ return (f == 'B') ? 1 : 0;
+ }
+ case PROP_RAW_SHORT:
+ if (attr_signed) {
+ return (f == 'h') ? 1 : 0;
+ }
+ else {
+ return (f == 'H') ? 1 : 0;
+ }
+ case PROP_RAW_INT:
+ if (attr_signed) {
+ return (f == 'i') ? 1 : 0;
+ }
+ else {
+ return (f == 'I') ? 1 : 0;
+ }
+ case PROP_RAW_BOOLEAN:
+ return (f == '?') ? 1 : 0;
+ case PROP_RAW_FLOAT:
+ return (f == 'f') ? 1 : 0;
+ case PROP_RAW_DOUBLE:
+ return (f == 'd') ? 1 : 0;
+ case PROP_RAW_UNSET:
+ return 0;
+ }
+
+ return 0;
}
static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
{
- PyObject *item = NULL;
- int i = 0, ok = 0;
- bool buffer_is_compat;
- void *array = NULL;
-
- /* get/set both take the same args currently */
- const char *attr;
- PyObject *seq;
- int tot, size, attr_tot;
- bool attr_signed;
- RawPropertyType raw_type;
-
- if (foreach_parse_args(self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) == -1) {
- return NULL;
- }
-
- if (tot == 0) {
- Py_RETURN_NONE;
- }
-
-
-
- if (set) { /* get the array from python */
- buffer_is_compat = false;
- if (PyObject_CheckBuffer(seq)) {
- Py_buffer buf;
- PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
-
- /* check if the buffer matches */
-
- buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
-
- if (buffer_is_compat) {
- ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
- }
-
- PyBuffer_Release(&buf);
- }
-
- /* could not use the buffer, fallback to sequence */
- if (!buffer_is_compat) {
- array = PyMem_Malloc(size * tot);
-
- for ( ; i < tot; i++) {
- item = PySequence_GetItem(seq, i);
- switch (raw_type) {
- case PROP_RAW_CHAR:
- ((char *)array)[i] = (char)PyLong_AsLong(item);
- break;
- case PROP_RAW_SHORT:
- ((short *)array)[i] = (short)PyLong_AsLong(item);
- break;
- case PROP_RAW_INT:
- ((int *)array)[i] = (int)PyLong_AsLong(item);
- break;
- case PROP_RAW_BOOLEAN:
- ((bool *)array)[i] = (int)PyLong_AsLong(item) != 0;
- break;
- case PROP_RAW_FLOAT:
- ((float *)array)[i] = (float)PyFloat_AsDouble(item);
- break;
- case PROP_RAW_DOUBLE:
- ((double *)array)[i] = (double)PyFloat_AsDouble(item);
- break;
- case PROP_RAW_UNSET:
- /* should never happen */
- BLI_assert(!"Invalid array type - set");
- break;
- }
-
- Py_DECREF(item);
- }
-
- ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
- }
- }
- else {
- buffer_is_compat = false;
- if (PyObject_CheckBuffer(seq)) {
- Py_buffer buf;
- PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
-
- /* check if the buffer matches, TODO - signed/unsigned types */
-
- buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
-
- if (buffer_is_compat) {
- ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
- }
-
- PyBuffer_Release(&buf);
- }
-
- /* could not use the buffer, fallback to sequence */
- if (!buffer_is_compat) {
- array = PyMem_Malloc(size * tot);
-
- ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
-
- if (!ok) {
- /* skip the loop */
- i = tot;
- }
-
- for ( ; i < tot; i++) {
-
- switch (raw_type) {
- case PROP_RAW_CHAR:
- item = PyLong_FromLong((long) ((char *)array)[i]);
- break;
- case PROP_RAW_SHORT:
- item = PyLong_FromLong((long) ((short *)array)[i]);
- break;
- case PROP_RAW_INT:
- item = PyLong_FromLong((long) ((int *)array)[i]);
- break;
- case PROP_RAW_FLOAT:
- item = PyFloat_FromDouble((double) ((float *)array)[i]);
- break;
- case PROP_RAW_DOUBLE:
- item = PyFloat_FromDouble((double) ((double *)array)[i]);
- break;
- case PROP_RAW_BOOLEAN:
- item = PyBool_FromLong((long) ((bool *)array)[i]);
- break;
- default: /* PROP_RAW_UNSET */
- /* should never happen */
- BLI_assert(!"Invalid array type - get");
- item = Py_None;
- Py_INCREF(item);
- break;
- }
-
- PySequence_SetItem(seq, i, item);
- Py_DECREF(item);
- }
- }
- }
-
- if (array) {
- PyMem_Free(array);
- }
-
- if (PyErr_Occurred()) {
- /* Maybe we could make our own error */
- PyErr_Print();
- PyErr_SetString(PyExc_TypeError, "couldn't access the py sequence");
- return NULL;
- }
- if (!ok) {
- PyErr_SetString(PyExc_RuntimeError, "internal error setting the array");
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyObject *item = NULL;
+ int i = 0, ok = 0;
+ bool buffer_is_compat;
+ void *array = NULL;
+
+ /* get/set both take the same args currently */
+ const char *attr;
+ PyObject *seq;
+ int tot, size, attr_tot;
+ bool attr_signed;
+ RawPropertyType raw_type;
+
+ if (foreach_parse_args(
+ self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) == -1) {
+ return NULL;
+ }
+
+ if (tot == 0) {
+ Py_RETURN_NONE;
+ }
+
+ if (set) { /* get the array from python */
+ buffer_is_compat = false;
+ if (PyObject_CheckBuffer(seq)) {
+ Py_buffer buf;
+ PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
+
+ /* check if the buffer matches */
+
+ buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
+
+ if (buffer_is_compat) {
+ ok = RNA_property_collection_raw_set(
+ NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
+ }
+
+ PyBuffer_Release(&buf);
+ }
+
+ /* could not use the buffer, fallback to sequence */
+ if (!buffer_is_compat) {
+ array = PyMem_Malloc(size * tot);
+
+ for (; i < tot; i++) {
+ item = PySequence_GetItem(seq, i);
+ switch (raw_type) {
+ case PROP_RAW_CHAR:
+ ((char *)array)[i] = (char)PyLong_AsLong(item);
+ break;
+ case PROP_RAW_SHORT:
+ ((short *)array)[i] = (short)PyLong_AsLong(item);
+ break;
+ case PROP_RAW_INT:
+ ((int *)array)[i] = (int)PyLong_AsLong(item);
+ break;
+ case PROP_RAW_BOOLEAN:
+ ((bool *)array)[i] = (int)PyLong_AsLong(item) != 0;
+ break;
+ case PROP_RAW_FLOAT:
+ ((float *)array)[i] = (float)PyFloat_AsDouble(item);
+ break;
+ case PROP_RAW_DOUBLE:
+ ((double *)array)[i] = (double)PyFloat_AsDouble(item);
+ break;
+ case PROP_RAW_UNSET:
+ /* should never happen */
+ BLI_assert(!"Invalid array type - set");
+ break;
+ }
+
+ Py_DECREF(item);
+ }
+
+ ok = RNA_property_collection_raw_set(
+ NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
+ }
+ }
+ else {
+ buffer_is_compat = false;
+ if (PyObject_CheckBuffer(seq)) {
+ Py_buffer buf;
+ PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
+
+ /* check if the buffer matches, TODO - signed/unsigned types */
+
+ buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
+
+ if (buffer_is_compat) {
+ ok = RNA_property_collection_raw_get(
+ NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
+ }
+
+ PyBuffer_Release(&buf);
+ }
+
+ /* could not use the buffer, fallback to sequence */
+ if (!buffer_is_compat) {
+ array = PyMem_Malloc(size * tot);
+
+ ok = RNA_property_collection_raw_get(
+ NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
+
+ if (!ok) {
+ /* skip the loop */
+ i = tot;
+ }
+
+ for (; i < tot; i++) {
+
+ switch (raw_type) {
+ case PROP_RAW_CHAR:
+ item = PyLong_FromLong((long)((char *)array)[i]);
+ break;
+ case PROP_RAW_SHORT:
+ item = PyLong_FromLong((long)((short *)array)[i]);
+ break;
+ case PROP_RAW_INT:
+ item = PyLong_FromLong((long)((int *)array)[i]);
+ break;
+ case PROP_RAW_FLOAT:
+ item = PyFloat_FromDouble((double)((float *)array)[i]);
+ break;
+ case PROP_RAW_DOUBLE:
+ item = PyFloat_FromDouble((double)((double *)array)[i]);
+ break;
+ case PROP_RAW_BOOLEAN:
+ item = PyBool_FromLong((long)((bool *)array)[i]);
+ break;
+ default: /* PROP_RAW_UNSET */
+ /* should never happen */
+ BLI_assert(!"Invalid array type - get");
+ item = Py_None;
+ Py_INCREF(item);
+ break;
+ }
+
+ PySequence_SetItem(seq, i, item);
+ Py_DECREF(item);
+ }
+ }
+ }
+
+ if (array) {
+ PyMem_Free(array);
+ }
+
+ if (PyErr_Occurred()) {
+ /* Maybe we could make our own error */
+ PyErr_Print();
+ PyErr_SetString(PyExc_TypeError, "couldn't access the py sequence");
+ return NULL;
+ }
+ if (!ok) {
+ PyErr_SetString(PyExc_RuntimeError, "internal error setting the array");
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyrna_prop_collection_foreach_get_doc,
-".. method:: foreach_get(attr, seq)\n"
-"\n"
-" This is a function to give fast access to attributes within a collection.\n"
-);
+ ".. method:: foreach_get(attr, seq)\n"
+ "\n"
+ " This is a function to give fast access to attributes within a collection.\n");
static PyObject *pyrna_prop_collection_foreach_get(BPy_PropertyRNA *self, PyObject *args)
{
- PYRNA_PROP_CHECK_OBJ(self);
+ PYRNA_PROP_CHECK_OBJ(self);
- return foreach_getset(self, args, 0);
+ return foreach_getset(self, args, 0);
}
PyDoc_STRVAR(pyrna_prop_collection_foreach_set_doc,
-".. method:: foreach_set(attr, seq)\n"
-"\n"
-" This is a function to give fast access to attributes within a collection.\n"
-);
+ ".. method:: foreach_set(attr, seq)\n"
+ "\n"
+ " This is a function to give fast access to attributes within a collection.\n");
static PyObject *pyrna_prop_collection_foreach_set(BPy_PropertyRNA *self, PyObject *args)
{
- PYRNA_PROP_CHECK_OBJ(self);
+ PYRNA_PROP_CHECK_OBJ(self);
- return foreach_getset(self, args, 1);
+ return foreach_getset(self, args, 1);
}
/* A bit of a kludge, make a list out of a collection or array,
* then return the lists iter function, not especially fast but convenient for now */
static PyObject *pyrna_prop_array_iter(BPy_PropertyArrayRNA *self)
{
- /* Try get values from a collection */
- PyObject *ret;
- PyObject *iter = NULL;
- int len;
+ /* Try get values from a collection */
+ PyObject *ret;
+ PyObject *iter = NULL;
+ int len;
- PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
+ PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
- len = pyrna_prop_array_length(self);
- ret = pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
+ len = pyrna_prop_array_length(self);
+ ret = pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
- /* we know this is a list so no need to PyIter_Check
- * otherwise it could be NULL (unlikely) if conversion failed */
- if (ret) {
- iter = PyObject_GetIter(ret);
- Py_DECREF(ret);
- }
+ /* we know this is a list so no need to PyIter_Check
+ * otherwise it could be NULL (unlikely) if conversion failed */
+ if (ret) {
+ iter = PyObject_GetIter(ret);
+ Py_DECREF(ret);
+ }
- return iter;
+ return iter;
}
static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self);
@@ -5331,348 +5387,400 @@ static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self);
#ifndef USE_PYRNA_ITER
static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self)
{
- /* Try get values from a collection */
- PyObject *ret;
- PyObject *iter = NULL;
- ret = pyrna_prop_collection_values(self);
+ /* Try get values from a collection */
+ PyObject *ret;
+ PyObject *iter = NULL;
+ ret = pyrna_prop_collection_values(self);
- /* we know this is a list so no need to PyIter_Check
- * otherwise it could be NULL (unlikely) if conversion failed */
- if (ret) {
- iter = PyObject_GetIter(ret);
- Py_DECREF(ret);
- }
+ /* we know this is a list so no need to PyIter_Check
+ * otherwise it could be NULL (unlikely) if conversion failed */
+ if (ret) {
+ iter = PyObject_GetIter(ret);
+ Py_DECREF(ret);
+ }
- return iter;
+ return iter;
}
#endif /* # !USE_PYRNA_ITER */
static struct PyMethodDef pyrna_struct_methods[] = {
- /* only for PointerRNA's with ID'props */
- {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, pyrna_struct_keys_doc},
- {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, pyrna_struct_values_doc},
- {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, pyrna_struct_items_doc},
-
- {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, pyrna_struct_get_doc},
- {"pop", (PyCFunction)pyrna_struct_pop, METH_VARARGS, pyrna_struct_pop_doc},
-
- {"as_pointer", (PyCFunction)pyrna_struct_as_pointer, METH_NOARGS, pyrna_struct_as_pointer_doc},
-
- /* bpy_rna_anim.c */
- {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS | METH_KEYWORDS, pyrna_struct_keyframe_insert_doc},
- {"keyframe_delete", (PyCFunction)pyrna_struct_keyframe_delete, METH_VARARGS | METH_KEYWORDS, pyrna_struct_keyframe_delete_doc},
- {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, pyrna_struct_driver_add_doc},
- {"driver_remove", (PyCFunction)pyrna_struct_driver_remove, METH_VARARGS, pyrna_struct_driver_remove_doc},
-
- {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, pyrna_struct_is_property_set_doc},
- {"property_unset", (PyCFunction)pyrna_struct_property_unset, METH_VARARGS, pyrna_struct_property_unset_doc},
- {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, pyrna_struct_is_property_hidden_doc},
- {"is_property_readonly", (PyCFunction)pyrna_struct_is_property_readonly, METH_VARARGS, pyrna_struct_is_property_readonly_doc},
- {"is_property_overridable_static", (PyCFunction)pyrna_struct_is_property_overridable_static, METH_VARARGS, pyrna_struct_is_property_overridable_static_doc},
- {"property_overridable_static_set", (PyCFunction)pyrna_struct_property_overridable_static_set, METH_VARARGS, pyrna_struct_property_overridable_static_set_doc},
- {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_VARARGS, pyrna_struct_path_resolve_doc},
- {"path_from_id", (PyCFunction)pyrna_struct_path_from_id, METH_VARARGS, pyrna_struct_path_from_id_doc},
- {"type_recast", (PyCFunction)pyrna_struct_type_recast, METH_NOARGS, pyrna_struct_type_recast_doc},
- {"bl_rna_get_subclass_py", (PyCFunction) pyrna_struct_bl_rna_get_subclass_py, METH_VARARGS | METH_CLASS, pyrna_struct_bl_rna_get_subclass_py_doc},
- {"bl_rna_get_subclass", (PyCFunction) pyrna_struct_bl_rna_get_subclass, METH_VARARGS | METH_CLASS, pyrna_struct_bl_rna_get_subclass_doc},
- {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
-
- /* experimental */
- /* unused for now */
+ /* only for PointerRNA's with ID'props */
+ {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, pyrna_struct_keys_doc},
+ {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, pyrna_struct_values_doc},
+ {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, pyrna_struct_items_doc},
+
+ {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, pyrna_struct_get_doc},
+ {"pop", (PyCFunction)pyrna_struct_pop, METH_VARARGS, pyrna_struct_pop_doc},
+
+ {"as_pointer", (PyCFunction)pyrna_struct_as_pointer, METH_NOARGS, pyrna_struct_as_pointer_doc},
+
+ /* bpy_rna_anim.c */
+ {"keyframe_insert",
+ (PyCFunction)pyrna_struct_keyframe_insert,
+ METH_VARARGS | METH_KEYWORDS,
+ pyrna_struct_keyframe_insert_doc},
+ {"keyframe_delete",
+ (PyCFunction)pyrna_struct_keyframe_delete,
+ METH_VARARGS | METH_KEYWORDS,
+ pyrna_struct_keyframe_delete_doc},
+ {"driver_add",
+ (PyCFunction)pyrna_struct_driver_add,
+ METH_VARARGS,
+ pyrna_struct_driver_add_doc},
+ {"driver_remove",
+ (PyCFunction)pyrna_struct_driver_remove,
+ METH_VARARGS,
+ pyrna_struct_driver_remove_doc},
+
+ {"is_property_set",
+ (PyCFunction)pyrna_struct_is_property_set,
+ METH_VARARGS,
+ pyrna_struct_is_property_set_doc},
+ {"property_unset",
+ (PyCFunction)pyrna_struct_property_unset,
+ METH_VARARGS,
+ pyrna_struct_property_unset_doc},
+ {"is_property_hidden",
+ (PyCFunction)pyrna_struct_is_property_hidden,
+ METH_VARARGS,
+ pyrna_struct_is_property_hidden_doc},
+ {"is_property_readonly",
+ (PyCFunction)pyrna_struct_is_property_readonly,
+ METH_VARARGS,
+ pyrna_struct_is_property_readonly_doc},
+ {"is_property_overridable_static",
+ (PyCFunction)pyrna_struct_is_property_overridable_static,
+ METH_VARARGS,
+ pyrna_struct_is_property_overridable_static_doc},
+ {"property_overridable_static_set",
+ (PyCFunction)pyrna_struct_property_overridable_static_set,
+ METH_VARARGS,
+ pyrna_struct_property_overridable_static_set_doc},
+ {"path_resolve",
+ (PyCFunction)pyrna_struct_path_resolve,
+ METH_VARARGS,
+ pyrna_struct_path_resolve_doc},
+ {"path_from_id",
+ (PyCFunction)pyrna_struct_path_from_id,
+ METH_VARARGS,
+ pyrna_struct_path_from_id_doc},
+ {"type_recast",
+ (PyCFunction)pyrna_struct_type_recast,
+ METH_NOARGS,
+ pyrna_struct_type_recast_doc},
+ {"bl_rna_get_subclass_py",
+ (PyCFunction)pyrna_struct_bl_rna_get_subclass_py,
+ METH_VARARGS | METH_CLASS,
+ pyrna_struct_bl_rna_get_subclass_py_doc},
+ {"bl_rna_get_subclass",
+ (PyCFunction)pyrna_struct_bl_rna_get_subclass,
+ METH_VARARGS | METH_CLASS,
+ pyrna_struct_bl_rna_get_subclass_doc},
+ {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
+
+/* experimental */
+/* unused for now */
#if 0
- {"callback_add", (PyCFunction)pyrna_callback_add, METH_VARARGS, NULL},
- {"callback_remove", (PyCFunction)pyrna_callback_remove, METH_VARARGS, NULL},
+ {"callback_add", (PyCFunction)pyrna_callback_add, METH_VARARGS, NULL},
+ {"callback_remove", (PyCFunction)pyrna_callback_remove, METH_VARARGS, NULL},
- {"callback_add", (PyCFunction)pyrna_callback_classmethod_add, METH_VARARGS | METH_CLASS, NULL},
- {"callback_remove", (PyCFunction)pyrna_callback_classmethod_remove, METH_VARARGS | METH_CLASS, NULL},
+ {"callback_add", (PyCFunction)pyrna_callback_classmethod_add, METH_VARARGS | METH_CLASS, NULL},
+ {"callback_remove", (PyCFunction)pyrna_callback_classmethod_remove, METH_VARARGS | METH_CLASS, NULL},
#endif
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef pyrna_prop_methods[] = {
- {"path_from_id", (PyCFunction)pyrna_prop_path_from_id, METH_NOARGS, pyrna_prop_path_from_id_doc},
- {"as_bytes", (PyCFunction)pyrna_prop_as_bytes, METH_NOARGS, pyrna_prop_as_bytes_doc},
- {"update", (PyCFunction)pyrna_prop_update, METH_NOARGS, pyrna_prop_update_doc},
- {"__dir__", (PyCFunction)pyrna_prop_dir, METH_NOARGS, NULL},
- {NULL, NULL, 0, NULL},
+ {"path_from_id",
+ (PyCFunction)pyrna_prop_path_from_id,
+ METH_NOARGS,
+ pyrna_prop_path_from_id_doc},
+ {"as_bytes", (PyCFunction)pyrna_prop_as_bytes, METH_NOARGS, pyrna_prop_as_bytes_doc},
+ {"update", (PyCFunction)pyrna_prop_update, METH_NOARGS, pyrna_prop_update_doc},
+ {"__dir__", (PyCFunction)pyrna_prop_dir, METH_NOARGS, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef pyrna_prop_array_methods[] = {
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef pyrna_prop_collection_methods[] = {
- {"foreach_get", (PyCFunction)pyrna_prop_collection_foreach_get, METH_VARARGS, pyrna_prop_collection_foreach_get_doc},
- {"foreach_set", (PyCFunction)pyrna_prop_collection_foreach_set, METH_VARARGS, pyrna_prop_collection_foreach_set_doc},
-
- {"keys", (PyCFunction)pyrna_prop_collection_keys, METH_NOARGS, pyrna_prop_collection_keys_doc},
- {"items", (PyCFunction)pyrna_prop_collection_items, METH_NOARGS, pyrna_prop_collection_items_doc},
- {"values", (PyCFunction)pyrna_prop_collection_values, METH_NOARGS, pyrna_prop_collection_values_doc},
-
- {"get", (PyCFunction)pyrna_prop_collection_get, METH_VARARGS, pyrna_prop_collection_get_doc},
- {"find", (PyCFunction)pyrna_prop_collection_find, METH_O, pyrna_prop_collection_find_doc},
- {NULL, NULL, 0, NULL},
+ {"foreach_get",
+ (PyCFunction)pyrna_prop_collection_foreach_get,
+ METH_VARARGS,
+ pyrna_prop_collection_foreach_get_doc},
+ {"foreach_set",
+ (PyCFunction)pyrna_prop_collection_foreach_set,
+ METH_VARARGS,
+ pyrna_prop_collection_foreach_set_doc},
+
+ {"keys", (PyCFunction)pyrna_prop_collection_keys, METH_NOARGS, pyrna_prop_collection_keys_doc},
+ {"items",
+ (PyCFunction)pyrna_prop_collection_items,
+ METH_NOARGS,
+ pyrna_prop_collection_items_doc},
+ {"values",
+ (PyCFunction)pyrna_prop_collection_values,
+ METH_NOARGS,
+ pyrna_prop_collection_values_doc},
+
+ {"get", (PyCFunction)pyrna_prop_collection_get, METH_VARARGS, pyrna_prop_collection_get_doc},
+ {"find", (PyCFunction)pyrna_prop_collection_find, METH_O, pyrna_prop_collection_find_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyMethodDef pyrna_prop_collection_idprop_methods[] = {
- {"add", (PyCFunction)pyrna_prop_collection_idprop_add, METH_NOARGS, NULL},
- {"remove", (PyCFunction)pyrna_prop_collection_idprop_remove, METH_O, NULL},
- {"clear", (PyCFunction)pyrna_prop_collection_idprop_clear, METH_NOARGS, NULL},
- {"move", (PyCFunction)pyrna_prop_collection_idprop_move, METH_VARARGS, NULL},
- {NULL, NULL, 0, NULL},
+ {"add", (PyCFunction)pyrna_prop_collection_idprop_add, METH_NOARGS, NULL},
+ {"remove", (PyCFunction)pyrna_prop_collection_idprop_remove, METH_O, NULL},
+ {"clear", (PyCFunction)pyrna_prop_collection_idprop_clear, METH_NOARGS, NULL},
+ {"move", (PyCFunction)pyrna_prop_collection_idprop_move, METH_VARARGS, NULL},
+ {NULL, NULL, 0, NULL},
};
/* only needed for subtyping, so a new class gets a valid BPy_StructRNA
* todo - also accept useful args */
static PyObject *pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *UNUSED(kwds))
{
- if (PyTuple_GET_SIZE(args) == 1) {
- BPy_StructRNA *base = (BPy_StructRNA *)PyTuple_GET_ITEM(args, 0);
- if (Py_TYPE(base) == type) {
- Py_INCREF(base);
- return (PyObject *)base;
- }
- else if (PyType_IsSubtype(Py_TYPE(base), &pyrna_struct_Type)) {
- /* this almost never runs, only when using user defined subclasses of built-in object.
- * this isn't common since its NOT related to registerable subclasses. eg:
- *
- * >>> class MyObSubclass(bpy.types.Object):
- * ... def test_func(self):
- * ... print(100)
- * ...
- * >>> myob = MyObSubclass(bpy.context.object)
- * >>> myob.test_func()
- * 100
- *
- * Keep this since it could be useful.
- */
- BPy_StructRNA *ret;
- if ((ret = (BPy_StructRNA *)type->tp_alloc(type, 0))) {
- ret->ptr = base->ptr;
- }
- /* pass on exception & NULL if tp_alloc fails */
- return (PyObject *)ret;
- }
-
- /* error, invalid type given */
- PyErr_Format(PyExc_TypeError,
- "bpy_struct.__new__(type): type '%.200s' is not a subtype of bpy_struct",
- type->tp_name);
- return NULL;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "bpy_struct.__new__(type): expected a single argument");
- return NULL;
- }
+ if (PyTuple_GET_SIZE(args) == 1) {
+ BPy_StructRNA *base = (BPy_StructRNA *)PyTuple_GET_ITEM(args, 0);
+ if (Py_TYPE(base) == type) {
+ Py_INCREF(base);
+ return (PyObject *)base;
+ }
+ else if (PyType_IsSubtype(Py_TYPE(base), &pyrna_struct_Type)) {
+ /* this almost never runs, only when using user defined subclasses of built-in object.
+ * this isn't common since its NOT related to registerable subclasses. eg:
+ *
+ * >>> class MyObSubclass(bpy.types.Object):
+ * ... def test_func(self):
+ * ... print(100)
+ * ...
+ * >>> myob = MyObSubclass(bpy.context.object)
+ * >>> myob.test_func()
+ * 100
+ *
+ * Keep this since it could be useful.
+ */
+ BPy_StructRNA *ret;
+ if ((ret = (BPy_StructRNA *)type->tp_alloc(type, 0))) {
+ ret->ptr = base->ptr;
+ }
+ /* pass on exception & NULL if tp_alloc fails */
+ return (PyObject *)ret;
+ }
+
+ /* error, invalid type given */
+ PyErr_Format(PyExc_TypeError,
+ "bpy_struct.__new__(type): type '%.200s' is not a subtype of bpy_struct",
+ type->tp_name);
+ return NULL;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "bpy_struct.__new__(type): expected a single argument");
+ return NULL;
+ }
}
/* only needed for subtyping, so a new class gets a valid BPy_StructRNA
* todo - also accept useful args */
static PyObject *pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *UNUSED(kwds))
{
- BPy_PropertyRNA *base;
-
- if (!PyArg_ParseTuple(args, "O!:bpy_prop.__new__", &pyrna_prop_Type, &base)) {
- return NULL;
- }
-
- if (type == Py_TYPE(base)) {
- return Py_INCREF_RET((PyObject *)base);
- }
- else if (PyType_IsSubtype(type, &pyrna_prop_Type)) {
- BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
- ret->ptr = base->ptr;
- ret->prop = base->prop;
- return (PyObject *)ret;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "bpy_prop.__new__(type): type '%.200s' is not a subtype of bpy_prop",
- type->tp_name);
- return NULL;
- }
+ BPy_PropertyRNA *base;
+
+ if (!PyArg_ParseTuple(args, "O!:bpy_prop.__new__", &pyrna_prop_Type, &base)) {
+ return NULL;
+ }
+
+ if (type == Py_TYPE(base)) {
+ return Py_INCREF_RET((PyObject *)base);
+ }
+ else if (PyType_IsSubtype(type, &pyrna_prop_Type)) {
+ BPy_PropertyRNA *ret = (BPy_PropertyRNA *)type->tp_alloc(type, 0);
+ ret->ptr = base->ptr;
+ ret->prop = base->prop;
+ return (PyObject *)ret;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "bpy_prop.__new__(type): type '%.200s' is not a subtype of bpy_prop",
+ type->tp_name);
+ return NULL;
+ }
}
static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
{
- PyObject *ret;
- const int type = RNA_property_type(prop);
- const int flag = RNA_property_flag(prop);
- const int flag_parameter = RNA_parameter_flag(prop);
-
- if (RNA_property_array_check(prop)) {
- int a, len;
-
- if (flag & PROP_DYNAMIC) {
- ParameterDynAlloc *data_alloc = data;
- len = data_alloc->array_tot;
- data = data_alloc->array;
- }
- else {
- len = RNA_property_array_length(ptr, prop);
- }
-
- /* resolve the array from a new pytype */
-
- /* kazanbas: TODO make multidim sequences here */
-
- switch (type) {
- case PROP_BOOLEAN:
- ret = PyTuple_New(len);
- for (a = 0; a < len; a++) {
- PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((bool *)data)[a]));
- }
- break;
- case PROP_INT:
- ret = PyTuple_New(len);
- for (a = 0; a < len; a++) {
- PyTuple_SET_ITEM(ret, a, PyLong_FromLong(((int *)data)[a]));
- }
- break;
- case PROP_FLOAT:
- switch (RNA_property_subtype(prop)) {
+ PyObject *ret;
+ const int type = RNA_property_type(prop);
+ const int flag = RNA_property_flag(prop);
+ const int flag_parameter = RNA_parameter_flag(prop);
+
+ if (RNA_property_array_check(prop)) {
+ int a, len;
+
+ if (flag & PROP_DYNAMIC) {
+ ParameterDynAlloc *data_alloc = data;
+ len = data_alloc->array_tot;
+ data = data_alloc->array;
+ }
+ else {
+ len = RNA_property_array_length(ptr, prop);
+ }
+
+ /* resolve the array from a new pytype */
+
+ /* kazanbas: TODO make multidim sequences here */
+
+ switch (type) {
+ case PROP_BOOLEAN:
+ ret = PyTuple_New(len);
+ for (a = 0; a < len; a++) {
+ PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((bool *)data)[a]));
+ }
+ break;
+ case PROP_INT:
+ ret = PyTuple_New(len);
+ for (a = 0; a < len; a++) {
+ PyTuple_SET_ITEM(ret, a, PyLong_FromLong(((int *)data)[a]));
+ }
+ break;
+ case PROP_FLOAT:
+ switch (RNA_property_subtype(prop)) {
#ifdef USE_MATHUTILS
- case PROP_ALL_VECTOR_SUBTYPES:
- ret = Vector_CreatePyObject(data, len, NULL);
- break;
- case PROP_MATRIX:
- if (len == 16) {
- ret = Matrix_CreatePyObject(data, 4, 4, NULL);
- break;
- }
- else if (len == 9) {
- ret = Matrix_CreatePyObject(data, 3, 3, NULL);
- break;
- }
- ATTR_FALLTHROUGH;
+ case PROP_ALL_VECTOR_SUBTYPES:
+ ret = Vector_CreatePyObject(data, len, NULL);
+ break;
+ case PROP_MATRIX:
+ if (len == 16) {
+ ret = Matrix_CreatePyObject(data, 4, 4, NULL);
+ break;
+ }
+ else if (len == 9) {
+ ret = Matrix_CreatePyObject(data, 3, 3, NULL);
+ break;
+ }
+ ATTR_FALLTHROUGH;
#endif
- default:
- ret = PyTuple_New(len);
- for (a = 0; a < len; a++) {
- PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble(((float *)data)[a]));
- }
- break;
- }
- break;
- default:
- PyErr_Format(PyExc_TypeError,
- "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)",
- type);
- ret = NULL;
- break;
- }
- }
- else {
- /* see if we can coerce into a python type - PropertyType */
- switch (type) {
- case PROP_BOOLEAN:
- ret = PyBool_FromLong(*(bool *)data);
- break;
- case PROP_INT:
- ret = PyLong_FromLong(*(int *)data);
- break;
- case PROP_FLOAT:
- ret = PyFloat_FromDouble(*(float *)data);
- break;
- case PROP_STRING:
- {
- const char *data_ch;
- PyObject *value_coerce = NULL;
- const int subtype = RNA_property_subtype(prop);
-
- if (flag & PROP_THICK_WRAP) {
- data_ch = (char *)data;
- }
- else {
- data_ch = *(char **)data;
- }
+ default:
+ ret = PyTuple_New(len);
+ for (a = 0; a < len; a++) {
+ PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble(((float *)data)[a]));
+ }
+ break;
+ }
+ break;
+ default:
+ PyErr_Format(
+ PyExc_TypeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
+ ret = NULL;
+ break;
+ }
+ }
+ else {
+ /* see if we can coerce into a python type - PropertyType */
+ switch (type) {
+ case PROP_BOOLEAN:
+ ret = PyBool_FromLong(*(bool *)data);
+ break;
+ case PROP_INT:
+ ret = PyLong_FromLong(*(int *)data);
+ break;
+ case PROP_FLOAT:
+ ret = PyFloat_FromDouble(*(float *)data);
+ break;
+ case PROP_STRING: {
+ const char *data_ch;
+ PyObject *value_coerce = NULL;
+ const int subtype = RNA_property_subtype(prop);
+
+ if (flag & PROP_THICK_WRAP) {
+ data_ch = (char *)data;
+ }
+ else {
+ data_ch = *(char **)data;
+ }
#ifdef USE_STRING_COERCE
- if (subtype == PROP_BYTESTRING) {
- ret = PyBytes_FromString(data_ch);
- }
- else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
- ret = PyC_UnicodeFromByte(data_ch);
- }
- else {
- ret = PyUnicode_FromString(data_ch);
- }
+ if (subtype == PROP_BYTESTRING) {
+ ret = PyBytes_FromString(data_ch);
+ }
+ else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
+ ret = PyC_UnicodeFromByte(data_ch);
+ }
+ else {
+ ret = PyUnicode_FromString(data_ch);
+ }
#else
- if (subtype == PROP_BYTESTRING) {
- ret = PyBytes_FromString(buf);
- }
- else {
- ret = PyUnicode_FromString(data_ch);
- }
+ if (subtype == PROP_BYTESTRING) {
+ ret = PyBytes_FromString(buf);
+ }
+ else {
+ ret = PyUnicode_FromString(data_ch);
+ }
#endif
#ifdef USE_STRING_COERCE
- Py_XDECREF(value_coerce);
+ Py_XDECREF(value_coerce);
#endif
- break;
- }
- case PROP_ENUM:
- {
- ret = pyrna_enum_to_py(ptr, prop, *(int *)data);
- break;
- }
- case PROP_POINTER:
- {
- PointerRNA newptr;
- StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
-
- if (flag_parameter & PARM_RNAPTR) {
- /* in this case we get the full ptr */
- newptr = *(PointerRNA *)data;
- }
- else {
- if (RNA_struct_is_ID(ptype)) {
- RNA_id_pointer_create(*(void **)data, &newptr);
- }
- else {
- /* note: this is taken from the function's ID pointer
- * and will break if a function returns a pointer from
- * another ID block, watch this! - it should at least be
- * easy to debug since they are all ID's */
- RNA_pointer_create(ptr->id.data, ptype, *(void **)data, &newptr);
- }
- }
-
- if (newptr.data) {
- ret = pyrna_struct_CreatePyObject(&newptr);
- }
- else {
- ret = Py_None;
- Py_INCREF(ret);
- }
- break;
- }
- case PROP_COLLECTION:
- {
- CollectionListBase *lb = (CollectionListBase *)data;
- CollectionPointerLink *link;
-
- ret = PyList_New(0);
-
- for (link = lb->first; link; link = link->next) {
- PyList_APPEND(ret, pyrna_struct_CreatePyObject(&link->ptr));
- }
-
- break;
- }
- default:
- PyErr_Format(PyExc_TypeError,
- "RNA Error: unknown type \"%d\" (pyrna_param_to_py)",
- type);
- ret = NULL;
- break;
- }
- }
-
- return ret;
+ break;
+ }
+ case PROP_ENUM: {
+ ret = pyrna_enum_to_py(ptr, prop, *(int *)data);
+ break;
+ }
+ case PROP_POINTER: {
+ PointerRNA newptr;
+ StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
+
+ if (flag_parameter & PARM_RNAPTR) {
+ /* in this case we get the full ptr */
+ newptr = *(PointerRNA *)data;
+ }
+ else {
+ if (RNA_struct_is_ID(ptype)) {
+ RNA_id_pointer_create(*(void **)data, &newptr);
+ }
+ else {
+ /* note: this is taken from the function's ID pointer
+ * and will break if a function returns a pointer from
+ * another ID block, watch this! - it should at least be
+ * easy to debug since they are all ID's */
+ RNA_pointer_create(ptr->id.data, ptype, *(void **)data, &newptr);
+ }
+ }
+
+ if (newptr.data) {
+ ret = pyrna_struct_CreatePyObject(&newptr);
+ }
+ else {
+ ret = Py_None;
+ Py_INCREF(ret);
+ }
+ break;
+ }
+ case PROP_COLLECTION: {
+ CollectionListBase *lb = (CollectionListBase *)data;
+ CollectionPointerLink *link;
+
+ ret = PyList_New(0);
+
+ for (link = lb->first; link; link = link->next) {
+ PyList_APPEND(ret, pyrna_struct_CreatePyObject(&link->ptr));
+ }
+
+ break;
+ }
+ default:
+ PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
+ ret = NULL;
+ break;
+ }
+ }
+
+ return ret;
}
/* Use to replace PyDict_GetItemString() when the overhead of converting a
@@ -5680,954 +5788,963 @@ static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *dat
* works on small dict's such as keyword args. */
static PyObject *small_dict_get_item_string(PyObject *dict, const char *key_lookup)
{
- PyObject *key = NULL;
- Py_ssize_t pos = 0;
- PyObject *value = NULL;
+ PyObject *key = NULL;
+ Py_ssize_t pos = 0;
+ PyObject *value = NULL;
- while (PyDict_Next(dict, &pos, &key, &value)) {
- if (PyUnicode_Check(key)) {
- if (STREQ(key_lookup, _PyUnicode_AsString(key))) {
- return value;
- }
- }
- }
+ while (PyDict_Next(dict, &pos, &key, &value)) {
+ if (PyUnicode_Check(key)) {
+ if (STREQ(key_lookup, _PyUnicode_AsString(key))) {
+ return value;
+ }
+ }
+ }
- return NULL;
+ return NULL;
}
static PyObject *pyrna_func_call(BPy_FunctionRNA *self, PyObject *args, PyObject *kw)
{
- /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
- PointerRNA *self_ptr = &self->ptr;
- FunctionRNA *self_func = self->func;
+ /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
+ PointerRNA *self_ptr = &self->ptr;
+ FunctionRNA *self_func = self->func;
- PointerRNA funcptr;
- ParameterList parms;
- ParameterIterator iter;
- PropertyRNA *parm;
- PyObject *ret, *item;
- int i, pyargs_len, pykw_len, parms_len, ret_len, flag_parameter, err = 0, kw_tot = 0;
- bool kw_arg;
+ PointerRNA funcptr;
+ ParameterList parms;
+ ParameterIterator iter;
+ PropertyRNA *parm;
+ PyObject *ret, *item;
+ int i, pyargs_len, pykw_len, parms_len, ret_len, flag_parameter, err = 0, kw_tot = 0;
+ bool kw_arg;
- PropertyRNA *pret_single = NULL;
- void *retdata_single = NULL;
+ PropertyRNA *pret_single = NULL;
+ void *retdata_single = NULL;
- /* enable this so all strings are copied and freed after calling.
- * this exposes bugs where the pointer to the string is held and re-used */
-// #define DEBUG_STRING_FREE
+ /* enable this so all strings are copied and freed after calling.
+ * this exposes bugs where the pointer to the string is held and re-used */
+ // #define DEBUG_STRING_FREE
#ifdef DEBUG_STRING_FREE
- PyObject *string_free_ls = PyList_New(0);
+ PyObject *string_free_ls = PyList_New(0);
#endif
- /* Should never happen but it does in rare cases */
- BLI_assert(self_ptr != NULL);
+ /* Should never happen but it does in rare cases */
+ BLI_assert(self_ptr != NULL);
- if (self_ptr == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "rna functions internal rna pointer is NULL, this is a bug. aborting");
- return NULL;
- }
+ if (self_ptr == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "rna functions internal rna pointer is NULL, this is a bug. aborting");
+ return NULL;
+ }
- if (self_func == NULL) {
- PyErr_Format(PyExc_RuntimeError,
- "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting",
- RNA_struct_identifier(self_ptr->type));
- return NULL;
- }
+ if (self_func == NULL) {
+ PyErr_Format(
+ PyExc_RuntimeError,
+ "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting",
+ RNA_struct_identifier(self_ptr->type));
+ return NULL;
+ }
- /* for testing */
+ /* for testing */
#if 0
- {
- const char *fn;
- int lineno;
- PyC_FileAndNum(&fn, &lineno);
- printf("pyrna_func_call > %.200s.%.200s : %.200s:%d\n",
- RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), fn, lineno);
- }
+ {
+ const char *fn;
+ int lineno;
+ PyC_FileAndNum(&fn, &lineno);
+ printf("pyrna_func_call > %.200s.%.200s : %.200s:%d\n",
+ RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), fn, lineno);
+ }
#endif
- /* include the ID pointer for pyrna_param_to_py() so we can include the
- * ID pointer on return values, this only works when returned values have
- * the same ID as the functions. */
- RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
-
- pyargs_len = PyTuple_GET_SIZE(args);
- pykw_len = kw ? PyDict_Size(kw) : 0;
-
- RNA_parameter_list_create(&parms, self_ptr, self_func);
- RNA_parameter_list_begin(&parms, &iter);
- parms_len = RNA_parameter_list_arg_count(&parms);
- ret_len = 0;
-
- if (pyargs_len + pykw_len > parms_len) {
- RNA_parameter_list_end(&iter);
- PyErr_Format(PyExc_TypeError,
- "%.200s.%.200s(): takes at most %d arguments, got %d",
- RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func),
- parms_len, pyargs_len + pykw_len);
- err = -1;
- }
-
- /* parse function parameters */
- for (i = 0; iter.valid && err == 0; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
- flag_parameter = RNA_parameter_flag(parm);
-
- /* only useful for single argument returns, we'll need another list loop for multiple */
- if (flag_parameter & PARM_OUTPUT) {
- ret_len++;
- if (pret_single == NULL) {
- pret_single = parm;
- retdata_single = iter.data;
- }
-
- continue;
- }
-
- item = NULL;
-
- if (i < pyargs_len) {
- /* New in 2.8x, optional arguments must be keywords. */
- if (UNLIKELY((flag_parameter & PARM_REQUIRED) == 0)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.%.200s(): required parameter \"%.200s\" to be a keyword argument!",
- RNA_struct_identifier(self_ptr->type),
- RNA_function_identifier(self_func),
- RNA_property_identifier(parm));
- err = -1;
- break;
- }
-
- item = PyTuple_GET_ITEM(args, i);
- kw_arg = false;
- }
- else if (kw != NULL) {
+ /* include the ID pointer for pyrna_param_to_py() so we can include the
+ * ID pointer on return values, this only works when returned values have
+ * the same ID as the functions. */
+ RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
+
+ pyargs_len = PyTuple_GET_SIZE(args);
+ pykw_len = kw ? PyDict_Size(kw) : 0;
+
+ RNA_parameter_list_create(&parms, self_ptr, self_func);
+ RNA_parameter_list_begin(&parms, &iter);
+ parms_len = RNA_parameter_list_arg_count(&parms);
+ ret_len = 0;
+
+ if (pyargs_len + pykw_len > parms_len) {
+ RNA_parameter_list_end(&iter);
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.%.200s(): takes at most %d arguments, got %d",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ parms_len,
+ pyargs_len + pykw_len);
+ err = -1;
+ }
+
+ /* parse function parameters */
+ for (i = 0; iter.valid && err == 0; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+ flag_parameter = RNA_parameter_flag(parm);
+
+ /* only useful for single argument returns, we'll need another list loop for multiple */
+ if (flag_parameter & PARM_OUTPUT) {
+ ret_len++;
+ if (pret_single == NULL) {
+ pret_single = parm;
+ retdata_single = iter.data;
+ }
+
+ continue;
+ }
+
+ item = NULL;
+
+ if (i < pyargs_len) {
+ /* New in 2.8x, optional arguments must be keywords. */
+ if (UNLIKELY((flag_parameter & PARM_REQUIRED) == 0)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.%.200s(): required parameter \"%.200s\" to be a keyword argument!",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ RNA_property_identifier(parm));
+ err = -1;
+ break;
+ }
+
+ item = PyTuple_GET_ITEM(args, i);
+ kw_arg = false;
+ }
+ else if (kw != NULL) {
#if 0
- item = PyDict_GetItemString(kw, RNA_property_identifier(parm)); /* borrow ref */
+ item = PyDict_GetItemString(kw, RNA_property_identifier(parm)); /* borrow ref */
#else
- item = small_dict_get_item_string(kw, RNA_property_identifier(parm)); /* borrow ref */
+ item = small_dict_get_item_string(kw, RNA_property_identifier(parm)); /* borrow ref */
#endif
- if (item) {
- kw_tot++; /* make sure invalid keywords are not given */
- }
-
- kw_arg = true;
- }
-
- i++; /* current argument */
-
- if (item == NULL) {
- if (flag_parameter & PARM_REQUIRED) {
- PyErr_Format(PyExc_TypeError,
- "%.200s.%.200s(): required parameter \"%.200s\" not specified",
- RNA_struct_identifier(self_ptr->type),
- RNA_function_identifier(self_func),
- RNA_property_identifier(parm));
- err = -1;
- break;
- }
- else { /* PyDict_GetItemString wont raise an error */
- continue;
- }
- }
+ if (item) {
+ kw_tot++; /* make sure invalid keywords are not given */
+ }
+
+ kw_arg = true;
+ }
+
+ i++; /* current argument */
+
+ if (item == NULL) {
+ if (flag_parameter & PARM_REQUIRED) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.%.200s(): required parameter \"%.200s\" not specified",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ RNA_property_identifier(parm));
+ err = -1;
+ break;
+ }
+ else { /* PyDict_GetItemString wont raise an error */
+ continue;
+ }
+ }
#ifdef DEBUG_STRING_FREE
- if (item) {
- if (PyUnicode_Check(item)) {
- PyList_APPEND(string_free_ls, PyUnicode_FromString(_PyUnicode_AsString(item)));
- }
- }
+ if (item) {
+ if (PyUnicode_Check(item)) {
+ PyList_APPEND(string_free_ls, PyUnicode_FromString(_PyUnicode_AsString(item)));
+ }
+ }
#endif
- err = pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
-
- if (err != 0) {
- /* the error generated isn't that useful, so generate it again with a useful prefix
- * could also write a function to prepend to error messages */
- char error_prefix[512];
- PyErr_Clear(); /* re-raise */
-
- if (kw_arg == true) {
- BLI_snprintf(error_prefix, sizeof(error_prefix),
- "%.200s.%.200s(): error with keyword argument \"%.200s\" - ",
- RNA_struct_identifier(self_ptr->type),
- RNA_function_identifier(self_func),
- RNA_property_identifier(parm));
- }
- else {
- BLI_snprintf(error_prefix, sizeof(error_prefix),
- "%.200s.%.200s(): error with argument %d, \"%.200s\" - ",
- RNA_struct_identifier(self_ptr->type),
- RNA_function_identifier(self_func),
- i,
- RNA_property_identifier(parm));
- }
-
- pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
-
- break;
- }
- }
-
- RNA_parameter_list_end(&iter);
-
- /* Check if we gave args that don't exist in the function
- * printing the error is slow but it should only happen when developing.
- * the if below is quick, checking if it passed less keyword args then we gave.
- * (Don't overwrite the error if we have one, otherwise can skip important messages and confuse with args)
- */
- if (err == 0 && kw && (pykw_len > kw_tot)) {
- PyObject *key, *value;
- Py_ssize_t pos = 0;
-
- DynStr *bad_args = BLI_dynstr_new();
- DynStr *good_args = BLI_dynstr_new();
-
- const char *arg_name, *bad_args_str, *good_args_str;
- bool found = false, first = true;
-
- while (PyDict_Next(kw, &pos, &key, &value)) {
-
- arg_name = _PyUnicode_AsString(key);
- found = false;
-
- if (arg_name == NULL) { /* unlikely the argname is not a string but ignore if it is*/
- PyErr_Clear();
- }
- else {
- /* Search for arg_name */
- RNA_parameter_list_begin(&parms, &iter);
- for (; iter.valid; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
- if (STREQ(arg_name, RNA_property_identifier(parm))) {
- found = true;
- break;
- }
- }
-
- RNA_parameter_list_end(&iter);
-
- if (found == false) {
- BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
- first = false;
- }
- }
- }
-
- /* list good args */
- first = true;
-
- RNA_parameter_list_begin(&parms, &iter);
- for (; iter.valid; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
- if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
- continue;
- }
-
- BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
- first = false;
- }
- RNA_parameter_list_end(&iter);
-
-
- bad_args_str = BLI_dynstr_get_cstring(bad_args);
- good_args_str = BLI_dynstr_get_cstring(good_args);
-
- PyErr_Format(PyExc_TypeError,
- "%.200s.%.200s(): was called with invalid keyword argument(s) (%s), expected (%s)",
- RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func),
- bad_args_str, good_args_str);
-
- BLI_dynstr_free(bad_args);
- BLI_dynstr_free(good_args);
- MEM_freeN((void *)bad_args_str);
- MEM_freeN((void *)good_args_str);
-
- err = -1;
- }
-
- ret = NULL;
- if (err == 0) {
- /* call function */
- ReportList reports;
- bContext *C = BPy_GetContext();
-
- BKE_reports_init(&reports, RPT_STORE);
- RNA_function_call(C, &reports, self_ptr, self_func, &parms);
-
- err = (BPy_reports_to_error(&reports, PyExc_RuntimeError, true));
-
- /* return value */
- if (err != -1) {
- if (ret_len > 0) {
- if (ret_len > 1) {
- ret = PyTuple_New(ret_len);
- i = 0; /* arg index */
-
- RNA_parameter_list_begin(&parms, &iter);
-
- for (; iter.valid; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
-
- if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
- PyTuple_SET_ITEM(ret, i++, pyrna_param_to_py(&funcptr, parm, iter.data));
- }
- }
-
- RNA_parameter_list_end(&iter);
- }
- else {
- ret = pyrna_param_to_py(&funcptr, pret_single, retdata_single);
- }
-
- /* possible there is an error in conversion */
- if (ret == NULL) {
- err = -1;
- }
- }
- }
- }
-
+ err = pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
+
+ if (err != 0) {
+ /* the error generated isn't that useful, so generate it again with a useful prefix
+ * could also write a function to prepend to error messages */
+ char error_prefix[512];
+ PyErr_Clear(); /* re-raise */
+
+ if (kw_arg == true) {
+ BLI_snprintf(error_prefix,
+ sizeof(error_prefix),
+ "%.200s.%.200s(): error with keyword argument \"%.200s\" - ",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ RNA_property_identifier(parm));
+ }
+ else {
+ BLI_snprintf(error_prefix,
+ sizeof(error_prefix),
+ "%.200s.%.200s(): error with argument %d, \"%.200s\" - ",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ i,
+ RNA_property_identifier(parm));
+ }
+
+ pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
+
+ break;
+ }
+ }
+
+ RNA_parameter_list_end(&iter);
+
+ /* Check if we gave args that don't exist in the function
+ * printing the error is slow but it should only happen when developing.
+ * the if below is quick, checking if it passed less keyword args then we gave.
+ * (Don't overwrite the error if we have one, otherwise can skip important messages and confuse with args)
+ */
+ if (err == 0 && kw && (pykw_len > kw_tot)) {
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+
+ DynStr *bad_args = BLI_dynstr_new();
+ DynStr *good_args = BLI_dynstr_new();
+
+ const char *arg_name, *bad_args_str, *good_args_str;
+ bool found = false, first = true;
+
+ while (PyDict_Next(kw, &pos, &key, &value)) {
+
+ arg_name = _PyUnicode_AsString(key);
+ found = false;
+
+ if (arg_name == NULL) { /* unlikely the argname is not a string but ignore if it is*/
+ PyErr_Clear();
+ }
+ else {
+ /* Search for arg_name */
+ RNA_parameter_list_begin(&parms, &iter);
+ for (; iter.valid; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+ if (STREQ(arg_name, RNA_property_identifier(parm))) {
+ found = true;
+ break;
+ }
+ }
+
+ RNA_parameter_list_end(&iter);
+
+ if (found == false) {
+ BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
+ first = false;
+ }
+ }
+ }
+
+ /* list good args */
+ first = true;
+
+ RNA_parameter_list_begin(&parms, &iter);
+ for (; iter.valid; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+ if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
+ continue;
+ }
+
+ BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
+ first = false;
+ }
+ RNA_parameter_list_end(&iter);
+
+ bad_args_str = BLI_dynstr_get_cstring(bad_args);
+ good_args_str = BLI_dynstr_get_cstring(good_args);
+
+ PyErr_Format(
+ PyExc_TypeError,
+ "%.200s.%.200s(): was called with invalid keyword argument(s) (%s), expected (%s)",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ bad_args_str,
+ good_args_str);
+
+ BLI_dynstr_free(bad_args);
+ BLI_dynstr_free(good_args);
+ MEM_freeN((void *)bad_args_str);
+ MEM_freeN((void *)good_args_str);
+
+ err = -1;
+ }
+
+ ret = NULL;
+ if (err == 0) {
+ /* call function */
+ ReportList reports;
+ bContext *C = BPy_GetContext();
+
+ BKE_reports_init(&reports, RPT_STORE);
+ RNA_function_call(C, &reports, self_ptr, self_func, &parms);
+
+ err = (BPy_reports_to_error(&reports, PyExc_RuntimeError, true));
+
+ /* return value */
+ if (err != -1) {
+ if (ret_len > 0) {
+ if (ret_len > 1) {
+ ret = PyTuple_New(ret_len);
+ i = 0; /* arg index */
+
+ RNA_parameter_list_begin(&parms, &iter);
+
+ for (; iter.valid; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+
+ if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
+ PyTuple_SET_ITEM(ret, i++, pyrna_param_to_py(&funcptr, parm, iter.data));
+ }
+ }
+
+ RNA_parameter_list_end(&iter);
+ }
+ else {
+ ret = pyrna_param_to_py(&funcptr, pret_single, retdata_single);
+ }
+
+ /* possible there is an error in conversion */
+ if (ret == NULL) {
+ err = -1;
+ }
+ }
+ }
+ }
#ifdef DEBUG_STRING_FREE
-#if 0
- if (PyList_GET_SIZE(string_free_ls)) {
- printf("%.200s.%.200s(): has %d strings\n",
- RNA_struct_identifier(self_ptr->type),
- RNA_function_identifier(self_func),
- (int)PyList_GET_SIZE(string_free_ls));
- }
-#endif
- Py_DECREF(string_free_ls);
-#undef DEBUG_STRING_FREE
+# if 0
+ if (PyList_GET_SIZE(string_free_ls)) {
+ printf("%.200s.%.200s(): has %d strings\n",
+ RNA_struct_identifier(self_ptr->type),
+ RNA_function_identifier(self_func),
+ (int)PyList_GET_SIZE(string_free_ls));
+ }
+# endif
+ Py_DECREF(string_free_ls);
+# undef DEBUG_STRING_FREE
#endif
- /* cleanup */
- RNA_parameter_list_end(&iter);
- RNA_parameter_list_free(&parms);
+ /* cleanup */
+ RNA_parameter_list_end(&iter);
+ RNA_parameter_list_free(&parms);
- if (ret) {
- return ret;
- }
+ if (ret) {
+ return ret;
+ }
- if (err == -1) {
- return NULL;
- }
+ if (err == -1) {
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject *pyrna_func_doc_get(BPy_FunctionRNA *self, void *UNUSED(closure))
{
- PyObject *ret;
- char *args;
+ PyObject *ret;
+ char *args;
- args = RNA_function_as_string_keywords(NULL, self->func, true, true, INT_MAX);
+ args = RNA_function_as_string_keywords(NULL, self->func, true, true, INT_MAX);
- ret = PyUnicode_FromFormat("%.200s.%.200s(%.200s)\n%s",
- RNA_struct_identifier(self->ptr.type),
- RNA_function_identifier(self->func),
- args, RNA_function_ui_description(self->func));
+ ret = PyUnicode_FromFormat("%.200s.%.200s(%.200s)\n%s",
+ RNA_struct_identifier(self->ptr.type),
+ RNA_function_identifier(self->func),
+ args,
+ RNA_function_ui_description(self->func));
- MEM_freeN(args);
+ MEM_freeN(args);
- return ret;
+ return ret;
}
/* subclasses of pyrna_struct_Type which support idprop definitions use this as a metaclass */
/* note: tp_base member is set to &PyType_Type on init */
PyTypeObject pyrna_struct_meta_idprop_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_struct_meta_idprop", /* tp_name */
-
- /* NOTE! would be PyTypeObject, but subtypes of Type must be PyHeapTypeObject's */
- sizeof(PyHeapTypeObject), /* tp_basicsize */
-
- 0, /* tp_itemsize */
- /* methods */
- NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* deprecated in python 3.0! */
- NULL, /* tp_repr */
-
- /* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
- NULL /*(getattrofunc) pyrna_struct_meta_idprop_getattro*/, /* getattrofunc tp_getattro; */
- (setattrofunc) pyrna_struct_meta_idprop_setattro, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- NULL, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL, /* struct PyGetSetDef *tp_getset; */
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_struct_meta_idprop", /* tp_name */
+
+ /* NOTE! would be PyTypeObject, but subtypes of Type must be PyHeapTypeObject's */
+ sizeof(PyHeapTypeObject), /* tp_basicsize */
+
+ 0, /* tp_itemsize */
+ /* methods */
+ NULL, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* deprecated in python 3.0! */
+ NULL, /* tp_repr */
+
+ /* Method suites for standard classes */
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+ NULL /*(getattrofunc) pyrna_struct_meta_idprop_getattro*/, /* getattrofunc tp_getattro; */
+ (setattrofunc)pyrna_struct_meta_idprop_setattro, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ NULL, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL, /* struct PyGetSetDef *tp_getset; */
#if defined(_MSC_VER)
- NULL, /* defer assignment */
+ NULL, /* defer assignment */
#else
- &PyType_Type, /* struct _typeobject *tp_base; */
+ &PyType_Type, /* struct _typeobject *tp_base; */
#endif
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
-
/*-----------------------BPy_StructRNA method def------------------------------*/
PyTypeObject pyrna_struct_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_struct", /* tp_name */
- sizeof(BPy_StructRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor) pyrna_struct_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- (reprfunc) pyrna_struct_repr, /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- &pyrna_struct_as_sequence, /* PySequenceMethods *tp_as_sequence; */
- &pyrna_struct_as_mapping, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- (hashfunc) pyrna_struct_hash, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- (reprfunc) pyrna_struct_str, /* reprfunc tp_str; */
- (getattrofunc) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
- (setattrofunc) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_struct", /* tp_name */
+ sizeof(BPy_StructRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_struct_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ (reprfunc)pyrna_struct_repr, /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ &pyrna_struct_as_sequence, /* PySequenceMethods *tp_as_sequence; */
+ &pyrna_struct_as_mapping, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ (hashfunc)pyrna_struct_hash, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ (reprfunc)pyrna_struct_str, /* reprfunc tp_str; */
+ (getattrofunc)pyrna_struct_getattro, /* getattrofunc tp_getattro; */
+ (setattrofunc)pyrna_struct_setattro, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+/*** Assigned meaning in release 2.0 ***/
+/* call function for all accessible objects */
#ifdef USE_PYRNA_STRUCT_REFERENCE
- (traverseproc) pyrna_struct_traverse, /* traverseproc tp_traverse; */
+ (traverseproc)pyrna_struct_traverse, /* traverseproc tp_traverse; */
- /* delete references to contained objects */
- (inquiry)pyrna_struct_clear, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ (inquiry)pyrna_struct_clear, /* inquiry tp_clear; */
#else
- NULL, /* traverseproc tp_traverse; */
+ NULL, /* traverseproc tp_traverse; */
-/* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
#endif /* !USE_PYRNA_STRUCT_REFERENCE */
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
- /*** weak reference enabler ***/
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_StructRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_StructRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- pyrna_struct_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- pyrna_struct_new, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ pyrna_struct_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ pyrna_struct_new, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
/*-----------------------BPy_PropertyRNA method def------------------------------*/
PyTypeObject pyrna_prop_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_prop", /* tp_name */
- sizeof(BPy_PropertyRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor) pyrna_prop_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- (reprfunc) pyrna_prop_repr, /* tp_repr */
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_prop", /* tp_name */
+ sizeof(BPy_PropertyRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_prop_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ (reprfunc)pyrna_prop_repr, /* tp_repr */
- /* Method suites for standard classes */
+ /* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
- /* More standard operations (here for binary compatibility) */
+ /* More standard operations (here for binary compatibility) */
- (hashfunc) pyrna_prop_hash, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- (reprfunc) pyrna_prop_str, /* reprfunc tp_str; */
+ (hashfunc)pyrna_prop_hash, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ (reprfunc)pyrna_prop_str, /* reprfunc tp_str; */
- /* will only use these if this is a subtype of a py class */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
+ /* will only use these if this is a subtype of a py class */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
- /*** weak reference enabler ***/
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- pyrna_prop_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- pyrna_prop_new, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ pyrna_prop_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ pyrna_prop_new, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
PyTypeObject pyrna_prop_array_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_prop_array", /* tp_name */
- sizeof(BPy_PropertyArrayRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)pyrna_prop_array_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- (reprfunc)pyrna_prop_array_repr, /* tp_repr */
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_prop_array", /* tp_name */
+ sizeof(BPy_PropertyArrayRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_prop_array_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ (reprfunc)pyrna_prop_array_repr, /* tp_repr */
- /* Method suites for standard classes */
+ /* Method suites for standard classes */
- &pyrna_prop_array_as_number, /* PyNumberMethods *tp_as_number; */
- &pyrna_prop_array_as_sequence, /* PySequenceMethods *tp_as_sequence; */
- &pyrna_prop_array_as_mapping, /* PyMappingMethods *tp_as_mapping; */
+ &pyrna_prop_array_as_number, /* PyNumberMethods *tp_as_number; */
+ &pyrna_prop_array_as_sequence, /* PySequenceMethods *tp_as_sequence; */
+ &pyrna_prop_array_as_mapping, /* PyMappingMethods *tp_as_mapping; */
- /* More standard operations (here for binary compatibility) */
+ /* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
- /* will only use these if this is a subtype of a py class */
- (getattrofunc) pyrna_prop_array_getattro, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
+ /* will only use these if this is a subtype of a py class */
+ (getattrofunc)pyrna_prop_array_getattro, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
- /*** weak reference enabler ***/
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyArrayRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_PropertyArrayRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- (getiterfunc)pyrna_prop_array_iter, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- pyrna_prop_array_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
- &pyrna_prop_Type, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ (getiterfunc)pyrna_prop_array_iter, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ pyrna_prop_array_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
+ &pyrna_prop_Type, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
PyTypeObject pyrna_prop_collection_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_prop_collection", /* tp_name */
- sizeof(BPy_PropertyRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)pyrna_prop_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* subclassed */ /* tp_repr */
-
- /* Method suites for standard classes */
-
- &pyrna_prop_collection_as_number, /* PyNumberMethods *tp_as_number; */
- &pyrna_prop_collection_as_sequence, /* PySequenceMethods *tp_as_sequence; */
- &pyrna_prop_collection_as_mapping, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
- (getattrofunc) pyrna_prop_collection_getattro, /* getattrofunc tp_getattro; */
- (setattrofunc) pyrna_prop_collection_setattro, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_prop_collection", /* tp_name */
+ sizeof(BPy_PropertyRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_prop_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL,
+ /* subclassed */ /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ &pyrna_prop_collection_as_number, /* PyNumberMethods *tp_as_number; */
+ &pyrna_prop_collection_as_sequence, /* PySequenceMethods *tp_as_sequence; */
+ &pyrna_prop_collection_as_mapping, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+ /* will only use these if this is a subtype of a py class */
+ (getattrofunc)pyrna_prop_collection_getattro, /* getattrofunc tp_getattro; */
+ (setattrofunc)pyrna_prop_collection_setattro, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- (getiterfunc)pyrna_prop_collection_iter, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- pyrna_prop_collection_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
- &pyrna_prop_Type, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ (getiterfunc)pyrna_prop_collection_iter, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ pyrna_prop_collection_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
+ &pyrna_prop_Type, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
/* only for add/remove/move methods */
static PyTypeObject pyrna_prop_collection_idprop_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_prop_collection_idprop", /* tp_name */
- sizeof(BPy_PropertyRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)pyrna_prop_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* subclassed */ /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_prop_collection_idprop", /* tp_name */
+ sizeof(BPy_PropertyRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_prop_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL,
+ /* subclassed */ /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+ /* will only use these if this is a subtype of a py class */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- pyrna_prop_collection_idprop_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
- &pyrna_prop_collection_Type, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ pyrna_prop_collection_idprop_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
+ &pyrna_prop_collection_Type, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
/*-----------------------BPy_PropertyRNA method def------------------------------*/
PyTypeObject pyrna_func_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_func", /* tp_name */
- sizeof(BPy_FunctionRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- (reprfunc) pyrna_func_repr, /* tp_repr */
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_func", /* tp_name */
+ sizeof(BPy_FunctionRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ NULL, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ (reprfunc)pyrna_func_repr, /* tp_repr */
- /* Method suites for standard classes */
+ /* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
- /* More standard operations (here for binary compatibility) */
+ /* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
- (ternaryfunc)pyrna_func_call, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
+ NULL, /* hashfunc tp_hash; */
+ (ternaryfunc)pyrna_func_call, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
- /* will only use these if this is a subtype of a py class */
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
+ /* will only use these if this is a subtype of a py class */
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- NULL, /* richcmpfunc tp_richcompare; */
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ NULL, /* richcmpfunc tp_richcompare; */
- /*** weak reference enabler ***/
+/*** weak reference enabler ***/
#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
+ offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
#else
- 0,
+ 0,
#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- NULL, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- pyrna_func_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ NULL, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ pyrna_func_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
#ifdef USE_PYRNA_ITER
@@ -6643,232 +6760,232 @@ static void pyrna_prop_collection_iter_dealloc(BPy_PropertyCollectionIterRNA *se
static PyObject *pyrna_prop_collection_iter_next(BPy_PropertyCollectionIterRNA *self);
static PyTypeObject pyrna_prop_collection_iter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bpy_prop_collection_iter", /* tp_name */
- sizeof(BPy_PropertyCollectionIterRNA), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)pyrna_prop_collection_iter_dealloc, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- NULL, /* subclassed */ /* tp_repr */
-
- /* Method suites for standard classes */
-
- NULL, /* PyNumberMethods *tp_as_number; */
- NULL, /* PySequenceMethods *tp_as_sequence; */
- NULL, /* PyMappingMethods *tp_as_mapping; */
-
- /* More standard operations (here for binary compatibility) */
-
- NULL, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
-
- /* will only use these if this is a subtype of a py class */
-#if defined(_MSC_VER)
- NULL, /* defer assignment */
-#else
- PyObject_GenericGetAttr, /* getattrofunc tp_getattro; */
-#endif
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT, /* long tp_flags; */
-
- NULL, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
- /* call function for all accessible objects */
- NULL, /* traverseproc tp_traverse; */
-
- /* delete references to contained objects */
- NULL, /* inquiry tp_clear; */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons (subclassed) ***/
- NULL, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
-#ifdef USE_WEAKREFS
- offsetof(BPy_PropertyCollectionIterRNA, in_weakreflist), /* long tp_weaklistoffset; */
-#else
- 0,
-#endif
- /*** Added in release 2.2 ***/
- /* Iterators */
-#if defined(_MSC_VER)
- NULL, /* defer assignment */
-#else
- PyObject_SelfIter, /* getiterfunc tp_iter; */
-#endif
- (iternextfunc) pyrna_prop_collection_iter_next, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- NULL, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- NULL, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- NULL, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ PyVarObject_HEAD_INIT(NULL, 0) "bpy_prop_collection_iter", /* tp_name */
+ sizeof(BPy_PropertyCollectionIterRNA), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)pyrna_prop_collection_iter_dealloc, /* tp_dealloc */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL,
+ /* tp_compare */ /* DEPRECATED in python 3.0! */
+ NULL,
+ /* subclassed */ /* tp_repr */
+
+ /* Method suites for standard classes */
+
+ NULL, /* PyNumberMethods *tp_as_number; */
+ NULL, /* PySequenceMethods *tp_as_sequence; */
+ NULL, /* PyMappingMethods *tp_as_mapping; */
+
+ /* More standard operations (here for binary compatibility) */
+
+ NULL, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
+ NULL, /* reprfunc tp_str; */
+
+/* will only use these if this is a subtype of a py class */
+# if defined(_MSC_VER)
+ NULL, /* defer assignment */
+# else
+ PyObject_GenericGetAttr, /* getattrofunc tp_getattro; */
+# endif
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT, /* long tp_flags; */
+
+ NULL, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+ /* call function for all accessible objects */
+ NULL, /* traverseproc tp_traverse; */
+
+ /* delete references to contained objects */
+ NULL, /* inquiry tp_clear; */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons (subclassed) ***/
+ NULL, /* richcmpfunc tp_richcompare; */
+
+/*** weak reference enabler ***/
+# ifdef USE_WEAKREFS
+ offsetof(BPy_PropertyCollectionIterRNA, in_weakreflist), /* long tp_weaklistoffset; */
+# else
+ 0,
+# endif
+/*** Added in release 2.2 ***/
+/* Iterators */
+# if defined(_MSC_VER)
+ NULL, /* defer assignment */
+# else
+ PyObject_SelfIter, /* getiterfunc tp_iter; */
+# endif
+ (iternextfunc)pyrna_prop_collection_iter_next, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ NULL, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ NULL, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ NULL, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
static PyObject *pyrna_prop_collection_iter_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
{
- BPy_PropertyCollectionIterRNA *self = PyObject_New(BPy_PropertyCollectionIterRNA, &pyrna_prop_collection_iter_Type);
+ BPy_PropertyCollectionIterRNA *self = PyObject_New(BPy_PropertyCollectionIterRNA,
+ &pyrna_prop_collection_iter_Type);
-#ifdef USE_WEAKREFS
- self->in_weakreflist = NULL;
-#endif
+# ifdef USE_WEAKREFS
+ self->in_weakreflist = NULL;
+# endif
- RNA_property_collection_begin(ptr, prop, &self->iter);
+ RNA_property_collection_begin(ptr, prop, &self->iter);
- return (PyObject *)self;
+ return (PyObject *)self;
}
static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self)
{
- return pyrna_prop_collection_iter_CreatePyObject(&self->ptr, self->prop);
+ return pyrna_prop_collection_iter_CreatePyObject(&self->ptr, self->prop);
}
static PyObject *pyrna_prop_collection_iter_next(BPy_PropertyCollectionIterRNA *self)
{
- if (self->iter.valid == false) {
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
- else {
- BPy_StructRNA *pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&self->iter.ptr);
+ if (self->iter.valid == false) {
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+ else {
+ BPy_StructRNA *pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&self->iter.ptr);
-#ifdef USE_PYRNA_STRUCT_REFERENCE
- if (pyrna) { /* unlikely but may fail */
- if ((PyObject *)pyrna != Py_None) {
- /* hold a reference to the iterator since it may have
- * allocated memory 'pyrna' needs. eg: introspecting dynamic enum's */
- /* TODO, we could have an api call to know if this is needed since most collections don't */
- pyrna_struct_reference_set(pyrna, (PyObject *)self);
- }
- }
-#endif /* !USE_PYRNA_STRUCT_REFERENCE */
+# ifdef USE_PYRNA_STRUCT_REFERENCE
+ if (pyrna) { /* unlikely but may fail */
+ if ((PyObject *)pyrna != Py_None) {
+ /* hold a reference to the iterator since it may have
+ * allocated memory 'pyrna' needs. eg: introspecting dynamic enum's */
+ /* TODO, we could have an api call to know if this is needed since most collections don't */
+ pyrna_struct_reference_set(pyrna, (PyObject *)self);
+ }
+ }
+# endif /* !USE_PYRNA_STRUCT_REFERENCE */
- RNA_property_collection_next(&self->iter);
+ RNA_property_collection_next(&self->iter);
- return (PyObject *)pyrna;
- }
+ return (PyObject *)pyrna;
+ }
}
-
static void pyrna_prop_collection_iter_dealloc(BPy_PropertyCollectionIterRNA *self)
{
-#ifdef USE_WEAKREFS
- if (self->in_weakreflist != NULL) {
- PyObject_ClearWeakRefs((PyObject *)self);
- }
-#endif
+# ifdef USE_WEAKREFS
+ if (self->in_weakreflist != NULL) {
+ PyObject_ClearWeakRefs((PyObject *)self);
+ }
+# endif
- RNA_property_collection_end(&self->iter);
+ RNA_property_collection_end(&self->iter);
- PyObject_DEL(self);
+ PyObject_DEL(self);
}
/* --- collection iterator: end --- */
#endif /* !USE_PYRNA_ITER */
-
static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
{
- PointerRNA ptr;
- PyObject *item;
+ PointerRNA ptr;
+ PyObject *item;
- Py_INCREF(newclass);
+ Py_INCREF(newclass);
- if (RNA_struct_py_type_get(srna)) {
- PyC_ObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
- }
+ if (RNA_struct_py_type_get(srna)) {
+ PyC_ObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
+ }
- Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
+ Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
- RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
+ RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
- /* Not 100% needed but useful,
- * having an instance within a type looks wrong however this instance IS an rna type */
+ /* Not 100% needed but useful,
+ * having an instance within a type looks wrong however this instance IS an rna type */
- /* python deals with the circular ref */
- RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
- item = pyrna_struct_CreatePyObject(&ptr);
+ /* python deals with the circular ref */
+ RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
+ item = pyrna_struct_CreatePyObject(&ptr);
- /* note, must set the class not the __dict__ else the internal slots are not updated correctly */
- PyObject_SetAttr(newclass, bpy_intern_str_bl_rna, item);
- Py_DECREF(item);
+ /* note, must set the class not the __dict__ else the internal slots are not updated correctly */
+ PyObject_SetAttr(newclass, bpy_intern_str_bl_rna, item);
+ Py_DECREF(item);
- /* add staticmethods and classmethods */
- {
- const PointerRNA func_ptr = {{NULL}, srna, NULL};
- const ListBase *lb;
- Link *link;
+ /* add staticmethods and classmethods */
+ {
+ const PointerRNA func_ptr = {{NULL}, srna, NULL};
+ const ListBase *lb;
+ Link *link;
- lb = RNA_struct_type_functions(srna);
- for (link = lb->first; link; link = link->next) {
- FunctionRNA *func = (FunctionRNA *)link;
- const int flag = RNA_function_flag(func);
- if ((flag & FUNC_NO_SELF) && /* is staticmethod or classmethod */
- (flag & FUNC_REGISTER) == false) /* is not for registration */
- {
- /* we may want to set the type of this later */
- PyObject *func_py = pyrna_func_to_py(&func_ptr, func);
- PyObject_SetAttrString(newclass, RNA_function_identifier(func), func_py);
- Py_DECREF(func_py);
- }
- }
- }
+ lb = RNA_struct_type_functions(srna);
+ for (link = lb->first; link; link = link->next) {
+ FunctionRNA *func = (FunctionRNA *)link;
+ const int flag = RNA_function_flag(func);
+ if ((flag & FUNC_NO_SELF) && /* is staticmethod or classmethod */
+ (flag & FUNC_REGISTER) == false) /* is not for registration */
+ {
+ /* we may want to set the type of this later */
+ PyObject *func_py = pyrna_func_to_py(&func_ptr, func);
+ PyObject_SetAttrString(newclass, RNA_function_identifier(func), func_py);
+ Py_DECREF(func_py);
+ }
+ }
+ }
- /* done with rna instance */
+ /* done with rna instance */
}
static PyObject *pyrna_srna_Subtype(StructRNA *srna);
/* return a borrowed reference */
-static PyObject *pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
+static PyObject *pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
{
- /* Assume RNA_struct_py_type_get(srna) was already checked */
- StructRNA *base;
+ /* Assume RNA_struct_py_type_get(srna) was already checked */
+ StructRNA *base;
- PyObject *py_base = NULL;
+ PyObject *py_base = NULL;
- /* get the base type */
- base = RNA_struct_base(srna);
+ /* get the base type */
+ base = RNA_struct_base(srna);
- if (base && base != srna) {
- /* printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
- py_base = pyrna_srna_Subtype(base); //, bpy_types_dict);
- Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
- }
+ if (base && base != srna) {
+ /* printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
+ py_base = pyrna_srna_Subtype(base); //, bpy_types_dict);
+ Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
+ }
- if (py_base == NULL) {
- py_base = (PyObject *)&pyrna_struct_Type;
- }
+ if (py_base == NULL) {
+ py_base = (PyObject *)&pyrna_struct_Type;
+ }
- return py_base;
+ return py_base;
}
/* check if we have a native python subclass, use it when it exists
@@ -6877,378 +6994,379 @@ static PyObject *bpy_types_dict = NULL;
static PyObject *pyrna_srna_ExternalType(StructRNA *srna)
{
- const char *idname = RNA_struct_identifier(srna);
- PyObject *newclass;
-
- if (bpy_types_dict == NULL) {
- PyObject *bpy_types = PyImport_ImportModuleLevel("bpy_types", NULL, NULL, NULL, 0);
-
- if (bpy_types == NULL) {
- PyErr_Print();
- PyErr_Clear();
- CLOG_ERROR(BPY_LOG_RNA, "failed to find 'bpy_types' module");
- return NULL;
- }
- bpy_types_dict = PyModule_GetDict(bpy_types); /* borrow */
- Py_DECREF(bpy_types); /* fairly safe to assume the dict is kept */
- }
-
- newclass = PyDict_GetItemString(bpy_types_dict, idname);
-
- /* sanity check, could skip this unless in debug mode */
- if (newclass) {
- PyObject *base_compare = pyrna_srna_PyBase(srna);
- //PyObject *slots = PyObject_GetAttrString(newclass, "__slots__"); // cant do this because it gets superclasses values!
- //PyObject *bases = PyObject_GetAttrString(newclass, "__bases__"); // can do this but faster not to.
- PyObject *tp_bases = ((PyTypeObject *)newclass)->tp_bases;
- PyObject *tp_slots = PyDict_GetItem(((PyTypeObject *)newclass)->tp_dict, bpy_intern_str___slots__);
-
- if (tp_slots == NULL) {
- CLOG_ERROR(BPY_LOG_RNA, "expected class '%s' to have __slots__ defined, see bpy_types.py", idname);
- newclass = NULL;
- }
- else if (PyTuple_GET_SIZE(tp_bases)) {
- PyObject *base = PyTuple_GET_ITEM(tp_bases, 0);
-
- if (base_compare != base) {
- char pyob_info[256];
- PyC_ObSpitStr(pyob_info, sizeof(pyob_info), base_compare);
- CLOG_ERROR(BPY_LOG_RNA,
- "incorrect subclassing of SRNA '%s', expected '%s', see bpy_types.py",
- idname, pyob_info);
- newclass = NULL;
- }
- else {
- CLOG_INFO(BPY_LOG_RNA, 2, "SRNA sub-classed: '%s'", idname);
- }
- }
- }
-
- return newclass;
+ const char *idname = RNA_struct_identifier(srna);
+ PyObject *newclass;
+
+ if (bpy_types_dict == NULL) {
+ PyObject *bpy_types = PyImport_ImportModuleLevel("bpy_types", NULL, NULL, NULL, 0);
+
+ if (bpy_types == NULL) {
+ PyErr_Print();
+ PyErr_Clear();
+ CLOG_ERROR(BPY_LOG_RNA, "failed to find 'bpy_types' module");
+ return NULL;
+ }
+ bpy_types_dict = PyModule_GetDict(bpy_types); /* borrow */
+ Py_DECREF(bpy_types); /* fairly safe to assume the dict is kept */
+ }
+
+ newclass = PyDict_GetItemString(bpy_types_dict, idname);
+
+ /* sanity check, could skip this unless in debug mode */
+ if (newclass) {
+ PyObject *base_compare = pyrna_srna_PyBase(srna);
+ //PyObject *slots = PyObject_GetAttrString(newclass, "__slots__"); // cant do this because it gets superclasses values!
+ //PyObject *bases = PyObject_GetAttrString(newclass, "__bases__"); // can do this but faster not to.
+ PyObject *tp_bases = ((PyTypeObject *)newclass)->tp_bases;
+ PyObject *tp_slots = PyDict_GetItem(((PyTypeObject *)newclass)->tp_dict,
+ bpy_intern_str___slots__);
+
+ if (tp_slots == NULL) {
+ CLOG_ERROR(
+ BPY_LOG_RNA, "expected class '%s' to have __slots__ defined, see bpy_types.py", idname);
+ newclass = NULL;
+ }
+ else if (PyTuple_GET_SIZE(tp_bases)) {
+ PyObject *base = PyTuple_GET_ITEM(tp_bases, 0);
+
+ if (base_compare != base) {
+ char pyob_info[256];
+ PyC_ObSpitStr(pyob_info, sizeof(pyob_info), base_compare);
+ CLOG_ERROR(BPY_LOG_RNA,
+ "incorrect subclassing of SRNA '%s', expected '%s', see bpy_types.py",
+ idname,
+ pyob_info);
+ newclass = NULL;
+ }
+ else {
+ CLOG_INFO(BPY_LOG_RNA, 2, "SRNA sub-classed: '%s'", idname);
+ }
+ }
+ }
+
+ return newclass;
}
static PyObject *pyrna_srna_Subtype(StructRNA *srna)
{
- PyObject *newclass = NULL;
-
- /* stupid/simple case */
- if (srna == NULL) {
- newclass = NULL; /* Nothing to do */
- } /* the class may have already been declared & allocated */
- else if ((newclass = RNA_struct_py_type_get(srna))) {
- Py_INCREF(newclass);
- } /* check if bpy_types.py module has the class defined in it */
- else if ((newclass = pyrna_srna_ExternalType(srna))) {
- pyrna_subtype_set_rna(newclass, srna);
- Py_INCREF(newclass);
- } /* create a new class instance with the C api
- * mainly for the purposing of matching the C/rna type hierarchy */
- else {
- /* subclass equivalents
- * - class myClass(myBase):
- * some = 'value' # or ...
- * - myClass = type(name='myClass', bases=(myBase,), dict={'__module__': 'bpy.types', '__slots__': ()})
- */
-
- /* Assume RNA_struct_py_type_get(srna) was already checked */
- PyObject *py_base = pyrna_srna_PyBase(srna);
- PyObject *metaclass;
- const char *idname = RNA_struct_identifier(srna);
-
- /* remove __doc__ for now */
- // const char *descr = RNA_struct_ui_description(srna);
- // if (!descr) descr = "(no docs)";
- // "__doc__", descr
-
- if (RNA_struct_idprops_check(srna) &&
- !PyObject_IsSubclass(py_base, (PyObject *)&pyrna_struct_meta_idprop_Type))
- {
- metaclass = (PyObject *)&pyrna_struct_meta_idprop_Type;
- }
- else {
- metaclass = (PyObject *)&PyType_Type;
- }
-
- /* always use O not N when calling, N causes refcount errors */
+ PyObject *newclass = NULL;
+
+ /* stupid/simple case */
+ if (srna == NULL) {
+ newclass = NULL; /* Nothing to do */
+ } /* the class may have already been declared & allocated */
+ else if ((newclass = RNA_struct_py_type_get(srna))) {
+ Py_INCREF(newclass);
+ } /* check if bpy_types.py module has the class defined in it */
+ else if ((newclass = pyrna_srna_ExternalType(srna))) {
+ pyrna_subtype_set_rna(newclass, srna);
+ Py_INCREF(newclass);
+ } /* create a new class instance with the C api
+ * mainly for the purposing of matching the C/rna type hierarchy */
+ else {
+ /* subclass equivalents
+ * - class myClass(myBase):
+ * some = 'value' # or ...
+ * - myClass = type(name='myClass', bases=(myBase,), dict={'__module__': 'bpy.types', '__slots__': ()})
+ */
+
+ /* Assume RNA_struct_py_type_get(srna) was already checked */
+ PyObject *py_base = pyrna_srna_PyBase(srna);
+ PyObject *metaclass;
+ const char *idname = RNA_struct_identifier(srna);
+
+ /* remove __doc__ for now */
+ // const char *descr = RNA_struct_ui_description(srna);
+ // if (!descr) descr = "(no docs)";
+ // "__doc__", descr
+
+ if (RNA_struct_idprops_check(srna) &&
+ !PyObject_IsSubclass(py_base, (PyObject *)&pyrna_struct_meta_idprop_Type)) {
+ metaclass = (PyObject *)&pyrna_struct_meta_idprop_Type;
+ }
+ else {
+ metaclass = (PyObject *)&PyType_Type;
+ }
+
+ /* always use O not N when calling, N causes refcount errors */
#if 0
- newclass = PyObject_CallFunction(metaclass, "s(O) {sss()}",
- idname, py_base, "__module__", "bpy.types", "__slots__");
+ newclass = PyObject_CallFunction(metaclass, "s(O) {sss()}",
+ idname, py_base, "__module__", "bpy.types", "__slots__");
#else
- {
- /* longhand of the call above */
- PyObject *args, *item, *value;
- int ok;
+ {
+ /* longhand of the call above */
+ PyObject *args, *item, *value;
+ int ok;
- args = PyTuple_New(3);
+ args = PyTuple_New(3);
- /* arg[0] (name=...) */
- PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(idname));
+ /* arg[0] (name=...) */
+ PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(idname));
+ /* arg[1] (bases=...) */
+ PyTuple_SET_ITEM(args, 1, item = PyTuple_New(1));
+ PyTuple_SET_ITEM(item, 0, Py_INCREF_RET(py_base));
- /* arg[1] (bases=...) */
- PyTuple_SET_ITEM(args, 1, item = PyTuple_New(1));
- PyTuple_SET_ITEM(item, 0, Py_INCREF_RET(py_base));
+ /* arg[2] (dict=...) */
+ PyTuple_SET_ITEM(args, 2, item = PyDict_New());
+ ok = PyDict_SetItem(item, bpy_intern_str___module__, bpy_intern_str_bpy_types);
+ BLI_assert(ok != -1);
+ ok = PyDict_SetItem(item, bpy_intern_str___slots__, value = PyTuple_New(0));
+ Py_DECREF(value);
+ BLI_assert(ok != -1);
+ newclass = PyObject_CallObject(metaclass, args);
+ Py_DECREF(args);
- /* arg[2] (dict=...) */
- PyTuple_SET_ITEM(args, 2, item = PyDict_New());
- ok = PyDict_SetItem(item, bpy_intern_str___module__, bpy_intern_str_bpy_types);
- BLI_assert(ok != -1);
- ok = PyDict_SetItem(item, bpy_intern_str___slots__, value = PyTuple_New(0)); Py_DECREF(value);
- BLI_assert(ok != -1);
-
- newclass = PyObject_CallObject(metaclass, args);
- Py_DECREF(args);
-
- (void)ok;
- }
+ (void)ok;
+ }
#endif
- /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
+ /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
- /* PyC_ObSpit("new class ref", newclass); */
+ /* PyC_ObSpit("new class ref", newclass); */
- if (newclass) {
- /* srna owns one, and the other is owned by the caller */
- pyrna_subtype_set_rna(newclass, srna);
+ if (newclass) {
+ /* srna owns one, and the other is owned by the caller */
+ pyrna_subtype_set_rna(newclass, srna);
- /* XXX, adding this back segfaults blender on load. */
- // Py_DECREF(newclass); /* let srna own */
- }
- else {
- /* this should not happen */
- CLOG_ERROR(BPY_LOG_RNA, "failed to register '%s'", idname);
- PyErr_Print();
- PyErr_Clear();
- }
- }
+ /* XXX, adding this back segfaults blender on load. */
+ // Py_DECREF(newclass); /* let srna own */
+ }
+ else {
+ /* this should not happen */
+ CLOG_ERROR(BPY_LOG_RNA, "failed to register '%s'", idname);
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
- return newclass;
+ return newclass;
}
/* use for subtyping so we know which srna is used for a PointerRNA */
static StructRNA *srna_from_ptr(PointerRNA *ptr)
{
- if (ptr->type == &RNA_Struct) {
- return ptr->data;
- }
- else {
- return ptr->type;
- }
+ if (ptr->type == &RNA_Struct) {
+ return ptr->data;
+ }
+ else {
+ return ptr->type;
+ }
}
/* always returns a new ref, be sure to decref when done */
static PyObject *pyrna_struct_Subtype(PointerRNA *ptr)
{
- return pyrna_srna_Subtype(srna_from_ptr(ptr));
+ return pyrna_srna_Subtype(srna_from_ptr(ptr));
}
/*-----------------------CreatePyObject---------------------------------*/
PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr)
{
- BPy_StructRNA *pyrna = NULL;
-
- /* note: don't rely on this to return None since NULL data with a valid type can often crash */
- if (ptr->data == NULL && ptr->type == NULL) { /* Operator RNA has NULL data */
- Py_RETURN_NONE;
- }
-
- /* New in 2.8x, since not many types support instancing
- * we may want to use a flag to avoid looping over all classes. - campbell */
- void **instance = ptr->data ? RNA_struct_instance(ptr) : NULL;
- if (instance && *instance) {
- pyrna = *instance;
-
- /* Refine may have changed types after the first instance was created. */
- if (ptr->type == pyrna->ptr.type) {
- Py_INCREF(pyrna);
- return (PyObject *)pyrna;
- }
- else {
- /* Existing users will need to use 'type_recast' method. */
- Py_DECREF(pyrna);
- *instance = NULL;
- /* Continue as if no instance was made */
-#if 0 /* no need to assign, will be written to next... */
- pyrna = NULL;
+ BPy_StructRNA *pyrna = NULL;
+
+ /* note: don't rely on this to return None since NULL data with a valid type can often crash */
+ if (ptr->data == NULL && ptr->type == NULL) { /* Operator RNA has NULL data */
+ Py_RETURN_NONE;
+ }
+
+ /* New in 2.8x, since not many types support instancing
+ * we may want to use a flag to avoid looping over all classes. - campbell */
+ void **instance = ptr->data ? RNA_struct_instance(ptr) : NULL;
+ if (instance && *instance) {
+ pyrna = *instance;
+
+ /* Refine may have changed types after the first instance was created. */
+ if (ptr->type == pyrna->ptr.type) {
+ Py_INCREF(pyrna);
+ return (PyObject *)pyrna;
+ }
+ else {
+ /* Existing users will need to use 'type_recast' method. */
+ Py_DECREF(pyrna);
+ *instance = NULL;
+ /* Continue as if no instance was made */
+#if 0 /* no need to assign, will be written to next... */
+ pyrna = NULL;
#endif
- }
- }
-
- {
- PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
-
- if (tp) {
- pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
- Py_DECREF(tp); /* srna owns, cant hold a ref */
- }
- else {
- CLOG_WARN(BPY_LOG_RNA, "could not make type '%s'", RNA_struct_identifier(ptr->type));
- pyrna = (BPy_StructRNA *) PyObject_GC_New(BPy_StructRNA, &pyrna_struct_Type);
+ }
+ }
+
+ {
+ PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
+
+ if (tp) {
+ pyrna = (BPy_StructRNA *)tp->tp_alloc(tp, 0);
+ Py_DECREF(tp); /* srna owns, cant hold a ref */
+ }
+ else {
+ CLOG_WARN(BPY_LOG_RNA, "could not make type '%s'", RNA_struct_identifier(ptr->type));
+ pyrna = (BPy_StructRNA *)PyObject_GC_New(BPy_StructRNA, &pyrna_struct_Type);
#ifdef USE_WEAKREFS
- pyrna->in_weakreflist = NULL;
+ pyrna->in_weakreflist = NULL;
#endif
- }
- }
+ }
+ }
- if (pyrna == NULL) {
- PyErr_SetString(PyExc_MemoryError, "couldn't create bpy_struct object");
- return NULL;
- }
+ if (pyrna == NULL) {
+ PyErr_SetString(PyExc_MemoryError, "couldn't create bpy_struct object");
+ return NULL;
+ }
- /* Blender's instance owns a reference (to avoid Python freeing it). */
- if (instance) {
- *instance = pyrna;
- Py_INCREF(pyrna);
- }
+ /* Blender's instance owns a reference (to avoid Python freeing it). */
+ if (instance) {
+ *instance = pyrna;
+ Py_INCREF(pyrna);
+ }
- pyrna->ptr = *ptr;
+ pyrna->ptr = *ptr;
#ifdef PYRNA_FREE_SUPPORT
- pyrna->freeptr = false;
+ pyrna->freeptr = false;
#endif
#ifdef USE_PYRNA_STRUCT_REFERENCE
- pyrna->reference = NULL;
+ pyrna->reference = NULL;
#endif
- // PyC_ObSpit("NewStructRNA: ", (PyObject *)pyrna);
+ // PyC_ObSpit("NewStructRNA: ", (PyObject *)pyrna);
#ifdef USE_PYRNA_INVALIDATE_WEAKREF
- if (ptr->id.data) {
- id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
- }
+ if (ptr->id.data) {
+ id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
+ }
#endif
- return (PyObject *)pyrna;
+ return (PyObject *)pyrna;
}
PyObject *pyrna_prop_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
{
- BPy_PropertyRNA *pyrna;
+ BPy_PropertyRNA *pyrna;
- if (RNA_property_array_check(prop) == 0) {
- PyTypeObject *type;
+ if (RNA_property_array_check(prop) == 0) {
+ PyTypeObject *type;
- if (RNA_property_type(prop) != PROP_COLLECTION) {
- type = &pyrna_prop_Type;
- }
- else {
- if ((RNA_property_flag(prop) & PROP_IDPROPERTY) == 0) {
- type = &pyrna_prop_collection_Type;
- }
- else {
- type = &pyrna_prop_collection_idprop_Type;
- }
- }
+ if (RNA_property_type(prop) != PROP_COLLECTION) {
+ type = &pyrna_prop_Type;
+ }
+ else {
+ if ((RNA_property_flag(prop) & PROP_IDPROPERTY) == 0) {
+ type = &pyrna_prop_collection_Type;
+ }
+ else {
+ type = &pyrna_prop_collection_idprop_Type;
+ }
+ }
- pyrna = (BPy_PropertyRNA *) PyObject_NEW(BPy_PropertyRNA, type);
+ pyrna = (BPy_PropertyRNA *)PyObject_NEW(BPy_PropertyRNA, type);
#ifdef USE_WEAKREFS
- pyrna->in_weakreflist = NULL;
+ pyrna->in_weakreflist = NULL;
#endif
- }
- else {
- pyrna = (BPy_PropertyRNA *) PyObject_NEW(BPy_PropertyArrayRNA, &pyrna_prop_array_Type);
- ((BPy_PropertyArrayRNA *)pyrna)->arraydim = 0;
- ((BPy_PropertyArrayRNA *)pyrna)->arrayoffset = 0;
+ }
+ else {
+ pyrna = (BPy_PropertyRNA *)PyObject_NEW(BPy_PropertyArrayRNA, &pyrna_prop_array_Type);
+ ((BPy_PropertyArrayRNA *)pyrna)->arraydim = 0;
+ ((BPy_PropertyArrayRNA *)pyrna)->arrayoffset = 0;
#ifdef USE_WEAKREFS
- ((BPy_PropertyArrayRNA *)pyrna)->in_weakreflist = NULL;
+ ((BPy_PropertyArrayRNA *)pyrna)->in_weakreflist = NULL;
#endif
- }
+ }
- if (pyrna == NULL) {
- PyErr_SetString(PyExc_MemoryError, "couldn't create BPy_rna object");
- return NULL;
- }
+ if (pyrna == NULL) {
+ PyErr_SetString(PyExc_MemoryError, "couldn't create BPy_rna object");
+ return NULL;
+ }
- pyrna->ptr = *ptr;
- pyrna->prop = prop;
+ pyrna->ptr = *ptr;
+ pyrna->prop = prop;
#ifdef USE_PYRNA_INVALIDATE_WEAKREF
- if (ptr->id.data) {
- id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
- }
+ if (ptr->id.data) {
+ id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
+ }
#endif
- return (PyObject *)pyrna;
+ return (PyObject *)pyrna;
}
/* utility func to be used by external modules, *sneaky!* */
PyObject *pyrna_id_CreatePyObject(ID *id)
{
- if (id) {
- PointerRNA ptr;
- RNA_id_pointer_create(id, &ptr);
- return pyrna_struct_CreatePyObject(&ptr);
- }
- else {
- Py_RETURN_NONE;
- }
+ if (id) {
+ PointerRNA ptr;
+ RNA_id_pointer_create(id, &ptr);
+ return pyrna_struct_CreatePyObject(&ptr);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
{
- if (pyrna_id_CheckPyObject(obj)) {
- *id = ((BPy_StructRNA *)obj)->ptr.id.data;
- return true;
- }
- else {
- *id = NULL;
- return false;
- }
+ if (pyrna_id_CheckPyObject(obj)) {
+ *id = ((BPy_StructRNA *)obj)->ptr.id.data;
+ return true;
+ }
+ else {
+ *id = NULL;
+ return false;
+ }
}
bool pyrna_id_CheckPyObject(PyObject *obj)
{
- return BPy_StructRNA_Check(obj) && (RNA_struct_is_ID(((BPy_StructRNA *) obj)->ptr.type));
+ return BPy_StructRNA_Check(obj) && (RNA_struct_is_ID(((BPy_StructRNA *)obj)->ptr.type));
}
void BPY_rna_init(void)
{
-#ifdef USE_MATHUTILS /* register mathutils callbacks, ok to run more than once. */
- mathutils_rna_array_cb_index = Mathutils_RegisterCallback(&mathutils_rna_array_cb);
- mathutils_rna_matrix_cb_index = Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
+#ifdef USE_MATHUTILS /* register mathutils callbacks, ok to run more than once. */
+ mathutils_rna_array_cb_index = Mathutils_RegisterCallback(&mathutils_rna_array_cb);
+ mathutils_rna_matrix_cb_index = Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
#endif
- /* for some reason MSVC complains of these */
+ /* for some reason MSVC complains of these */
#if defined(_MSC_VER)
- pyrna_struct_meta_idprop_Type.tp_base = &PyType_Type;
+ pyrna_struct_meta_idprop_Type.tp_base = &PyType_Type;
- pyrna_prop_collection_iter_Type.tp_iter = PyObject_SelfIter;
- pyrna_prop_collection_iter_Type.tp_getattro = PyObject_GenericGetAttr;
+ pyrna_prop_collection_iter_Type.tp_iter = PyObject_SelfIter;
+ pyrna_prop_collection_iter_Type.tp_getattro = PyObject_GenericGetAttr;
#endif
- /* metaclass */
- if (PyType_Ready(&pyrna_struct_meta_idprop_Type) < 0) {
- return;
- }
+ /* metaclass */
+ if (PyType_Ready(&pyrna_struct_meta_idprop_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_struct_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_struct_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_prop_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_prop_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_prop_array_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_prop_array_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_prop_collection_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_prop_collection_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_prop_collection_idprop_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_prop_collection_idprop_Type) < 0) {
+ return;
+ }
- if (PyType_Ready(&pyrna_func_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_func_Type) < 0) {
+ return;
+ }
#ifdef USE_PYRNA_ITER
- if (PyType_Ready(&pyrna_prop_collection_iter_Type) < 0) {
- return;
- }
+ if (PyType_Ready(&pyrna_prop_collection_iter_Type) < 0) {
+ return;
+ }
#endif
}
@@ -7256,26 +7374,26 @@ void BPY_rna_init(void)
static PointerRNA *rna_module_ptr = NULL;
PyObject *BPY_rna_module(void)
{
- BPy_StructRNA *pyrna;
- PointerRNA ptr;
+ BPy_StructRNA *pyrna;
+ PointerRNA ptr;
- /* for now, return the base RNA type rather than a real module */
- RNA_main_pointer_create(G_MAIN, &ptr);
- pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
+ /* for now, return the base RNA type rather than a real module */
+ RNA_main_pointer_create(G_MAIN, &ptr);
+ pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
- rna_module_ptr = &pyrna->ptr;
- return (PyObject *)pyrna;
+ rna_module_ptr = &pyrna->ptr;
+ return (PyObject *)pyrna;
}
void BPY_update_rna_module(void)
{
- if (rna_module_ptr) {
+ if (rna_module_ptr) {
#if 0
- RNA_main_pointer_create(G_MAIN, rna_module_ptr);
+ RNA_main_pointer_create(G_MAIN, rna_module_ptr);
#else
- rna_module_ptr->data = G_MAIN; /* just set data is enough */
+ rna_module_ptr->data = G_MAIN; /* just set data is enough */
#endif
- }
+ }
}
#if 0
@@ -7283,49 +7401,48 @@ void BPY_update_rna_module(void)
* without having the datatypes in blender */
PyObject *BPY_rna_doc(void)
{
- PointerRNA ptr;
+ PointerRNA ptr;
- /* for now, return the base RNA type rather than a real module */
- RNA_blender_rna_pointer_create(&ptr);
+ /* for now, return the base RNA type rather than a real module */
+ RNA_blender_rna_pointer_create(&ptr);
- return pyrna_struct_CreatePyObject(&ptr);
+ return pyrna_struct_CreatePyObject(&ptr);
}
#endif
-
/* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a different type
* the self->ptr and self->prop are always set to the "structs" collection */
/* ---------------getattr-------------------------------------------- */
static PyObject *pyrna_basetype_getattro(BPy_BaseTypeRNA *self, PyObject *pyname)
{
- PointerRNA newptr;
- PyObject *ret;
- const char *name = _PyUnicode_AsString(pyname);
-
- if (name == NULL) {
- PyErr_SetString(PyExc_AttributeError, "bpy.types: __getattr__ must be a string");
- ret = NULL;
- }
- else if (RNA_property_collection_lookup_string(&self->ptr, self->prop, name, &newptr)) {
- ret = pyrna_struct_Subtype(&newptr);
- if (ret == NULL) {
- PyErr_Format(PyExc_RuntimeError,
- "bpy.types.%.200s subtype could not be generated, this is a bug!",
- _PyUnicode_AsString(pyname));
- }
- }
- else {
+ PointerRNA newptr;
+ PyObject *ret;
+ const char *name = _PyUnicode_AsString(pyname);
+
+ if (name == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy.types: __getattr__ must be a string");
+ ret = NULL;
+ }
+ else if (RNA_property_collection_lookup_string(&self->ptr, self->prop, name, &newptr)) {
+ ret = pyrna_struct_Subtype(&newptr);
+ if (ret == NULL) {
+ PyErr_Format(PyExc_RuntimeError,
+ "bpy.types.%.200s subtype could not be generated, this is a bug!",
+ _PyUnicode_AsString(pyname));
+ }
+ }
+ else {
#if 0
- PyErr_Format(PyExc_AttributeError,
- "bpy.types.%.200s RNA_Struct does not exist",
- _PyUnicode_AsString(pyname));
- return NULL;
+ PyErr_Format(PyExc_AttributeError,
+ "bpy.types.%.200s RNA_Struct does not exist",
+ _PyUnicode_AsString(pyname));
+ return NULL;
#endif
- /* The error raised here will be displayed */
- ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
- }
+ /* The error raised here will be displayed */
+ ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
+ }
- return ret;
+ return ret;
}
static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
@@ -7333,43 +7450,42 @@ static PyObject *pyrna_register_class(PyObject *self, PyObject *py_class);
static PyObject *pyrna_unregister_class(PyObject *self, PyObject *py_class);
static struct PyMethodDef pyrna_basetype_methods[] = {
- {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
- {NULL, NULL, 0, NULL},
+ {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
+ {NULL, NULL, 0, NULL},
};
/* used to call ..._keys() direct, but we need to filter out operator subclasses */
#if 0
static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
{
- PyObject *list;
-#if 0
- PyMethodDef *meth;
-#endif
+ PyObject *list;
+# if 0
+ PyMethodDef *meth;
+# endif
- list = pyrna_prop_collection_keys(self); /* like calling structs.keys(), avoids looping here */
+ list = pyrna_prop_collection_keys(self); /* like calling structs.keys(), avoids looping here */
-#if 0 /* for now only contains __dir__ */
- for (meth = pyrna_basetype_methods; meth->ml_name; meth++) {
- PyList_APPEND(list, PyUnicode_FromString(meth->ml_name));
- }
-#endif
- return list;
+# if 0 /* for now only contains __dir__ */
+ for (meth = pyrna_basetype_methods; meth->ml_name; meth++) {
+ PyList_APPEND(list, PyUnicode_FromString(meth->ml_name));
+ }
+# endif
+ return list;
}
#else
static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
{
- PyObject *ret = PyList_New(0);
+ PyObject *ret = PyList_New(0);
- RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
- {
- StructRNA *srna = itemptr.data;
- PyList_APPEND(ret, PyUnicode_FromString(RNA_struct_identifier(srna)));
- }
- RNA_PROP_END;
+ RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop) {
+ StructRNA *srna = itemptr.data;
+ PyList_APPEND(ret, PyUnicode_FromString(RNA_struct_identifier(srna)));
+ }
+ RNA_PROP_END;
- return ret;
+ return ret;
}
#endif
@@ -7381,98 +7497,103 @@ static PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
*/
PyObject *BPY_rna_types(void)
{
- BPy_BaseTypeRNA *self;
-
- if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY) == 0) {
- pyrna_basetype_Type.tp_name = "RNA_Types";
- pyrna_basetype_Type.tp_basicsize = sizeof(BPy_BaseTypeRNA);
- pyrna_basetype_Type.tp_getattro = (getattrofunc) pyrna_basetype_getattro;
- pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
- pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
-
- if (PyType_Ready(&pyrna_basetype_Type) < 0) {
- return NULL;
- }
- }
-
- /* static members for the base class */
- /* add __name__ since help() expects its */
- PyDict_SetItem(pyrna_basetype_Type.tp_dict, bpy_intern_str___name__, bpy_intern_str_bpy_types);
-
- /* internal base types we have no other accessors for */
- {
- PyTypeObject *pyrna_types[] = {
- &pyrna_struct_meta_idprop_Type,
- &pyrna_struct_Type,
- &pyrna_prop_Type,
- &pyrna_prop_array_Type,
- &pyrna_prop_collection_Type,
- &pyrna_func_Type,
- };
-
- for (int i = 0; i < ARRAY_SIZE(pyrna_types); i += 1) {
- PyDict_SetItemString(pyrna_basetype_Type.tp_dict, pyrna_types[i]->tp_name, (PyObject *)pyrna_types[i]);
- }
- }
-
- self = (BPy_BaseTypeRNA *)PyObject_NEW(BPy_BaseTypeRNA, &pyrna_basetype_Type);
-
- /* avoid doing this lookup for every getattr */
- RNA_blender_rna_pointer_create(&self->ptr);
- self->prop = RNA_struct_find_property(&self->ptr, "structs");
+ BPy_BaseTypeRNA *self;
+
+ if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY) == 0) {
+ pyrna_basetype_Type.tp_name = "RNA_Types";
+ pyrna_basetype_Type.tp_basicsize = sizeof(BPy_BaseTypeRNA);
+ pyrna_basetype_Type.tp_getattro = (getattrofunc)pyrna_basetype_getattro;
+ pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
+ pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
+
+ if (PyType_Ready(&pyrna_basetype_Type) < 0) {
+ return NULL;
+ }
+ }
+
+ /* static members for the base class */
+ /* add __name__ since help() expects its */
+ PyDict_SetItem(pyrna_basetype_Type.tp_dict, bpy_intern_str___name__, bpy_intern_str_bpy_types);
+
+ /* internal base types we have no other accessors for */
+ {
+ PyTypeObject *pyrna_types[] = {
+ &pyrna_struct_meta_idprop_Type,
+ &pyrna_struct_Type,
+ &pyrna_prop_Type,
+ &pyrna_prop_array_Type,
+ &pyrna_prop_collection_Type,
+ &pyrna_func_Type,
+ };
+
+ for (int i = 0; i < ARRAY_SIZE(pyrna_types); i += 1) {
+ PyDict_SetItemString(
+ pyrna_basetype_Type.tp_dict, pyrna_types[i]->tp_name, (PyObject *)pyrna_types[i]);
+ }
+ }
+
+ self = (BPy_BaseTypeRNA *)PyObject_NEW(BPy_BaseTypeRNA, &pyrna_basetype_Type);
+
+ /* avoid doing this lookup for every getattr */
+ RNA_blender_rna_pointer_create(&self->ptr);
+ self->prop = RNA_struct_find_property(&self->ptr, "structs");
#ifdef USE_WEAKREFS
- self->in_weakreflist = NULL;
+ self->in_weakreflist = NULL;
#endif
- return (PyObject *)self;
+ return (PyObject *)self;
}
StructRNA *pyrna_struct_as_srna(PyObject *self, const bool parent, const char *error_prefix)
{
- BPy_StructRNA *py_srna = NULL;
- StructRNA *srna;
-
- /* ack, PyObject_GetAttrString wont look up this types tp_dict first :/ */
- if (PyType_Check(self)) {
- py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
- Py_XINCREF(py_srna);
- }
-
- if (parent) {
- /* be very careful with this since it will return a parent classes srna.
- * modifying this will do confusing stuff! */
- if (py_srna == NULL) {
- py_srna = (BPy_StructRNA *)PyObject_GetAttr(self, bpy_intern_str_bl_rna);
- }
- }
-
- if (py_srna == NULL) {
- PyErr_Format(PyExc_RuntimeError,
- "%.200s, missing bl_rna attribute from '%.200s' instance (may not be registered)",
- error_prefix, Py_TYPE(self)->tp_name);
- return NULL;
- }
-
- if (!BPy_StructRNA_Check(py_srna)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s, bl_rna attribute wrong type '%.200s' on '%.200s'' instance",
- error_prefix, Py_TYPE(py_srna)->tp_name,
- Py_TYPE(self)->tp_name);
- Py_DECREF(py_srna);
- return NULL;
- }
-
- if (py_srna->ptr.type != &RNA_Struct) {
- PyErr_Format(PyExc_TypeError,
- "%.200s, bl_rna attribute not a RNA_Struct, on '%.200s'' instance",
- error_prefix, Py_TYPE(self)->tp_name);
- Py_DECREF(py_srna);
- return NULL;
- }
-
- srna = py_srna->ptr.data;
- Py_DECREF(py_srna);
-
- return srna;
+ BPy_StructRNA *py_srna = NULL;
+ StructRNA *srna;
+
+ /* ack, PyObject_GetAttrString wont look up this types tp_dict first :/ */
+ if (PyType_Check(self)) {
+ py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)self)->tp_dict,
+ bpy_intern_str_bl_rna);
+ Py_XINCREF(py_srna);
+ }
+
+ if (parent) {
+ /* be very careful with this since it will return a parent classes srna.
+ * modifying this will do confusing stuff! */
+ if (py_srna == NULL) {
+ py_srna = (BPy_StructRNA *)PyObject_GetAttr(self, bpy_intern_str_bl_rna);
+ }
+ }
+
+ if (py_srna == NULL) {
+ PyErr_Format(PyExc_RuntimeError,
+ "%.200s, missing bl_rna attribute from '%.200s' instance (may not be registered)",
+ error_prefix,
+ Py_TYPE(self)->tp_name);
+ return NULL;
+ }
+
+ if (!BPy_StructRNA_Check(py_srna)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s, bl_rna attribute wrong type '%.200s' on '%.200s'' instance",
+ error_prefix,
+ Py_TYPE(py_srna)->tp_name,
+ Py_TYPE(self)->tp_name);
+ Py_DECREF(py_srna);
+ return NULL;
+ }
+
+ if (py_srna->ptr.type != &RNA_Struct) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s, bl_rna attribute not a RNA_Struct, on '%.200s'' instance",
+ error_prefix,
+ Py_TYPE(self)->tp_name);
+ Py_DECREF(py_srna);
+ return NULL;
+ }
+
+ srna = py_srna->ptr.data;
+ Py_DECREF(py_srna);
+
+ return srna;
}
/* Orphan functions, not sure where they should go */
@@ -7482,755 +7603,791 @@ StructRNA *pyrna_struct_as_srna(PyObject *self, const bool parent, const char *e
StructRNA *srna_from_self(PyObject *self, const char *error_prefix)
{
- if (self == NULL) {
- return NULL;
- }
- else if (PyCapsule_CheckExact(self)) {
- return PyCapsule_GetPointer(self, NULL);
- }
- else if (PyType_Check(self) == 0) {
- return NULL;
- }
- else {
- /* These cases above not errors, they just mean the type was not compatible
- * After this any errors will be raised in the script */
+ if (self == NULL) {
+ return NULL;
+ }
+ else if (PyCapsule_CheckExact(self)) {
+ return PyCapsule_GetPointer(self, NULL);
+ }
+ else if (PyType_Check(self) == 0) {
+ return NULL;
+ }
+ else {
+ /* These cases above not errors, they just mean the type was not compatible
+ * After this any errors will be raised in the script */
- PyObject *error_type, *error_value, *error_traceback;
- StructRNA *srna;
+ PyObject *error_type, *error_value, *error_traceback;
+ StructRNA *srna;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- PyErr_Clear();
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ PyErr_Clear();
- srna = pyrna_struct_as_srna(self, false, error_prefix);
+ srna = pyrna_struct_as_srna(self, false, error_prefix);
- if (!PyErr_Occurred()) {
- PyErr_Restore(error_type, error_value, error_traceback);
- }
+ if (!PyErr_Occurred()) {
+ PyErr_Restore(error_type, error_value, error_traceback);
+ }
- return srna;
- }
+ return srna;
+ }
}
static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item)
{
- /* We only care about results from C which
- * are for sure types, save some time with error */
- if (pyrna_is_deferred_prop(item)) {
-
- PyObject *py_func, *py_kw, *py_srna_cobject, *py_ret;
-
- if (PyArg_ParseTuple(item, "OO!", &py_func, &PyDict_Type, &py_kw)) {
- PyObject *args_fake;
-
- if (*_PyUnicode_AsString(key) == '_') {
- PyErr_Format(PyExc_ValueError,
- "bpy_struct \"%.200s\" registration error: "
- "%.200s could not register because the property starts with an '_'\n",
- RNA_struct_identifier(srna), _PyUnicode_AsString(key));
- return -1;
- }
- py_srna_cobject = PyCapsule_New(srna, NULL, NULL);
-
- /* not 100% nice :/, modifies the dict passed, should be ok */
- PyDict_SetItem(py_kw, bpy_intern_str_attr, key);
-
- args_fake = PyTuple_New(1);
- PyTuple_SET_ITEM(args_fake, 0, py_srna_cobject);
-
- PyObject *type = PyDict_GetItemString(py_kw, "type");
- StructRNA *type_srna = srna_from_self(type, "");
- if (type_srna) {
- if (!RNA_struct_idprops_datablock_allowed(srna) &&
- (*(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) == BPy_PointerProperty ||
- *(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) == BPy_CollectionProperty) &&
- RNA_struct_idprops_contains_datablock(type_srna))
- {
- PyErr_Format(PyExc_ValueError,
- "bpy_struct \"%.200s\" doesn't support datablock properties\n",
- RNA_struct_identifier(srna));
- return -1;
- }
- }
-
- py_ret = PyObject_Call(py_func, args_fake, py_kw);
-
- if (py_ret) {
- Py_DECREF(py_ret);
- Py_DECREF(args_fake); /* free's py_srna_cobject too */
- }
- else {
- /* _must_ print before decreffing args_fake */
- PyErr_Print();
- PyErr_Clear();
-
- Py_DECREF(args_fake); /* free's py_srna_cobject too */
-
- // PyC_LineSpit();
- PyErr_Format(PyExc_ValueError,
- "bpy_struct \"%.200s\" registration error: "
- "%.200s could not register\n",
- RNA_struct_identifier(srna), _PyUnicode_AsString(key));
- return -1;
- }
- }
- else {
- /* Since this is a class dict, ignore args that can't be passed */
-
- /* for testing only */
+ /* We only care about results from C which
+ * are for sure types, save some time with error */
+ if (pyrna_is_deferred_prop(item)) {
+
+ PyObject *py_func, *py_kw, *py_srna_cobject, *py_ret;
+
+ if (PyArg_ParseTuple(item, "OO!", &py_func, &PyDict_Type, &py_kw)) {
+ PyObject *args_fake;
+
+ if (*_PyUnicode_AsString(key) == '_') {
+ PyErr_Format(PyExc_ValueError,
+ "bpy_struct \"%.200s\" registration error: "
+ "%.200s could not register because the property starts with an '_'\n",
+ RNA_struct_identifier(srna),
+ _PyUnicode_AsString(key));
+ return -1;
+ }
+ py_srna_cobject = PyCapsule_New(srna, NULL, NULL);
+
+ /* not 100% nice :/, modifies the dict passed, should be ok */
+ PyDict_SetItem(py_kw, bpy_intern_str_attr, key);
+
+ args_fake = PyTuple_New(1);
+ PyTuple_SET_ITEM(args_fake, 0, py_srna_cobject);
+
+ PyObject *type = PyDict_GetItemString(py_kw, "type");
+ StructRNA *type_srna = srna_from_self(type, "");
+ if (type_srna) {
+ if (!RNA_struct_idprops_datablock_allowed(srna) &&
+ (*(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) == BPy_PointerProperty ||
+ *(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) ==
+ BPy_CollectionProperty) &&
+ RNA_struct_idprops_contains_datablock(type_srna)) {
+ PyErr_Format(PyExc_ValueError,
+ "bpy_struct \"%.200s\" doesn't support datablock properties\n",
+ RNA_struct_identifier(srna));
+ return -1;
+ }
+ }
+
+ py_ret = PyObject_Call(py_func, args_fake, py_kw);
+
+ if (py_ret) {
+ Py_DECREF(py_ret);
+ Py_DECREF(args_fake); /* free's py_srna_cobject too */
+ }
+ else {
+ /* _must_ print before decreffing args_fake */
+ PyErr_Print();
+ PyErr_Clear();
+
+ Py_DECREF(args_fake); /* free's py_srna_cobject too */
+
+ // PyC_LineSpit();
+ PyErr_Format(PyExc_ValueError,
+ "bpy_struct \"%.200s\" registration error: "
+ "%.200s could not register\n",
+ RNA_struct_identifier(srna),
+ _PyUnicode_AsString(key));
+ return -1;
+ }
+ }
+ else {
+ /* Since this is a class dict, ignore args that can't be passed */
+
+ /* for testing only */
#if 0
- PyC_ObSpit("Why doesn't this work??", item);
- PyErr_Print();
+ PyC_ObSpit("Why doesn't this work??", item);
+ PyErr_Print();
#endif
- PyErr_Clear();
- }
- }
+ PyErr_Clear();
+ }
+ }
- return 0;
+ return 0;
}
static int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
{
- PyObject *annotations_dict;
- PyObject *item, *key;
- Py_ssize_t pos = 0;
- int ret = 0;
-
- /* in both cases PyDict_CheckExact(class_dict) will be true even
- * though Operators have a metaclass dict namespace */
- if ((annotations_dict = PyDict_GetItem(class_dict, bpy_intern_str___annotations__)) &&
- PyDict_CheckExact(annotations_dict))
- {
- while (PyDict_Next(annotations_dict, &pos, &key, &item)) {
- ret = deferred_register_prop(srna, key, item);
-
- if (ret != 0) {
- break;
- }
- }
- }
-
- {
- /* This block can be removed once 2.8x is released and annotations are in use. */
- bool has_warning = false;
- while (PyDict_Next(class_dict, &pos, &key, &item)) {
- if (pyrna_is_deferred_prop(item)) {
- if (!has_warning) {
- printf("Warning: class %.200s "
- "contains a properties which should be an annotation!\n",
- RNA_struct_identifier(srna));
- PyC_LineSpit();
- has_warning = true;
- }
- printf(" make annotation: %.200s.%.200s\n",
- RNA_struct_identifier(srna), _PyUnicode_AsString(key));
- }
- ret = deferred_register_prop(srna, key, item);
-
- if (ret != 0) {
- break;
- }
- }
- }
-
- return ret;
+ PyObject *annotations_dict;
+ PyObject *item, *key;
+ Py_ssize_t pos = 0;
+ int ret = 0;
+
+ /* in both cases PyDict_CheckExact(class_dict) will be true even
+ * though Operators have a metaclass dict namespace */
+ if ((annotations_dict = PyDict_GetItem(class_dict, bpy_intern_str___annotations__)) &&
+ PyDict_CheckExact(annotations_dict)) {
+ while (PyDict_Next(annotations_dict, &pos, &key, &item)) {
+ ret = deferred_register_prop(srna, key, item);
+
+ if (ret != 0) {
+ break;
+ }
+ }
+ }
+
+ {
+ /* This block can be removed once 2.8x is released and annotations are in use. */
+ bool has_warning = false;
+ while (PyDict_Next(class_dict, &pos, &key, &item)) {
+ if (pyrna_is_deferred_prop(item)) {
+ if (!has_warning) {
+ printf(
+ "Warning: class %.200s "
+ "contains a properties which should be an annotation!\n",
+ RNA_struct_identifier(srna));
+ PyC_LineSpit();
+ has_warning = true;
+ }
+ printf(" make annotation: %.200s.%.200s\n",
+ RNA_struct_identifier(srna),
+ _PyUnicode_AsString(key));
+ }
+ ret = deferred_register_prop(srna, key, item);
+
+ if (ret != 0) {
+ break;
+ }
+ }
+ }
+
+ return ret;
}
static int pyrna_deferred_register_class_recursive(StructRNA *srna, PyTypeObject *py_class)
{
- const int len = PyTuple_GET_SIZE(py_class->tp_bases);
- int i, ret;
-
- /* first scan base classes for registerable properties */
- for (i = 0; i < len; i++) {
- PyTypeObject *py_superclass = (PyTypeObject *)PyTuple_GET_ITEM(py_class->tp_bases, i);
-
- /* the rules for using these base classes are not clear,
- * 'object' is of course not worth looking into and
- * existing subclasses of RNA would cause a lot more dictionary
- * looping then is needed (SomeOperator would scan Operator.__dict__)
- * which is harmless but not at all useful.
- *
- * So only scan base classes which are not subclasses if blender types.
- * This best fits having 'mix-in' classes for operators and render engines.
- */
- if (py_superclass != &PyBaseObject_Type &&
- !PyObject_IsSubclass((PyObject *)py_superclass, (PyObject *)&pyrna_struct_Type))
- {
- ret = pyrna_deferred_register_class_recursive(srna, py_superclass);
-
- if (ret != 0) {
- return ret;
- }
- }
- }
-
- /* not register out own properties */
- return pyrna_deferred_register_props(srna, py_class->tp_dict); /* getattr(..., "__dict__") returns a proxy */
+ const int len = PyTuple_GET_SIZE(py_class->tp_bases);
+ int i, ret;
+
+ /* first scan base classes for registerable properties */
+ for (i = 0; i < len; i++) {
+ PyTypeObject *py_superclass = (PyTypeObject *)PyTuple_GET_ITEM(py_class->tp_bases, i);
+
+ /* the rules for using these base classes are not clear,
+ * 'object' is of course not worth looking into and
+ * existing subclasses of RNA would cause a lot more dictionary
+ * looping then is needed (SomeOperator would scan Operator.__dict__)
+ * which is harmless but not at all useful.
+ *
+ * So only scan base classes which are not subclasses if blender types.
+ * This best fits having 'mix-in' classes for operators and render engines.
+ */
+ if (py_superclass != &PyBaseObject_Type &&
+ !PyObject_IsSubclass((PyObject *)py_superclass, (PyObject *)&pyrna_struct_Type)) {
+ ret = pyrna_deferred_register_class_recursive(srna, py_superclass);
+
+ if (ret != 0) {
+ return ret;
+ }
+ }
+ }
+
+ /* not register out own properties */
+ return pyrna_deferred_register_props(
+ srna, py_class->tp_dict); /* getattr(..., "__dict__") returns a proxy */
}
int pyrna_deferred_register_class(StructRNA *srna, PyTypeObject *py_class)
{
- /* Panels and Menus don't need this
- * save some time and skip the checks here */
- if (!RNA_struct_idprops_register_check(srna)) {
- return 0;
- }
+ /* Panels and Menus don't need this
+ * save some time and skip the checks here */
+ if (!RNA_struct_idprops_register_check(srna)) {
+ return 0;
+ }
- return pyrna_deferred_register_class_recursive(srna, py_class);
+ return pyrna_deferred_register_class_recursive(srna, py_class);
}
/*-------------------- Type Registration ------------------------*/
static int rna_function_arg_count(FunctionRNA *func, int *min_count)
{
- const ListBase *lb = RNA_function_defined_parameters(func);
- PropertyRNA *parm;
- Link *link;
- int flag = RNA_function_flag(func);
- const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
- int count = is_staticmethod ? 0 : 1;
- bool done_min_count = false;
-
- for (link = lb->first; link; link = link->next) {
- parm = (PropertyRNA *)link;
- if (!(RNA_parameter_flag(parm) & PARM_OUTPUT)) {
- if (!done_min_count && (RNA_parameter_flag(parm) & PARM_PYFUNC_OPTIONAL)) {
- /* From now on, following parameters are optional in py func */
- if (min_count) {
- *min_count = count;
- }
- done_min_count = true;
- }
- count++;
- }
- }
-
- if (!done_min_count && min_count) {
- *min_count = count;
- }
- return count;
-}
-
-static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, void *py_data, int *have_function)
-{
- const ListBase *lb;
- Link *link;
- const char *class_type = RNA_struct_identifier(srna);
- StructRNA *srna_base = RNA_struct_base(srna);
- PyObject *py_class = (PyObject *)py_data;
- PyObject *base_class = RNA_struct_py_type_get(srna);
- PyObject *item;
- int i, arg_count, func_arg_count, func_arg_min_count = 0;
- const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; /* __name__ */
-
- if (srna_base) {
- if (bpy_class_validate_recursive(dummyptr, srna_base, py_data, have_function) != 0) {
- return -1;
- }
- }
-
- if (base_class) {
- if (!PyObject_IsSubclass(py_class, base_class)) {
- PyErr_Format(PyExc_TypeError,
- "expected %.200s subclass of class \"%.200s\"",
- class_type, py_class_name);
- return -1;
- }
- }
-
- /* verify callback functions */
- lb = RNA_struct_type_functions(srna);
- i = 0;
- for (link = lb->first; link; link = link->next) {
- FunctionRNA *func = (FunctionRNA *)link;
- const int flag = RNA_function_flag(func);
- /* TODO(campbell): this is used for classmethod's too,
- * even though class methods should have 'FUNC_USE_SELF_TYPE' set, see Operator.poll for eg.
- * Keep this as-is since its working but we should be using 'FUNC_USE_SELF_TYPE' for many functions. */
- const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
-
- if (!(flag & FUNC_REGISTER)) {
- continue;
- }
-
- item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
-
- have_function[i] = (item != NULL);
- i++;
-
- if (item == NULL) {
- if ((flag & (FUNC_REGISTER_OPTIONAL & ~FUNC_REGISTER)) == 0) {
- PyErr_Format(PyExc_AttributeError,
- "expected %.200s, %.200s class to have an \"%.200s\" attribute",
- class_type, py_class_name,
- RNA_function_identifier(func));
- return -1;
- }
-
- PyErr_Clear();
- }
- else {
- Py_DECREF(item); /* no need to keep a ref, the class owns it (technically we should keep a ref but...) */
- if (is_staticmethod) {
- if (PyMethod_Check(item) == 0) {
- PyErr_Format(PyExc_TypeError,
- "expected %.200s, %.200s class \"%.200s\" "
- "attribute to be a static/class method, not a %.200s",
- class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
- return -1;
- }
- item = ((PyMethodObject *)item)->im_func;
- }
- else {
- if (PyFunction_Check(item) == 0) {
- PyErr_Format(PyExc_TypeError,
- "expected %.200s, %.200s class \"%.200s\" "
- "attribute to be a function, not a %.200s",
- class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
- return -1;
- }
- }
-
- func_arg_count = rna_function_arg_count(func, &func_arg_min_count);
-
- if (func_arg_count >= 0) { /* -1 if we don't care*/
- arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
-
- /* note, the number of args we check for and the number of args we give to
- * '@staticmethods' are different (quirk of python),
- * this is why rna_function_arg_count() doesn't return the value -1*/
- if (is_staticmethod) {
- func_arg_count++;
- func_arg_min_count++;
- }
-
- if (arg_count < func_arg_min_count || arg_count > func_arg_count) {
- if (func_arg_min_count != func_arg_count) {
- PyErr_Format(PyExc_ValueError,
- "expected %.200s, %.200s class \"%.200s\" function to have between %d and %d "
- "args, found %d",
- class_type, py_class_name, RNA_function_identifier(func),
- func_arg_count, func_arg_min_count, arg_count);
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "expected %.200s, %.200s class \"%.200s\" function to have %d args, found %d",
- class_type, py_class_name, RNA_function_identifier(func),
- func_arg_count, arg_count);
- }
- return -1;
- }
- }
- }
- }
-
- /* verify properties */
- lb = RNA_struct_type_properties(srna);
- for (link = lb->first; link; link = link->next) {
- const char *identifier;
- PropertyRNA *prop = (PropertyRNA *)link;
- const int flag = RNA_property_flag(prop);
-
- if (!(flag & PROP_REGISTER)) {
- continue;
- }
-
- /* TODO(campbell): Use Python3.7x _PyObject_LookupAttr(), also in the macro below. */
- identifier = RNA_property_identifier(prop);
- item = PyObject_GetAttrString(py_class, identifier);
-
- if (item == NULL) {
- PyErr_Clear();
- /* Sneaky workaround to use the class name as the bl_idname */
-
-#define BPY_REPLACEMENT_STRING(rna_attr, py_attr) \
- else if (STREQ(identifier, rna_attr)) { \
- if ((item = PyObject_GetAttr(py_class, py_attr))) { \
- if (item != Py_None) { \
- if (pyrna_py_to_prop(dummyptr, prop, NULL, \
- item, "validating class:") != 0) \
- { \
- Py_DECREF(item); \
- return -1; \
- } \
- } \
- Py_DECREF(item); \
- } \
- else { \
- PyErr_Clear(); \
- } \
- } /* intentionally allow else here */
-
- if (false) {} /* needed for macro */
- BPY_REPLACEMENT_STRING("bl_idname", bpy_intern_str___name__)
- BPY_REPLACEMENT_STRING("bl_description", bpy_intern_str___doc__)
-
-#undef BPY_REPLACEMENT_STRING
-
- if (item == NULL && (((flag & PROP_REGISTER_OPTIONAL) != PROP_REGISTER_OPTIONAL))) {
- PyErr_Format(PyExc_AttributeError,
- "expected %.200s, %.200s class to have an \"%.200s\" attribute",
- class_type, py_class_name, identifier);
- return -1;
- }
-
- PyErr_Clear();
- }
- else {
- if (pyrna_py_to_prop(dummyptr, prop, NULL, item, "validating class:") != 0) {
- Py_DECREF(item);
- return -1;
- }
- Py_DECREF(item);
- }
- }
-
- return 0;
+ const ListBase *lb = RNA_function_defined_parameters(func);
+ PropertyRNA *parm;
+ Link *link;
+ int flag = RNA_function_flag(func);
+ const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
+ int count = is_staticmethod ? 0 : 1;
+ bool done_min_count = false;
+
+ for (link = lb->first; link; link = link->next) {
+ parm = (PropertyRNA *)link;
+ if (!(RNA_parameter_flag(parm) & PARM_OUTPUT)) {
+ if (!done_min_count && (RNA_parameter_flag(parm) & PARM_PYFUNC_OPTIONAL)) {
+ /* From now on, following parameters are optional in py func */
+ if (min_count) {
+ *min_count = count;
+ }
+ done_min_count = true;
+ }
+ count++;
+ }
+ }
+
+ if (!done_min_count && min_count) {
+ *min_count = count;
+ }
+ return count;
+}
+
+static int bpy_class_validate_recursive(PointerRNA *dummyptr,
+ StructRNA *srna,
+ void *py_data,
+ int *have_function)
+{
+ const ListBase *lb;
+ Link *link;
+ const char *class_type = RNA_struct_identifier(srna);
+ StructRNA *srna_base = RNA_struct_base(srna);
+ PyObject *py_class = (PyObject *)py_data;
+ PyObject *base_class = RNA_struct_py_type_get(srna);
+ PyObject *item;
+ int i, arg_count, func_arg_count, func_arg_min_count = 0;
+ const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; /* __name__ */
+
+ if (srna_base) {
+ if (bpy_class_validate_recursive(dummyptr, srna_base, py_data, have_function) != 0) {
+ return -1;
+ }
+ }
+
+ if (base_class) {
+ if (!PyObject_IsSubclass(py_class, base_class)) {
+ PyErr_Format(PyExc_TypeError,
+ "expected %.200s subclass of class \"%.200s\"",
+ class_type,
+ py_class_name);
+ return -1;
+ }
+ }
+
+ /* verify callback functions */
+ lb = RNA_struct_type_functions(srna);
+ i = 0;
+ for (link = lb->first; link; link = link->next) {
+ FunctionRNA *func = (FunctionRNA *)link;
+ const int flag = RNA_function_flag(func);
+ /* TODO(campbell): this is used for classmethod's too,
+ * even though class methods should have 'FUNC_USE_SELF_TYPE' set, see Operator.poll for eg.
+ * Keep this as-is since its working but we should be using 'FUNC_USE_SELF_TYPE' for many functions. */
+ const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
+
+ if (!(flag & FUNC_REGISTER)) {
+ continue;
+ }
+
+ item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
+
+ have_function[i] = (item != NULL);
+ i++;
+
+ if (item == NULL) {
+ if ((flag & (FUNC_REGISTER_OPTIONAL & ~FUNC_REGISTER)) == 0) {
+ PyErr_Format(PyExc_AttributeError,
+ "expected %.200s, %.200s class to have an \"%.200s\" attribute",
+ class_type,
+ py_class_name,
+ RNA_function_identifier(func));
+ return -1;
+ }
+
+ PyErr_Clear();
+ }
+ else {
+ Py_DECREF(
+ item); /* no need to keep a ref, the class owns it (technically we should keep a ref but...) */
+ if (is_staticmethod) {
+ if (PyMethod_Check(item) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "expected %.200s, %.200s class \"%.200s\" "
+ "attribute to be a static/class method, not a %.200s",
+ class_type,
+ py_class_name,
+ RNA_function_identifier(func),
+ Py_TYPE(item)->tp_name);
+ return -1;
+ }
+ item = ((PyMethodObject *)item)->im_func;
+ }
+ else {
+ if (PyFunction_Check(item) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "expected %.200s, %.200s class \"%.200s\" "
+ "attribute to be a function, not a %.200s",
+ class_type,
+ py_class_name,
+ RNA_function_identifier(func),
+ Py_TYPE(item)->tp_name);
+ return -1;
+ }
+ }
+
+ func_arg_count = rna_function_arg_count(func, &func_arg_min_count);
+
+ if (func_arg_count >= 0) { /* -1 if we don't care*/
+ arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
+
+ /* note, the number of args we check for and the number of args we give to
+ * '@staticmethods' are different (quirk of python),
+ * this is why rna_function_arg_count() doesn't return the value -1*/
+ if (is_staticmethod) {
+ func_arg_count++;
+ func_arg_min_count++;
+ }
+
+ if (arg_count < func_arg_min_count || arg_count > func_arg_count) {
+ if (func_arg_min_count != func_arg_count) {
+ PyErr_Format(
+ PyExc_ValueError,
+ "expected %.200s, %.200s class \"%.200s\" function to have between %d and %d "
+ "args, found %d",
+ class_type,
+ py_class_name,
+ RNA_function_identifier(func),
+ func_arg_count,
+ func_arg_min_count,
+ arg_count);
+ }
+ else {
+ PyErr_Format(
+ PyExc_ValueError,
+ "expected %.200s, %.200s class \"%.200s\" function to have %d args, found %d",
+ class_type,
+ py_class_name,
+ RNA_function_identifier(func),
+ func_arg_count,
+ arg_count);
+ }
+ return -1;
+ }
+ }
+ }
+ }
+
+ /* verify properties */
+ lb = RNA_struct_type_properties(srna);
+ for (link = lb->first; link; link = link->next) {
+ const char *identifier;
+ PropertyRNA *prop = (PropertyRNA *)link;
+ const int flag = RNA_property_flag(prop);
+
+ if (!(flag & PROP_REGISTER)) {
+ continue;
+ }
+
+ /* TODO(campbell): Use Python3.7x _PyObject_LookupAttr(), also in the macro below. */
+ identifier = RNA_property_identifier(prop);
+ item = PyObject_GetAttrString(py_class, identifier);
+
+ if (item == NULL) {
+ PyErr_Clear();
+ /* Sneaky workaround to use the class name as the bl_idname */
+
+#define BPY_REPLACEMENT_STRING(rna_attr, py_attr) \
+ else if (STREQ(identifier, rna_attr)) \
+ { \
+ if ((item = PyObject_GetAttr(py_class, py_attr))) { \
+ if (item != Py_None) { \
+ if (pyrna_py_to_prop(dummyptr, prop, NULL, item, "validating class:") != 0) { \
+ Py_DECREF(item); \
+ return -1; \
+ } \
+ } \
+ Py_DECREF(item); \
+ } \
+ else { \
+ PyErr_Clear(); \
+ } \
+ } /* intentionally allow else here */
+
+ if (false) {
+ } /* needed for macro */
+ BPY_REPLACEMENT_STRING("bl_idname", bpy_intern_str___name__)
+ BPY_REPLACEMENT_STRING("bl_description", bpy_intern_str___doc__)
+
+#undef BPY_REPLACEMENT_STRING
+
+ if (item == NULL && (((flag & PROP_REGISTER_OPTIONAL) != PROP_REGISTER_OPTIONAL))) {
+ PyErr_Format(PyExc_AttributeError,
+ "expected %.200s, %.200s class to have an \"%.200s\" attribute",
+ class_type,
+ py_class_name,
+ identifier);
+ return -1;
+ }
+
+ PyErr_Clear();
+ }
+ else {
+ if (pyrna_py_to_prop(dummyptr, prop, NULL, item, "validating class:") != 0) {
+ Py_DECREF(item);
+ return -1;
+ }
+ Py_DECREF(item);
+ }
+ }
+
+ return 0;
}
static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
{
- return bpy_class_validate_recursive(dummyptr, dummyptr->type, py_data, have_function);
+ return bpy_class_validate_recursive(dummyptr, dummyptr->type, py_data, have_function);
}
/* TODO - multiple return values like with rna functions */
static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
{
- PyObject *args;
- PyObject *ret = NULL, *py_srna = NULL, *py_class_instance = NULL, *parmitem;
- PyTypeObject *py_class;
- PropertyRNA *parm;
- ParameterIterator iter;
- PointerRNA funcptr;
- int err = 0, i, ret_len = 0, arg_count;
- int flag = RNA_function_flag(func);
- const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
- const bool is_classmethod = (flag & FUNC_NO_SELF) && (flag & FUNC_USE_SELF_TYPE);
+ PyObject *args;
+ PyObject *ret = NULL, *py_srna = NULL, *py_class_instance = NULL, *parmitem;
+ PyTypeObject *py_class;
+ PropertyRNA *parm;
+ ParameterIterator iter;
+ PointerRNA funcptr;
+ int err = 0, i, ret_len = 0, arg_count;
+ int flag = RNA_function_flag(func);
+ const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
+ const bool is_classmethod = (flag & FUNC_NO_SELF) && (flag & FUNC_USE_SELF_TYPE);
- PropertyRNA *pret_single = NULL;
- void *retdata_single = NULL;
+ PropertyRNA *pret_single = NULL;
+ void *retdata_single = NULL;
- PyGILState_STATE gilstate;
+ PyGILState_STATE gilstate;
#ifdef USE_PEDANTIC_WRITE
- const bool is_readonly_init = !(RNA_struct_is_a(ptr->type, &RNA_Operator) ||
- RNA_struct_is_a(ptr->type, &RNA_Gizmo));
- // const char *func_id = RNA_function_identifier(func); /* UNUSED */
- /* testing, for correctness, not operator and not draw function */
- const bool is_readonly = !(RNA_function_flag(func) & FUNC_ALLOW_WRITE);
+ const bool is_readonly_init = !(RNA_struct_is_a(ptr->type, &RNA_Operator) ||
+ RNA_struct_is_a(ptr->type, &RNA_Gizmo));
+ // const char *func_id = RNA_function_identifier(func); /* UNUSED */
+ /* testing, for correctness, not operator and not draw function */
+ const bool is_readonly = !(RNA_function_flag(func) & FUNC_ALLOW_WRITE);
#endif
- py_class = RNA_struct_py_type_get(ptr->type);
- /* rare case. can happen when registering subclasses */
- if (py_class == NULL) {
- CLOG_WARN(BPY_LOG_RNA, "unable to get Python class for rna struct '%.200s'", RNA_struct_identifier(ptr->type));
- return -1;
- }
-
- /* XXX, this is needed because render engine calls without a context
- * this should be supported at some point but at the moment its not! */
- if (C == NULL) {
- C = BPy_GetContext();
- }
-
- /* annoying!, need to check if the screen gets set to NULL which is a
- * hint that the file was actually re-loaded. */
- const bool is_valid_wm = (CTX_wm_manager(C) != NULL);
-
- bpy_context_set(C, &gilstate);
-
- if (!(is_staticmethod || is_classmethod)) {
- /* some datatypes (operator, render engine) can store PyObjects for re-use */
- if (ptr->data) {
- void **instance = RNA_struct_instance(ptr);
-
- if (instance) {
- if (*instance) {
- py_class_instance = *instance;
- Py_INCREF(py_class_instance);
- }
- }
- }
- /* end exception */
-
- if (py_class_instance == NULL) {
- py_srna = pyrna_struct_CreatePyObject(ptr);
- }
-
- if (py_class_instance) {
- /* special case, instance is cached */
- }
- else if (py_srna == NULL) {
- py_class_instance = NULL;
- }
- else if (py_srna == Py_None) { /* probably wont ever happen but possible */
- Py_DECREF(py_srna);
- py_class_instance = NULL;
- }
- else {
+ py_class = RNA_struct_py_type_get(ptr->type);
+ /* rare case. can happen when registering subclasses */
+ if (py_class == NULL) {
+ CLOG_WARN(BPY_LOG_RNA,
+ "unable to get Python class for rna struct '%.200s'",
+ RNA_struct_identifier(ptr->type));
+ return -1;
+ }
+
+ /* XXX, this is needed because render engine calls without a context
+ * this should be supported at some point but at the moment its not! */
+ if (C == NULL) {
+ C = BPy_GetContext();
+ }
+
+ /* annoying!, need to check if the screen gets set to NULL which is a
+ * hint that the file was actually re-loaded. */
+ const bool is_valid_wm = (CTX_wm_manager(C) != NULL);
+
+ bpy_context_set(C, &gilstate);
+
+ if (!(is_staticmethod || is_classmethod)) {
+ /* some datatypes (operator, render engine) can store PyObjects for re-use */
+ if (ptr->data) {
+ void **instance = RNA_struct_instance(ptr);
+
+ if (instance) {
+ if (*instance) {
+ py_class_instance = *instance;
+ Py_INCREF(py_class_instance);
+ }
+ }
+ }
+ /* end exception */
+
+ if (py_class_instance == NULL) {
+ py_srna = pyrna_struct_CreatePyObject(ptr);
+ }
+
+ if (py_class_instance) {
+ /* special case, instance is cached */
+ }
+ else if (py_srna == NULL) {
+ py_class_instance = NULL;
+ }
+ else if (py_srna == Py_None) { /* probably wont ever happen but possible */
+ Py_DECREF(py_srna);
+ py_class_instance = NULL;
+ }
+ else {
#if 1
- /* Skip the code below and call init directly on the allocated 'py_srna'
- * otherwise __init__() always needs to take a second self argument, see pyrna_struct_new().
- * Although this is annoying to have to implement a part of pythons typeobject.c:type_call().
- */
- if (py_class->tp_init) {
-#ifdef USE_PEDANTIC_WRITE
- const int prev_write = rna_disallow_writes;
- rna_disallow_writes = is_readonly_init ? false : true; /* only operators can write on __init__ */
-#endif
-
- /* true in most cases even when the class its self doesn't define an __init__ function. */
- args = PyTuple_New(0);
- if (py_class->tp_init(py_srna, args, NULL) < 0) {
- Py_DECREF(py_srna);
- py_srna = NULL;
- /* err set below */
- }
- Py_DECREF(args);
-#ifdef USE_PEDANTIC_WRITE
- rna_disallow_writes = prev_write;
-#endif
- }
- py_class_instance = py_srna;
+ /* Skip the code below and call init directly on the allocated 'py_srna'
+ * otherwise __init__() always needs to take a second self argument, see pyrna_struct_new().
+ * Although this is annoying to have to implement a part of pythons typeobject.c:type_call().
+ */
+ if (py_class->tp_init) {
+# ifdef USE_PEDANTIC_WRITE
+ const int prev_write = rna_disallow_writes;
+ rna_disallow_writes = is_readonly_init ? false :
+ true; /* only operators can write on __init__ */
+# endif
+
+ /* true in most cases even when the class its self doesn't define an __init__ function. */
+ args = PyTuple_New(0);
+ if (py_class->tp_init(py_srna, args, NULL) < 0) {
+ Py_DECREF(py_srna);
+ py_srna = NULL;
+ /* err set below */
+ }
+ Py_DECREF(args);
+# ifdef USE_PEDANTIC_WRITE
+ rna_disallow_writes = prev_write;
+# endif
+ }
+ py_class_instance = py_srna;
#else
- const int prev_write = rna_disallow_writes;
- rna_disallow_writes = true;
-
- /* 'almost' all the time calling the class isn't needed.
- * We could just do... */
-#if 0
- py_class_instance = py_srna;
- Py_INCREF(py_class_instance);
-#endif
- /*
- * This would work fine but means __init__ functions wouldn't run.
- * none of blenders default scripts use __init__ but its nice to call it
- * for general correctness. just to note why this is here when it could be safely removed.
- */
- args = PyTuple_New(1);
- PyTuple_SET_ITEM(args, 0, py_srna);
- py_class_instance = PyObject_Call(py_class, args, NULL);
- Py_DECREF(args);
-
- rna_disallow_writes = prev_write;
+ const int prev_write = rna_disallow_writes;
+ rna_disallow_writes = true;
+
+ /* 'almost' all the time calling the class isn't needed.
+ * We could just do... */
+# if 0
+ py_class_instance = py_srna;
+ Py_INCREF(py_class_instance);
+# endif
+ /*
+ * This would work fine but means __init__ functions wouldn't run.
+ * none of blenders default scripts use __init__ but its nice to call it
+ * for general correctness. just to note why this is here when it could be safely removed.
+ */
+ args = PyTuple_New(1);
+ PyTuple_SET_ITEM(args, 0, py_srna);
+ py_class_instance = PyObject_Call(py_class, args, NULL);
+ Py_DECREF(args);
+
+ rna_disallow_writes = prev_write;
#endif
- if (py_class_instance == NULL) {
- err = -1; /* so the error is not overridden below */
- }
- }
- }
-
- /* Initializing the class worked, now run its invoke function */
- if (err != -1 && (is_staticmethod || is_classmethod || py_class_instance)) {
- PyObject *item = PyObject_GetAttrString((PyObject *)py_class, RNA_function_identifier(func));
-
- if (item) {
- RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
-
- if (is_staticmethod) {
- arg_count = ((PyCodeObject *)PyFunction_GET_CODE(((PyMethodObject *)item)->im_func))->co_argcount - 1;
- }
- else {
- arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
- }
-// args = PyTuple_New(rna_function_arg_count(func)); /* first arg is included in 'item' */
- args = PyTuple_New(arg_count); /* first arg is included in 'item' */
-
-
- if (is_staticmethod) {
- i = 0;
- }
- else if (is_classmethod) {
- PyTuple_SET_ITEM(args, 0, (PyObject *)py_class);
- i = 1;
- }
- else {
- PyTuple_SET_ITEM(args, 0, py_class_instance);
- i = 1;
- }
-
- RNA_parameter_list_begin(parms, &iter);
-
- /* parse function parameters */
- for (; iter.valid; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
-
- /* only useful for single argument returns, we'll need another list loop for multiple */
- if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
- ret_len++;
- if (pret_single == NULL) {
- pret_single = parm;
- retdata_single = iter.data;
- }
-
- continue;
- }
-
- if (i < arg_count) {
- parmitem = pyrna_param_to_py(&funcptr, parm, iter.data);
- PyTuple_SET_ITEM(args, i, parmitem);
- i++;
- }
- }
+ if (py_class_instance == NULL) {
+ err = -1; /* so the error is not overridden below */
+ }
+ }
+ }
+
+ /* Initializing the class worked, now run its invoke function */
+ if (err != -1 && (is_staticmethod || is_classmethod || py_class_instance)) {
+ PyObject *item = PyObject_GetAttrString((PyObject *)py_class, RNA_function_identifier(func));
+
+ if (item) {
+ RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
+
+ if (is_staticmethod) {
+ arg_count =
+ ((PyCodeObject *)PyFunction_GET_CODE(((PyMethodObject *)item)->im_func))->co_argcount -
+ 1;
+ }
+ else {
+ arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
+ }
+ // args = PyTuple_New(rna_function_arg_count(func)); /* first arg is included in 'item' */
+ args = PyTuple_New(arg_count); /* first arg is included in 'item' */
+
+ if (is_staticmethod) {
+ i = 0;
+ }
+ else if (is_classmethod) {
+ PyTuple_SET_ITEM(args, 0, (PyObject *)py_class);
+ i = 1;
+ }
+ else {
+ PyTuple_SET_ITEM(args, 0, py_class_instance);
+ i = 1;
+ }
+
+ RNA_parameter_list_begin(parms, &iter);
+
+ /* parse function parameters */
+ for (; iter.valid; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+
+ /* only useful for single argument returns, we'll need another list loop for multiple */
+ if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
+ ret_len++;
+ if (pret_single == NULL) {
+ pret_single = parm;
+ retdata_single = iter.data;
+ }
+
+ continue;
+ }
+
+ if (i < arg_count) {
+ parmitem = pyrna_param_to_py(&funcptr, parm, iter.data);
+ PyTuple_SET_ITEM(args, i, parmitem);
+ i++;
+ }
+ }
#ifdef USE_PEDANTIC_WRITE
- rna_disallow_writes = is_readonly ? true : false;
+ rna_disallow_writes = is_readonly ? true : false;
#endif
- /* *** Main Caller *** */
+ /* *** Main Caller *** */
- ret = PyObject_Call(item, args, NULL);
+ ret = PyObject_Call(item, args, NULL);
- /* *** Done Calling *** */
+ /* *** Done Calling *** */
#ifdef USE_PEDANTIC_WRITE
- rna_disallow_writes = false;
+ rna_disallow_writes = false;
#endif
- RNA_parameter_list_end(&iter);
- Py_DECREF(item);
- Py_DECREF(args);
- }
- else {
- PyErr_Print();
- PyErr_Clear();
- PyErr_Format(PyExc_TypeError,
- "could not find function %.200s in %.200s to execute callback",
- RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
- err = -1;
- }
- }
- else {
- /* the error may be already set if the class instance couldn't be created */
- if (err != -1) {
- PyErr_Format(PyExc_RuntimeError,
- "could not create instance of %.200s to call callback function %.200s",
- RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
- err = -1;
- }
- }
-
- if (ret == NULL) { /* covers py_class_instance failing too */
- err = -1;
- }
- else {
- if (ret_len == 0 && ret != Py_None) {
- PyErr_Format(PyExc_RuntimeError,
- "expected class %.200s, function %.200s to return None, not %.200s",
- RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
- Py_TYPE(ret)->tp_name);
- err = -1;
- }
- else if (ret_len == 1) {
- err = pyrna_py_to_prop(&funcptr, pret_single, retdata_single, ret, "");
-
- /* when calling operator funcs only gives Function.result with
- * no line number since the func has finished calling on error,
- * re-raise the exception with more info since it would be slow to
- * create prefix on every call (when there are no errors) */
- if (err == -1) {
- PyC_Err_Format_Prefix(PyExc_RuntimeError,
- "class %.200s, function %.200s: incompatible return value ",
- RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
- }
- }
- else if (ret_len > 1) {
-
- if (PyTuple_Check(ret) == 0) {
- PyErr_Format(PyExc_RuntimeError,
- "expected class %.200s, function %.200s to return a tuple of size %d, not %.200s",
- RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
- ret_len, Py_TYPE(ret)->tp_name);
- err = -1;
- }
- else if (PyTuple_GET_SIZE(ret) != ret_len) {
- PyErr_Format(PyExc_RuntimeError,
- "class %.200s, function %.200s to returned %d items, expected %d",
- RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
- PyTuple_GET_SIZE(ret), ret_len);
- err = -1;
- }
- else {
-
- RNA_parameter_list_begin(parms, &iter);
-
- /* parse function parameters */
- for (i = 0; iter.valid; RNA_parameter_list_next(&iter)) {
- parm = iter.parm;
-
- /* only useful for single argument returns, we'll need another list loop for multiple */
- if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
- err = pyrna_py_to_prop(&funcptr, parm, iter.data,
- PyTuple_GET_ITEM(ret, i++),
- "calling class function:");
- if (err) {
- break;
- }
- }
- }
-
- RNA_parameter_list_end(&iter);
- }
- }
- Py_DECREF(ret);
- }
-
- if (err != 0) {
- ReportList *reports;
- /* alert the user, else they wont know unless they see the console. */
- if ((!is_staticmethod) && (!is_classmethod) &&
- (ptr->data) &&
- (RNA_struct_is_a(ptr->type, &RNA_Operator)) &&
- (is_valid_wm == (CTX_wm_manager(C) != NULL)))
- {
- wmOperator *op = ptr->data;
- reports = op->reports;
- }
- else {
- /* wont alert users but they can view in 'info' space */
- reports = CTX_wm_reports(C);
- }
-
- BPy_errors_to_report(reports);
-
- /* also print in the console for py */
- PyErr_Print();
- PyErr_Clear();
- }
-
- bpy_context_clear(C, &gilstate);
-
- return err;
+ RNA_parameter_list_end(&iter);
+ Py_DECREF(item);
+ Py_DECREF(args);
+ }
+ else {
+ PyErr_Print();
+ PyErr_Clear();
+ PyErr_Format(PyExc_TypeError,
+ "could not find function %.200s in %.200s to execute callback",
+ RNA_function_identifier(func),
+ RNA_struct_identifier(ptr->type));
+ err = -1;
+ }
+ }
+ else {
+ /* the error may be already set if the class instance couldn't be created */
+ if (err != -1) {
+ PyErr_Format(PyExc_RuntimeError,
+ "could not create instance of %.200s to call callback function %.200s",
+ RNA_struct_identifier(ptr->type),
+ RNA_function_identifier(func));
+ err = -1;
+ }
+ }
+
+ if (ret == NULL) { /* covers py_class_instance failing too */
+ err = -1;
+ }
+ else {
+ if (ret_len == 0 && ret != Py_None) {
+ PyErr_Format(PyExc_RuntimeError,
+ "expected class %.200s, function %.200s to return None, not %.200s",
+ RNA_struct_identifier(ptr->type),
+ RNA_function_identifier(func),
+ Py_TYPE(ret)->tp_name);
+ err = -1;
+ }
+ else if (ret_len == 1) {
+ err = pyrna_py_to_prop(&funcptr, pret_single, retdata_single, ret, "");
+
+ /* when calling operator funcs only gives Function.result with
+ * no line number since the func has finished calling on error,
+ * re-raise the exception with more info since it would be slow to
+ * create prefix on every call (when there are no errors) */
+ if (err == -1) {
+ PyC_Err_Format_Prefix(PyExc_RuntimeError,
+ "class %.200s, function %.200s: incompatible return value ",
+ RNA_struct_identifier(ptr->type),
+ RNA_function_identifier(func));
+ }
+ }
+ else if (ret_len > 1) {
+
+ if (PyTuple_Check(ret) == 0) {
+ PyErr_Format(
+ PyExc_RuntimeError,
+ "expected class %.200s, function %.200s to return a tuple of size %d, not %.200s",
+ RNA_struct_identifier(ptr->type),
+ RNA_function_identifier(func),
+ ret_len,
+ Py_TYPE(ret)->tp_name);
+ err = -1;
+ }
+ else if (PyTuple_GET_SIZE(ret) != ret_len) {
+ PyErr_Format(PyExc_RuntimeError,
+ "class %.200s, function %.200s to returned %d items, expected %d",
+ RNA_struct_identifier(ptr->type),
+ RNA_function_identifier(func),
+ PyTuple_GET_SIZE(ret),
+ ret_len);
+ err = -1;
+ }
+ else {
+
+ RNA_parameter_list_begin(parms, &iter);
+
+ /* parse function parameters */
+ for (i = 0; iter.valid; RNA_parameter_list_next(&iter)) {
+ parm = iter.parm;
+
+ /* only useful for single argument returns, we'll need another list loop for multiple */
+ if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
+ err = pyrna_py_to_prop(
+ &funcptr, parm, iter.data, PyTuple_GET_ITEM(ret, i++), "calling class function:");
+ if (err) {
+ break;
+ }
+ }
+ }
+
+ RNA_parameter_list_end(&iter);
+ }
+ }
+ Py_DECREF(ret);
+ }
+
+ if (err != 0) {
+ ReportList *reports;
+ /* alert the user, else they wont know unless they see the console. */
+ if ((!is_staticmethod) && (!is_classmethod) && (ptr->data) &&
+ (RNA_struct_is_a(ptr->type, &RNA_Operator)) &&
+ (is_valid_wm == (CTX_wm_manager(C) != NULL))) {
+ wmOperator *op = ptr->data;
+ reports = op->reports;
+ }
+ else {
+ /* wont alert users but they can view in 'info' space */
+ reports = CTX_wm_reports(C);
+ }
+
+ BPy_errors_to_report(reports);
+
+ /* also print in the console for py */
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ bpy_context_clear(C, &gilstate);
+
+ return err;
}
static void bpy_class_free(void *pyob_ptr)
{
- PyObject *self = (PyObject *)pyob_ptr;
- PyGILState_STATE gilstate;
+ PyObject *self = (PyObject *)pyob_ptr;
+ PyGILState_STATE gilstate;
- gilstate = PyGILState_Ensure();
+ gilstate = PyGILState_Ensure();
- /* breaks re-registering classes */
- // PyDict_Clear(((PyTypeObject *)self)->tp_dict);
+ /* breaks re-registering classes */
+ // PyDict_Clear(((PyTypeObject *)self)->tp_dict);
- /* remove the rna attribute instead. */
- PyDict_DelItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
- if (PyErr_Occurred()) {
- PyErr_Clear();
- }
+ /* remove the rna attribute instead. */
+ PyDict_DelItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
+ if (PyErr_Occurred()) {
+ PyErr_Clear();
+ }
#if 0 /* needs further investigation, too annoying so quiet for now */
- if (G.debug & G_DEBUG_PYTHON) {
- if (self->ob_refcnt > 1) {
- PyC_ObSpit("zombie class - ref should be 1", self);
- }
- }
+ if (G.debug & G_DEBUG_PYTHON) {
+ if (self->ob_refcnt > 1) {
+ PyC_ObSpit("zombie class - ref should be 1", self);
+ }
+ }
#endif
- Py_DECREF((PyObject *)pyob_ptr);
+ Py_DECREF((PyObject *)pyob_ptr);
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
}
/**
@@ -8241,61 +8398,56 @@ static void bpy_class_free(void *pyob_ptr)
void pyrna_alloc_types(void)
{
#ifdef DEBUG
- PyGILState_STATE gilstate;
+ PyGILState_STATE gilstate;
- PointerRNA ptr;
- PropertyRNA *prop;
+ PointerRNA ptr;
+ PropertyRNA *prop;
- gilstate = PyGILState_Ensure();
+ gilstate = PyGILState_Ensure();
- /* avoid doing this lookup for every getattr */
- RNA_blender_rna_pointer_create(&ptr);
- prop = RNA_struct_find_property(&ptr, "structs");
+ /* avoid doing this lookup for every getattr */
+ RNA_blender_rna_pointer_create(&ptr);
+ prop = RNA_struct_find_property(&ptr, "structs");
- RNA_PROP_BEGIN (&ptr, itemptr, prop)
- {
- PyObject *item = pyrna_struct_Subtype(&itemptr);
- if (item == NULL) {
- if (PyErr_Occurred()) {
- PyErr_Print();
- PyErr_Clear();
- }
- }
- else {
- Py_DECREF(item);
- }
- }
- RNA_PROP_END;
+ RNA_PROP_BEGIN (&ptr, itemptr, prop) {
+ PyObject *item = pyrna_struct_Subtype(&itemptr);
+ if (item == NULL) {
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
+ else {
+ Py_DECREF(item);
+ }
+ }
+ RNA_PROP_END;
- PyGILState_Release(gilstate);
-#endif /* DEBUG */
+ PyGILState_Release(gilstate);
+#endif /* DEBUG */
}
-
void pyrna_free_types(void)
{
- PointerRNA ptr;
- PropertyRNA *prop;
-
- /* avoid doing this lookup for every getattr */
- RNA_blender_rna_pointer_create(&ptr);
- prop = RNA_struct_find_property(&ptr, "structs");
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ /* avoid doing this lookup for every getattr */
+ RNA_blender_rna_pointer_create(&ptr);
+ prop = RNA_struct_find_property(&ptr, "structs");
- RNA_PROP_BEGIN (&ptr, itemptr, prop)
- {
- StructRNA *srna = srna_from_ptr(&itemptr);
- void *py_ptr = RNA_struct_py_type_get(srna);
+ RNA_PROP_BEGIN (&ptr, itemptr, prop) {
+ StructRNA *srna = srna_from_ptr(&itemptr);
+ void *py_ptr = RNA_struct_py_type_get(srna);
- if (py_ptr) {
-#if 0 /* XXX - should be able to do this but makes python crash on exit */
- bpy_class_free(py_ptr);
+ if (py_ptr) {
+#if 0 /* XXX - should be able to do this but makes python crash on exit */
+ bpy_class_free(py_ptr);
#endif
- RNA_struct_py_type_set(srna, NULL);
- }
- }
- RNA_PROP_END;
-
+ RNA_struct_py_type_set(srna, NULL);
+ }
+ }
+ RNA_PROP_END;
}
/* Note! MemLeak XXX
@@ -8308,401 +8460,429 @@ void pyrna_free_types(void)
* - Should still be fixed - Campbell
* */
PyDoc_STRVAR(pyrna_register_class_doc,
-".. method:: register_class(cls)\n"
-"\n"
-" Register a subclass of a blender type in (:class:`bpy.types.Panel`,\n"
-" :class:`bpy.types.UIList`, :class:`bpy.types.Menu`, :class:`bpy.types.Header`,\n"
-" :class:`bpy.types.Operator`, :class:`bpy.types.KeyingSetInfo`,\n"
-" :class:`bpy.types.RenderEngine`).\n"
-"\n"
-" If the class has a *register* class method it will be called\n"
-" before registration.\n"
-"\n"
-" .. note::\n"
-"\n"
-" :exc:`ValueError` exception is raised if the class is not a\n"
-" subclass of a registerable blender class.\n"
-"\n"
-);
-PyMethodDef meth_bpy_register_class = {"register_class", pyrna_register_class, METH_O, pyrna_register_class_doc};
+ ".. method:: register_class(cls)\n"
+ "\n"
+ " Register a subclass of a blender type in (:class:`bpy.types.Panel`,\n"
+ " :class:`bpy.types.UIList`, :class:`bpy.types.Menu`, :class:`bpy.types.Header`,\n"
+ " :class:`bpy.types.Operator`, :class:`bpy.types.KeyingSetInfo`,\n"
+ " :class:`bpy.types.RenderEngine`).\n"
+ "\n"
+ " If the class has a *register* class method it will be called\n"
+ " before registration.\n"
+ "\n"
+ " .. note::\n"
+ "\n"
+ " :exc:`ValueError` exception is raised if the class is not a\n"
+ " subclass of a registerable blender class.\n"
+ "\n");
+PyMethodDef meth_bpy_register_class = {
+ "register_class", pyrna_register_class, METH_O, pyrna_register_class_doc};
static PyObject *pyrna_register_class(PyObject *UNUSED(self), PyObject *py_class)
{
- bContext *C = NULL;
- ReportList reports;
- StructRegisterFunc reg;
- StructRNA *srna;
- StructRNA *srna_new;
- const char *identifier;
- PyObject *py_cls_meth;
- const char *error_prefix = "register_class(...):";
-
- if (!PyType_Check(py_class)) {
- PyErr_Format(PyExc_ValueError,
- "register_class(...): "
- "expected a class argument, not '%.200s'", Py_TYPE(py_class)->tp_name);
- return NULL;
- }
-
- if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna)) {
- PyErr_SetString(PyExc_ValueError,
- "register_class(...): "
- "already registered as a subclass");
- return NULL;
- }
-
- if (!pyrna_write_check()) {
- PyErr_Format(PyExc_RuntimeError,
- "register_class(...): "
- "can't run in readonly state '%.200s'",
- ((PyTypeObject *)py_class)->tp_name);
- return NULL;
- }
-
- /* warning: gets parent classes srna, only for the register function */
- srna = pyrna_struct_as_srna(py_class, true, "register_class(...):");
- if (srna == NULL) {
- return NULL;
- }
-
- /* fails in cases, cant use this check but would like to :| */
+ bContext *C = NULL;
+ ReportList reports;
+ StructRegisterFunc reg;
+ StructRNA *srna;
+ StructRNA *srna_new;
+ const char *identifier;
+ PyObject *py_cls_meth;
+ const char *error_prefix = "register_class(...):";
+
+ if (!PyType_Check(py_class)) {
+ PyErr_Format(PyExc_ValueError,
+ "register_class(...): "
+ "expected a class argument, not '%.200s'",
+ Py_TYPE(py_class)->tp_name);
+ return NULL;
+ }
+
+ if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna)) {
+ PyErr_SetString(PyExc_ValueError,
+ "register_class(...): "
+ "already registered as a subclass");
+ return NULL;
+ }
+
+ if (!pyrna_write_check()) {
+ PyErr_Format(PyExc_RuntimeError,
+ "register_class(...): "
+ "can't run in readonly state '%.200s'",
+ ((PyTypeObject *)py_class)->tp_name);
+ return NULL;
+ }
+
+ /* warning: gets parent classes srna, only for the register function */
+ srna = pyrna_struct_as_srna(py_class, true, "register_class(...):");
+ if (srna == NULL) {
+ return NULL;
+ }
+
+ /* fails in cases, cant use this check but would like to :| */
#if 0
- if (RNA_struct_py_type_get(srna)) {
- PyErr_Format(PyExc_ValueError,
- "register_class(...): %.200s's parent class %.200s is already registered, this is not allowed",
- ((PyTypeObject *)py_class)->tp_name, RNA_struct_identifier(srna));
- return NULL;
- }
+ if (RNA_struct_py_type_get(srna)) {
+ PyErr_Format(PyExc_ValueError,
+ "register_class(...): %.200s's parent class %.200s is already registered, this is not allowed",
+ ((PyTypeObject *)py_class)->tp_name, RNA_struct_identifier(srna));
+ return NULL;
+ }
#endif
- /* check that we have a register callback for this type */
- reg = RNA_struct_register(srna);
-
- if (!reg) {
- PyErr_Format(PyExc_ValueError,
- "register_class(...): expected a subclass of a registerable "
- "rna type (%.200s does not support registration)",
- RNA_struct_identifier(srna));
- return NULL;
- }
-
- /* get the context, so register callback can do necessary refreshes */
- C = BPy_GetContext();
-
- /* call the register callback with reports & identifier */
- BKE_reports_init(&reports, RPT_STORE);
-
- identifier = ((PyTypeObject *)py_class)->tp_name;
-
- srna_new = reg(CTX_data_main(C), &reports, py_class, identifier,
- bpy_class_validate, bpy_class_call, bpy_class_free);
-
- if (!BLI_listbase_is_empty(&reports.list)) {
- const bool has_error = BPy_reports_to_error(&reports, PyExc_RuntimeError, false);
- if (!has_error) {
- BPy_reports_write_stdout(&reports, error_prefix);
- }
- BKE_reports_clear(&reports);
- if (has_error) {
- return NULL;
- }
- }
-
- /* python errors validating are not converted into reports so the check above will fail.
- * the cause for returning NULL will be printed as an error */
- if (srna_new == NULL) {
- return NULL;
- }
-
- pyrna_subtype_set_rna(py_class, srna_new); /* takes a ref to py_class */
-
- /* old srna still references us, keep the check in case registering somehow can free it */
- if (RNA_struct_py_type_get(srna)) {
- RNA_struct_py_type_set(srna, NULL);
- // Py_DECREF(py_class); // should be able to do this XXX since the old rna adds a new ref.
- }
-
- /* Can't use this because it returns a dict proxy
- *
- * item = PyObject_GetAttrString(py_class, "__dict__");
- */
- if (pyrna_deferred_register_class(srna_new, (PyTypeObject *)py_class) != 0) {
- return NULL;
- }
-
- /* call classed register method () */
- switch (_PyObject_LookupAttr(py_class, bpy_intern_str_register, &py_cls_meth)) {
- case 1:
- {
- PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
- if (ret) {
- Py_DECREF(ret);
- }
- else {
- return NULL;
- }
- break;
- }
- case -1:
- {
- return NULL;
- }
- }
-
- Py_RETURN_NONE;
-}
-
-
-static int pyrna_srna_contains_pointer_prop_srna(
- StructRNA *srna_props, StructRNA *srna,
- const char **r_prop_identifier)
-{
- PropertyRNA *prop;
- LinkData *link;
-
- /* verify properties */
- const ListBase *lb = RNA_struct_type_properties(srna);
-
- for (link = lb->first; link; link = link->next) {
- prop = (PropertyRNA *)link;
- if (RNA_property_type(prop) == PROP_POINTER && !RNA_property_builtin(prop)) {
- PointerRNA tptr;
- RNA_pointer_create(NULL, &RNA_Struct, srna_props, &tptr);
-
- if (RNA_property_pointer_type(&tptr, prop) == srna) {
- *r_prop_identifier = RNA_property_identifier(prop);
- return 1;
- }
- }
- }
-
- return 0;
+ /* check that we have a register callback for this type */
+ reg = RNA_struct_register(srna);
+
+ if (!reg) {
+ PyErr_Format(PyExc_ValueError,
+ "register_class(...): expected a subclass of a registerable "
+ "rna type (%.200s does not support registration)",
+ RNA_struct_identifier(srna));
+ return NULL;
+ }
+
+ /* get the context, so register callback can do necessary refreshes */
+ C = BPy_GetContext();
+
+ /* call the register callback with reports & identifier */
+ BKE_reports_init(&reports, RPT_STORE);
+
+ identifier = ((PyTypeObject *)py_class)->tp_name;
+
+ srna_new = reg(CTX_data_main(C),
+ &reports,
+ py_class,
+ identifier,
+ bpy_class_validate,
+ bpy_class_call,
+ bpy_class_free);
+
+ if (!BLI_listbase_is_empty(&reports.list)) {
+ const bool has_error = BPy_reports_to_error(&reports, PyExc_RuntimeError, false);
+ if (!has_error) {
+ BPy_reports_write_stdout(&reports, error_prefix);
+ }
+ BKE_reports_clear(&reports);
+ if (has_error) {
+ return NULL;
+ }
+ }
+
+ /* python errors validating are not converted into reports so the check above will fail.
+ * the cause for returning NULL will be printed as an error */
+ if (srna_new == NULL) {
+ return NULL;
+ }
+
+ pyrna_subtype_set_rna(py_class, srna_new); /* takes a ref to py_class */
+
+ /* old srna still references us, keep the check in case registering somehow can free it */
+ if (RNA_struct_py_type_get(srna)) {
+ RNA_struct_py_type_set(srna, NULL);
+ // Py_DECREF(py_class); // should be able to do this XXX since the old rna adds a new ref.
+ }
+
+ /* Can't use this because it returns a dict proxy
+ *
+ * item = PyObject_GetAttrString(py_class, "__dict__");
+ */
+ if (pyrna_deferred_register_class(srna_new, (PyTypeObject *)py_class) != 0) {
+ return NULL;
+ }
+
+ /* call classed register method () */
+ switch (_PyObject_LookupAttr(py_class, bpy_intern_str_register, &py_cls_meth)) {
+ case 1: {
+ PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
+ if (ret) {
+ Py_DECREF(ret);
+ }
+ else {
+ return NULL;
+ }
+ break;
+ }
+ case -1: {
+ return NULL;
+ }
+ }
+
+ Py_RETURN_NONE;
+}
+
+static int pyrna_srna_contains_pointer_prop_srna(StructRNA *srna_props,
+ StructRNA *srna,
+ const char **r_prop_identifier)
+{
+ PropertyRNA *prop;
+ LinkData *link;
+
+ /* verify properties */
+ const ListBase *lb = RNA_struct_type_properties(srna);
+
+ for (link = lb->first; link; link = link->next) {
+ prop = (PropertyRNA *)link;
+ if (RNA_property_type(prop) == PROP_POINTER && !RNA_property_builtin(prop)) {
+ PointerRNA tptr;
+ RNA_pointer_create(NULL, &RNA_Struct, srna_props, &tptr);
+
+ if (RNA_property_pointer_type(&tptr, prop) == srna) {
+ *r_prop_identifier = RNA_property_identifier(prop);
+ return 1;
+ }
+ }
+ }
+
+ return 0;
}
PyDoc_STRVAR(pyrna_unregister_class_doc,
-".. method:: unregister_class(cls)\n"
-"\n"
-" Unload the python class from blender.\n"
-"\n"
-" If the class has an *unregister* class method it will be called\n"
-" before unregistering.\n"
-);
+ ".. method:: unregister_class(cls)\n"
+ "\n"
+ " Unload the python class from blender.\n"
+ "\n"
+ " If the class has an *unregister* class method it will be called\n"
+ " before unregistering.\n");
PyMethodDef meth_bpy_unregister_class = {
- "unregister_class", pyrna_unregister_class, METH_O, pyrna_unregister_class_doc,
+ "unregister_class",
+ pyrna_unregister_class,
+ METH_O,
+ pyrna_unregister_class_doc,
};
static PyObject *pyrna_unregister_class(PyObject *UNUSED(self), PyObject *py_class)
{
- bContext *C = NULL;
- StructUnregisterFunc unreg;
- StructRNA *srna;
- PyObject *py_cls_meth;
+ bContext *C = NULL;
+ StructUnregisterFunc unreg;
+ StructRNA *srna;
+ PyObject *py_cls_meth;
- if (!PyType_Check(py_class)) {
- PyErr_Format(PyExc_ValueError,
- "register_class(...): "
- "expected a class argument, not '%.200s'", Py_TYPE(py_class)->tp_name);
- return NULL;
- }
+ if (!PyType_Check(py_class)) {
+ PyErr_Format(PyExc_ValueError,
+ "register_class(...): "
+ "expected a class argument, not '%.200s'",
+ Py_TYPE(py_class)->tp_name);
+ return NULL;
+ }
#if 0
- if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna) == NULL) {
- PWM_cursor_wait(0);
- PyErr_SetString(PyExc_ValueError, "unregister_class(): not a registered as a subclass");
- return NULL;
- }
+ if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna) == NULL) {
+ PWM_cursor_wait(0);
+ PyErr_SetString(PyExc_ValueError, "unregister_class(): not a registered as a subclass");
+ return NULL;
+ }
#endif
- if (!pyrna_write_check()) {
- PyErr_Format(PyExc_RuntimeError,
- "unregister_class(...): "
- "can't run in readonly state '%.200s'",
- ((PyTypeObject *)py_class)->tp_name);
- return NULL;
- }
-
- srna = pyrna_struct_as_srna(py_class, false, "unregister_class(...):");
- if (srna == NULL) {
- return NULL;
- }
-
- /* check that we have a unregister callback for this type */
- unreg = RNA_struct_unregister(srna);
-
- if (!unreg) {
- PyErr_SetString(PyExc_ValueError,
- "unregister_class(...): "
- "expected a Type subclassed from a registerable rna type (no unregister supported)");
- return NULL;
- }
-
- /* call classed unregister method */
- switch (_PyObject_LookupAttr(py_class, bpy_intern_str_unregister, &py_cls_meth)) {
- case 1:
- {
- PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
- if (ret) {
- Py_DECREF(ret);
- }
- else {
- return NULL;
- }
- break;
- }
- case -1:
- {
- return NULL;
- }
- }
-
- /* should happen all the time but very slow */
- if (G.debug & G_DEBUG_PYTHON) {
- /* remove all properties using this class */
- StructRNA *srna_iter;
- PointerRNA ptr_rna;
- PropertyRNA *prop_rna;
- const char *prop_identifier = NULL;
-
- RNA_blender_rna_pointer_create(&ptr_rna);
- prop_rna = RNA_struct_find_property(&ptr_rna, "structs");
-
-
- /* loop over all structs */
- RNA_PROP_BEGIN (&ptr_rna, itemptr, prop_rna)
- {
- srna_iter = itemptr.data;
- if (pyrna_srna_contains_pointer_prop_srna(srna_iter, srna, &prop_identifier)) {
- break;
- }
- }
- RNA_PROP_END;
-
- if (prop_identifier) {
- PyErr_Format(PyExc_RuntimeError,
- "unregister_class(...): can't unregister %s because %s.%s pointer property is using this",
- RNA_struct_identifier(srna), RNA_struct_identifier(srna_iter), prop_identifier);
- return NULL;
- }
- }
-
- /* get the context, so register callback can do necessary refreshes */
- C = BPy_GetContext();
-
- /* call unregister */
- unreg(CTX_data_main(C), srna); /* calls bpy_class_free, this decref's py_class */
-
- PyDict_DelItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna);
- if (PyErr_Occurred()) {
- PyErr_Clear(); //return NULL;
- }
-
- Py_RETURN_NONE;
+ if (!pyrna_write_check()) {
+ PyErr_Format(PyExc_RuntimeError,
+ "unregister_class(...): "
+ "can't run in readonly state '%.200s'",
+ ((PyTypeObject *)py_class)->tp_name);
+ return NULL;
+ }
+
+ srna = pyrna_struct_as_srna(py_class, false, "unregister_class(...):");
+ if (srna == NULL) {
+ return NULL;
+ }
+
+ /* check that we have a unregister callback for this type */
+ unreg = RNA_struct_unregister(srna);
+
+ if (!unreg) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "unregister_class(...): "
+ "expected a Type subclassed from a registerable rna type (no unregister supported)");
+ return NULL;
+ }
+
+ /* call classed unregister method */
+ switch (_PyObject_LookupAttr(py_class, bpy_intern_str_unregister, &py_cls_meth)) {
+ case 1: {
+ PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
+ if (ret) {
+ Py_DECREF(ret);
+ }
+ else {
+ return NULL;
+ }
+ break;
+ }
+ case -1: {
+ return NULL;
+ }
+ }
+
+ /* should happen all the time but very slow */
+ if (G.debug & G_DEBUG_PYTHON) {
+ /* remove all properties using this class */
+ StructRNA *srna_iter;
+ PointerRNA ptr_rna;
+ PropertyRNA *prop_rna;
+ const char *prop_identifier = NULL;
+
+ RNA_blender_rna_pointer_create(&ptr_rna);
+ prop_rna = RNA_struct_find_property(&ptr_rna, "structs");
+
+ /* loop over all structs */
+ RNA_PROP_BEGIN (&ptr_rna, itemptr, prop_rna) {
+ srna_iter = itemptr.data;
+ if (pyrna_srna_contains_pointer_prop_srna(srna_iter, srna, &prop_identifier)) {
+ break;
+ }
+ }
+ RNA_PROP_END;
+
+ if (prop_identifier) {
+ PyErr_Format(PyExc_RuntimeError,
+ "unregister_class(...): can't unregister %s because %s.%s pointer property is "
+ "using this",
+ RNA_struct_identifier(srna),
+ RNA_struct_identifier(srna_iter),
+ prop_identifier);
+ return NULL;
+ }
+ }
+
+ /* get the context, so register callback can do necessary refreshes */
+ C = BPy_GetContext();
+
+ /* call unregister */
+ unreg(CTX_data_main(C), srna); /* calls bpy_class_free, this decref's py_class */
+
+ PyDict_DelItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna);
+ if (PyErr_Occurred()) {
+ PyErr_Clear(); //return NULL;
+ }
+
+ Py_RETURN_NONE;
}
/* Access to 'owner_id' internal global. */
static PyObject *pyrna_bl_owner_id_get(PyObject *UNUSED(self))
{
- const char *name = RNA_struct_state_owner_get();
- if (name) {
- return PyUnicode_FromString(name);
- }
- Py_RETURN_NONE;
+ const char *name = RNA_struct_state_owner_get();
+ if (name) {
+ return PyUnicode_FromString(name);
+ }
+ Py_RETURN_NONE;
}
static PyObject *pyrna_bl_owner_id_set(PyObject *UNUSED(self), PyObject *value)
{
- const char *name;
- if (value == Py_None) {
- name = NULL;
- }
- else if (PyUnicode_Check(value)) {
- name = _PyUnicode_AsString(value);
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "owner_set(...): "
- "expected None or a string, not '%.200s'", Py_TYPE(value)->tp_name);
- return NULL;
- }
- RNA_struct_state_owner_set(name);
- Py_RETURN_NONE;
+ const char *name;
+ if (value == Py_None) {
+ name = NULL;
+ }
+ else if (PyUnicode_Check(value)) {
+ name = _PyUnicode_AsString(value);
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "owner_set(...): "
+ "expected None or a string, not '%.200s'",
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+ RNA_struct_state_owner_set(name);
+ Py_RETURN_NONE;
}
PyMethodDef meth_bpy_owner_id_get = {
- "_bl_owner_id_get", (PyCFunction)pyrna_bl_owner_id_get, METH_NOARGS, NULL,
+ "_bl_owner_id_get",
+ (PyCFunction)pyrna_bl_owner_id_get,
+ METH_NOARGS,
+ NULL,
};
PyMethodDef meth_bpy_owner_id_set = {
- "_bl_owner_id_set", (PyCFunction)pyrna_bl_owner_id_set, METH_O, NULL,
+ "_bl_owner_id_set",
+ (PyCFunction)pyrna_bl_owner_id_set,
+ METH_O,
+ NULL,
};
/* currently this is fairly limited, we would need to make some way to split up
* pyrna_callback_classmethod_... if we want more than one callback per type */
typedef struct BPyRNA_CallBack {
- PyMethodDef py_method;
- StructRNA *bpy_srna;
+ PyMethodDef py_method;
+ StructRNA *bpy_srna;
} PyRNA_CallBack;
-PyDoc_STRVAR(pyrna_draw_handler_add_doc,
-".. method:: draw_handler_add(callback, args, region_type, draw_type)\n"
-"\n"
-" Add a new draw handler to this space type.\n"
-" It will be called every time the specified region in the space type will be drawn.\n"
-" Note: All arguments are positional only for now.\n"
-"\n"
-" :param callback:\n"
-" A function that will be called when the region is drawn.\n"
-" It gets the specified arguments as input.\n"
-" :type callback: function\n"
-" :param args: Arguments that will be passed to the callback.\n"
-" :type args: tuple\n"
-" :param region_type: The region type the callback draws in; usually `'WINDOW'`. (:class:`bpy.types.Region.type`)\n"
-" :type region_type: str\n"
-" :param draw_type: Usually `POST_PIXEL` for 2D drawing and `POST_VIEW` for 3D drawing. In some cases `PRE_VIEW` can be used.\n"
-" :type draw_type: str\n"
-" :return: Handler that can be removed later on.\n"
-" :rtype: object"
-);
+PyDoc_STRVAR(
+ pyrna_draw_handler_add_doc,
+ ".. method:: draw_handler_add(callback, args, region_type, draw_type)\n"
+ "\n"
+ " Add a new draw handler to this space type.\n"
+ " It will be called every time the specified region in the space type will be drawn.\n"
+ " Note: All arguments are positional only for now.\n"
+ "\n"
+ " :param callback:\n"
+ " A function that will be called when the region is drawn.\n"
+ " It gets the specified arguments as input.\n"
+ " :type callback: function\n"
+ " :param args: Arguments that will be passed to the callback.\n"
+ " :type args: tuple\n"
+ " :param region_type: The region type the callback draws in; usually `'WINDOW'`. "
+ "(:class:`bpy.types.Region.type`)\n"
+ " :type region_type: str\n"
+ " :param draw_type: Usually `POST_PIXEL` for 2D drawing and `POST_VIEW` for 3D drawing. In "
+ "some cases `PRE_VIEW` can be used.\n"
+ " :type draw_type: str\n"
+ " :return: Handler that can be removed later on.\n"
+ " :rtype: object");
PyDoc_STRVAR(pyrna_draw_handler_remove_doc,
-".. method:: draw_handler_remove(handler, region_type)\n"
-"\n"
-" Remove a draw handler that was added previously.\n"
-"\n"
-" :param handler: The draw handler that should be removed.\n"
-" :type handler: object\n"
-" :param region_type: Region type the callback was added to.\n"
-" :type region_type: str\n"
-);
+ ".. method:: draw_handler_remove(handler, region_type)\n"
+ "\n"
+ " Remove a draw handler that was added previously.\n"
+ "\n"
+ " :param handler: The draw handler that should be removed.\n"
+ " :type handler: object\n"
+ " :param region_type: Region type the callback was added to.\n"
+ " :type region_type: str\n");
static struct BPyRNA_CallBack pyrna_cb_methods[] = {
- {{"draw_handler_add", (PyCFunction)pyrna_callback_classmethod_add,
- METH_VARARGS | METH_STATIC, pyrna_draw_handler_add_doc}, &RNA_Space},
- {{"draw_handler_remove", (PyCFunction)pyrna_callback_classmethod_remove,
- METH_VARARGS | METH_STATIC, pyrna_draw_handler_remove_doc}, &RNA_Space},
-
- {{"draw_cursor_add", (PyCFunction)pyrna_callback_classmethod_add, METH_VARARGS | METH_STATIC, ""}, &RNA_WindowManager},
- {{"draw_cursor_remove", (PyCFunction)pyrna_callback_classmethod_remove, METH_VARARGS | METH_STATIC, ""}, &RNA_WindowManager},
- {{NULL, NULL, 0, NULL}, NULL},
+ {{"draw_handler_add",
+ (PyCFunction)pyrna_callback_classmethod_add,
+ METH_VARARGS | METH_STATIC,
+ pyrna_draw_handler_add_doc},
+ &RNA_Space},
+ {{"draw_handler_remove",
+ (PyCFunction)pyrna_callback_classmethod_remove,
+ METH_VARARGS | METH_STATIC,
+ pyrna_draw_handler_remove_doc},
+ &RNA_Space},
+
+ {{"draw_cursor_add",
+ (PyCFunction)pyrna_callback_classmethod_add,
+ METH_VARARGS | METH_STATIC,
+ ""},
+ &RNA_WindowManager},
+ {{"draw_cursor_remove",
+ (PyCFunction)pyrna_callback_classmethod_remove,
+ METH_VARARGS | METH_STATIC,
+ ""},
+ &RNA_WindowManager},
+ {{NULL, NULL, 0, NULL}, NULL},
};
void BPY_rna_register_cb(void)
{
- int i;
+ int i;
- for (i = 0; pyrna_cb_methods[i].bpy_srna; i++) {
- PyObject *cls;
- PyObject *func;
- PyObject *classmethod;
- PyObject *args = PyTuple_New(1);
+ for (i = 0; pyrna_cb_methods[i].bpy_srna; i++) {
+ PyObject *cls;
+ PyObject *func;
+ PyObject *classmethod;
+ PyObject *args = PyTuple_New(1);
- cls = pyrna_srna_Subtype(pyrna_cb_methods[i].bpy_srna);
- func = PyCFunction_New(&pyrna_cb_methods[i].py_method, NULL);
- PyTuple_SET_ITEM(args, 0, func);
- classmethod = PyObject_CallObject((PyObject *)&PyClassMethod_Type, args);
+ cls = pyrna_srna_Subtype(pyrna_cb_methods[i].bpy_srna);
+ func = PyCFunction_New(&pyrna_cb_methods[i].py_method, NULL);
+ PyTuple_SET_ITEM(args, 0, func);
+ classmethod = PyObject_CallObject((PyObject *)&PyClassMethod_Type, args);
- PyObject_SetAttrString(cls, pyrna_cb_methods[i].py_method.ml_name, classmethod);
+ PyObject_SetAttrString(cls, pyrna_cb_methods[i].py_method.ml_name, classmethod);
- Py_DECREF(classmethod);
- Py_DECREF(args); /* clears 'func' too */
- Py_DECREF(cls);
- }
+ Py_DECREF(classmethod);
+ Py_DECREF(args); /* clears 'func' too */
+ Py_DECREF(cls);
+ }
}
diff --git a/source/blender/python/intern/bpy_rna.h b/source/blender/python/intern/bpy_rna.h
index c4c6944d46d..588c3cbf171 100644
--- a/source/blender/python/intern/bpy_rna.h
+++ b/source/blender/python/intern/bpy_rna.h
@@ -25,31 +25,30 @@
#ifdef WITH_PYTHON_SAFETY
/* play it safe and keep optional for now, need to test further now this affects looping on 10000's of verts for eg. */
-#define USE_WEAKREFS
+# define USE_WEAKREFS
/* method to invalidate removed py data, XXX, slow to remove objects, otherwise no overhead */
/* #define USE_PYRNA_INVALIDATE_GC */
/* different method */
-#define USE_PYRNA_INVALIDATE_WEAKREF
+# define USE_PYRNA_INVALIDATE_WEAKREF
/* support for inter references, currently only needed for corner case */
-#define USE_PYRNA_STRUCT_REFERENCE
+# define USE_PYRNA_STRUCT_REFERENCE
#else /* WITH_PYTHON_SAFETY */
- /* default, no defines! */
+/* default, no defines! */
#endif /* !WITH_PYTHON_SAFETY */
-
/* sanity checks on above defs */
#if defined(USE_PYRNA_INVALIDATE_WEAKREF) && !defined(USE_WEAKREFS)
-#define USE_WEAKREFS
+# define USE_WEAKREFS
#endif
#if defined(USE_PYRNA_INVALIDATE_GC) && defined(USE_PYRNA_INVALIDATE_WEAKREF)
-#error "Only 1 reference check method at a time!"
+# error "Only 1 reference check method at a time!"
#endif
/* only used by operator introspection get_rna(), this is only used for doc gen
@@ -72,86 +71,102 @@ extern PyTypeObject pyrna_prop_array_Type;
extern PyTypeObject pyrna_prop_collection_Type;
extern PyTypeObject pyrna_func_Type;
-#define BPy_StructRNA_Check(v) (PyObject_TypeCheck(v, &pyrna_struct_Type))
-#define BPy_StructRNA_CheckExact(v) (Py_TYPE(v) == &pyrna_struct_Type)
-#define BPy_PropertyRNA_Check(v) (PyObject_TypeCheck(v, &pyrna_prop_Type))
-#define BPy_PropertyRNA_CheckExact(v) (Py_TYPE(v) == &pyrna_prop_Type)
-
-#define PYRNA_STRUCT_CHECK_OBJ(obj) if (UNLIKELY(pyrna_struct_validity_check(obj) == -1)) { return NULL; } (void)0
-#define PYRNA_STRUCT_CHECK_INT(obj) if (UNLIKELY(pyrna_struct_validity_check(obj) == -1)) { return -1; } (void)0
-
-#define PYRNA_PROP_CHECK_OBJ(obj) if (UNLIKELY(pyrna_prop_validity_check(obj) == -1)) { return NULL; } (void)0
-#define PYRNA_PROP_CHECK_INT(obj) if (UNLIKELY(pyrna_prop_validity_check(obj) == -1)) { return -1; } (void)0
+#define BPy_StructRNA_Check(v) (PyObject_TypeCheck(v, &pyrna_struct_Type))
+#define BPy_StructRNA_CheckExact(v) (Py_TYPE(v) == &pyrna_struct_Type)
+#define BPy_PropertyRNA_Check(v) (PyObject_TypeCheck(v, &pyrna_prop_Type))
+#define BPy_PropertyRNA_CheckExact(v) (Py_TYPE(v) == &pyrna_prop_Type)
+
+#define PYRNA_STRUCT_CHECK_OBJ(obj) \
+ if (UNLIKELY(pyrna_struct_validity_check(obj) == -1)) { \
+ return NULL; \
+ } \
+ (void)0
+#define PYRNA_STRUCT_CHECK_INT(obj) \
+ if (UNLIKELY(pyrna_struct_validity_check(obj) == -1)) { \
+ return -1; \
+ } \
+ (void)0
+
+#define PYRNA_PROP_CHECK_OBJ(obj) \
+ if (UNLIKELY(pyrna_prop_validity_check(obj) == -1)) { \
+ return NULL; \
+ } \
+ (void)0
+#define PYRNA_PROP_CHECK_INT(obj) \
+ if (UNLIKELY(pyrna_prop_validity_check(obj) == -1)) { \
+ return -1; \
+ } \
+ (void)0
#define PYRNA_STRUCT_IS_VALID(pysrna) (LIKELY(((BPy_StructRNA *)(pysrna))->ptr.type != NULL))
-#define PYRNA_PROP_IS_VALID(pysrna) (LIKELY(((BPy_PropertyRNA *)(pysrna))->ptr.type != NULL))
+#define PYRNA_PROP_IS_VALID(pysrna) (LIKELY(((BPy_PropertyRNA *)(pysrna))->ptr.type != NULL))
/* 'in_weakreflist' MUST be aligned */
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- PointerRNA ptr;
+ PointerRNA ptr;
} BPy_DummyPointerRNA;
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- PointerRNA ptr;
+ PointerRNA ptr;
#ifdef USE_PYRNA_STRUCT_REFERENCE
- /* generic PyObject we hold a reference to, example use:
- * hold onto the collection iterator to prevent it from freeing allocated data we may use */
- PyObject *reference;
+ /* generic PyObject we hold a reference to, example use:
+ * hold onto the collection iterator to prevent it from freeing allocated data we may use */
+ PyObject *reference;
#endif /* !USE_PYRNA_STRUCT_REFERENCE */
#ifdef PYRNA_FREE_SUPPORT
- bool freeptr; /* needed in some cases if ptr.data is created on the fly, free when deallocing */
-#endif /* PYRNA_FREE_SUPPORT */
+ bool freeptr; /* needed in some cases if ptr.data is created on the fly, free when deallocing */
+#endif /* PYRNA_FREE_SUPPORT */
} BPy_StructRNA;
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- PointerRNA ptr;
- PropertyRNA *prop;
+ PointerRNA ptr;
+ PropertyRNA *prop;
} BPy_PropertyRNA;
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- PointerRNA ptr;
- PropertyRNA *prop;
+ PointerRNA ptr;
+ PropertyRNA *prop;
- /* Arystan: this is a hack to allow sub-item r/w access like: face.uv[n][m] */
- int arraydim; /* array dimension, e.g: 0 for face.uv, 2 for face.uv[n][m], etc. */
- int arrayoffset; /* array first item offset, e.g. if face.uv is [4][2], arrayoffset for face.uv[n] is 2n */
+ /* Arystan: this is a hack to allow sub-item r/w access like: face.uv[n][m] */
+ int arraydim; /* array dimension, e.g: 0 for face.uv, 2 for face.uv[n][m], etc. */
+ int arrayoffset; /* array first item offset, e.g. if face.uv is [4][2], arrayoffset for face.uv[n] is 2n */
} BPy_PropertyArrayRNA;
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- /* collection iterator specific parts */
- CollectionPropertyIterator iter;
+ /* collection iterator specific parts */
+ CollectionPropertyIterator iter;
} BPy_PropertyCollectionIterRNA;
typedef struct {
- PyObject_HEAD /* required python macro */
+ PyObject_HEAD /* required python macro */
#ifdef USE_WEAKREFS
- PyObject *in_weakreflist;
+ PyObject *in_weakreflist;
#endif
- PointerRNA ptr;
- FunctionRNA *func;
+ PointerRNA ptr;
+ FunctionRNA *func;
} BPy_FunctionRNA;
/* cheap trick */
@@ -160,37 +175,44 @@ typedef struct {
StructRNA *srna_from_self(PyObject *self, const char *error_prefix);
StructRNA *pyrna_struct_as_srna(PyObject *self, const bool parent, const char *error_prefix);
-void BPY_rna_init(void);
+void BPY_rna_init(void);
PyObject *BPY_rna_module(void);
-void BPY_update_rna_module(void);
+void BPY_update_rna_module(void);
/*PyObject *BPY_rna_doc(void);*/
PyObject *BPY_rna_types(void);
-void BPY_rna_register_cb(void);
+void BPY_rna_register_cb(void);
PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr);
PyObject *pyrna_prop_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop);
/* extern'd by other modules which don't deal closely with RNA */
PyObject *pyrna_id_CreatePyObject(struct ID *id);
-bool pyrna_id_FromPyObject(PyObject *obj, struct ID **id);
-bool pyrna_id_CheckPyObject(PyObject *obj);
+bool pyrna_id_FromPyObject(PyObject *obj, struct ID **id);
+bool pyrna_id_CheckPyObject(PyObject *obj);
/* operators also need this to set args */
-int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const bool all_args, const char *error_prefix);
+int pyrna_pydict_to_props(PointerRNA *ptr,
+ PyObject *kw,
+ const bool all_args,
+ const char *error_prefix);
PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop);
-unsigned int *pyrna_set_to_enum_bitmap(
- const struct EnumPropertyItem *items, PyObject *value,
- int type_size, bool type_convert_sign,
- int bitmap_size,
- const char *error_prefix);
-PyObject *pyrna_enum_bitfield_to_py(
- const struct EnumPropertyItem *items, int value);
-int pyrna_set_to_enum_bitfield(
- const struct EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix);
-
-int pyrna_enum_value_from_id(
- const EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix);
+unsigned int *pyrna_set_to_enum_bitmap(const struct EnumPropertyItem *items,
+ PyObject *value,
+ int type_size,
+ bool type_convert_sign,
+ int bitmap_size,
+ const char *error_prefix);
+PyObject *pyrna_enum_bitfield_to_py(const struct EnumPropertyItem *items, int value);
+int pyrna_set_to_enum_bitfield(const struct EnumPropertyItem *items,
+ PyObject *value,
+ int *r_value,
+ const char *error_prefix);
+
+int pyrna_enum_value_from_id(const EnumPropertyItem *item,
+ const char *identifier,
+ int *value,
+ const char *error_prefix);
int pyrna_deferred_register_class(struct StructRNA *srna, PyTypeObject *py_class);
@@ -199,12 +221,22 @@ void pyrna_alloc_types(void);
void pyrna_free_types(void);
/* primitive type conversion */
-int pyrna_py_to_array(PointerRNA *ptr, PropertyRNA *prop, char *param_data, PyObject *py, const char *error_prefix);
-int pyrna_py_to_array_index(PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset, int index, PyObject *py, const char *error_prefix);
+int pyrna_py_to_array(
+ PointerRNA *ptr, PropertyRNA *prop, char *param_data, PyObject *py, const char *error_prefix);
+int pyrna_py_to_array_index(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int arraydim,
+ int arrayoffset,
+ int index,
+ PyObject *py,
+ const char *error_prefix);
PyObject *pyrna_array_index(PointerRNA *ptr, PropertyRNA *prop, int index);
PyObject *pyrna_py_from_array(PointerRNA *ptr, PropertyRNA *prop);
-PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, int index);
+PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index);
PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop);
int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value);
diff --git a/source/blender/python/intern/bpy_rna_anim.c b/source/blender/python/intern/bpy_rna_anim.c
index a25906ac9a1..2cd8c8641bb 100644
--- a/source/blender/python/intern/bpy_rna_anim.c
+++ b/source/blender/python/intern/bpy_rna_anim.c
@@ -56,554 +56,596 @@
#include "../generic/python_utildefines.h"
/* for keyframes and drivers */
-static int pyrna_struct_anim_args_parse_ex(
- PointerRNA *ptr, const char *error_prefix, const char *path,
- const char **r_path_full, int *r_index, bool *r_path_no_validate)
+static int pyrna_struct_anim_args_parse_ex(PointerRNA *ptr,
+ const char *error_prefix,
+ const char *path,
+ const char **r_path_full,
+ int *r_index,
+ bool *r_path_no_validate)
{
- const bool is_idbase = RNA_struct_is_ID(ptr->type);
- PropertyRNA *prop;
- PointerRNA r_ptr;
-
- if (ptr->data == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s this struct has no data, can't be animated",
- error_prefix);
- return -1;
- }
-
- /* full paths can only be given from ID base */
- if (is_idbase) {
- int path_index = -1;
- if (RNA_path_resolve_property_full(ptr, path, &r_ptr, &prop, &path_index) == false) {
- prop = NULL;
- }
- else if (path_index != -1) {
- PyErr_Format(PyExc_ValueError,
- "%.200s path includes index, must be a separate argument",
- error_prefix, path);
- return -1;
- }
- else if (ptr->id.data != r_ptr.id.data) {
- PyErr_Format(PyExc_ValueError,
- "%.200s path spans ID blocks",
- error_prefix, path);
- return -1;
- }
- }
- else {
- prop = RNA_struct_find_property(ptr, path);
- r_ptr = *ptr;
- }
-
- if (prop == NULL) {
- if (r_path_no_validate) {
- *r_path_no_validate = true;
- return -1;
- }
- PyErr_Format(PyExc_TypeError,
- "%.200s property \"%s\" not found",
- error_prefix, path);
- return -1;
- }
-
- if (r_path_no_validate) {
- /* Don't touch the index. */
- }
- else {
- if (!RNA_property_animateable(&r_ptr, prop)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s property \"%s\" not animatable",
- error_prefix, path);
- return -1;
- }
-
- if (RNA_property_array_check(prop) == 0) {
- if ((*r_index) == -1) {
- *r_index = 0;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s index %d was given while property \"%s\" is not an array",
- error_prefix, *r_index, path);
- return -1;
- }
- }
- else {
- int array_len = RNA_property_array_length(&r_ptr, prop);
- if ((*r_index) < -1 || (*r_index) >= array_len) {
- PyErr_Format(PyExc_TypeError,
- "%.200s index out of range \"%s\", given %d, array length is %d",
- error_prefix, path, *r_index, array_len);
- return -1;
- }
- }
- }
-
- if (is_idbase) {
- *r_path_full = BLI_strdup(path);
- }
- else {
- *r_path_full = RNA_path_from_ID_to_property(&r_ptr, prop);
-
- if (*r_path_full == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s could not make path to \"%s\"",
- error_prefix, path);
- return -1;
- }
- }
-
- return 0;
+ const bool is_idbase = RNA_struct_is_ID(ptr->type);
+ PropertyRNA *prop;
+ PointerRNA r_ptr;
+
+ if (ptr->data == NULL) {
+ PyErr_Format(
+ PyExc_TypeError, "%.200s this struct has no data, can't be animated", error_prefix);
+ return -1;
+ }
+
+ /* full paths can only be given from ID base */
+ if (is_idbase) {
+ int path_index = -1;
+ if (RNA_path_resolve_property_full(ptr, path, &r_ptr, &prop, &path_index) == false) {
+ prop = NULL;
+ }
+ else if (path_index != -1) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s path includes index, must be a separate argument",
+ error_prefix,
+ path);
+ return -1;
+ }
+ else if (ptr->id.data != r_ptr.id.data) {
+ PyErr_Format(PyExc_ValueError, "%.200s path spans ID blocks", error_prefix, path);
+ return -1;
+ }
+ }
+ else {
+ prop = RNA_struct_find_property(ptr, path);
+ r_ptr = *ptr;
+ }
+
+ if (prop == NULL) {
+ if (r_path_no_validate) {
+ *r_path_no_validate = true;
+ return -1;
+ }
+ PyErr_Format(PyExc_TypeError, "%.200s property \"%s\" not found", error_prefix, path);
+ return -1;
+ }
+
+ if (r_path_no_validate) {
+ /* Don't touch the index. */
+ }
+ else {
+ if (!RNA_property_animateable(&r_ptr, prop)) {
+ PyErr_Format(PyExc_TypeError, "%.200s property \"%s\" not animatable", error_prefix, path);
+ return -1;
+ }
+
+ if (RNA_property_array_check(prop) == 0) {
+ if ((*r_index) == -1) {
+ *r_index = 0;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s index %d was given while property \"%s\" is not an array",
+ error_prefix,
+ *r_index,
+ path);
+ return -1;
+ }
+ }
+ else {
+ int array_len = RNA_property_array_length(&r_ptr, prop);
+ if ((*r_index) < -1 || (*r_index) >= array_len) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s index out of range \"%s\", given %d, array length is %d",
+ error_prefix,
+ path,
+ *r_index,
+ array_len);
+ return -1;
+ }
+ }
+ }
+
+ if (is_idbase) {
+ *r_path_full = BLI_strdup(path);
+ }
+ else {
+ *r_path_full = RNA_path_from_ID_to_property(&r_ptr, prop);
+
+ if (*r_path_full == NULL) {
+ PyErr_Format(PyExc_TypeError, "%.200s could not make path to \"%s\"", error_prefix, path);
+ return -1;
+ }
+ }
+
+ return 0;
}
-static int pyrna_struct_anim_args_parse(
- PointerRNA *ptr, const char *error_prefix, const char *path,
- const char **r_path_full, int *r_index)
+static int pyrna_struct_anim_args_parse(PointerRNA *ptr,
+ const char *error_prefix,
+ const char *path,
+ const char **r_path_full,
+ int *r_index)
{
- return pyrna_struct_anim_args_parse_ex(ptr, error_prefix, path, r_path_full, r_index, NULL);
+ return pyrna_struct_anim_args_parse_ex(ptr, error_prefix, path, r_path_full, r_index, NULL);
}
/**
* Unlike #pyrna_struct_anim_args_parse \a r_path_full may be copied from \a path.
*/
-static int pyrna_struct_anim_args_parse_no_resolve(
- PointerRNA *ptr, const char *error_prefix, const char *path,
- const char **r_path_full)
+static int pyrna_struct_anim_args_parse_no_resolve(PointerRNA *ptr,
+ const char *error_prefix,
+ const char *path,
+ const char **r_path_full)
{
- const bool is_idbase = RNA_struct_is_ID(ptr->type);
- if (is_idbase) {
- *r_path_full = path;
- return 0;
- }
- else {
- char *path_prefix = RNA_path_from_ID_to_struct(ptr);
- if (path_prefix == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s could not make path for type %s",
- error_prefix, RNA_struct_identifier(ptr->type));
- return -1;
- }
-
- if (*path == '[') {
- *r_path_full = BLI_string_joinN(path_prefix, path);
- }
- else {
- *r_path_full = BLI_string_join_by_sep_charN('.', path_prefix, path);
- }
- MEM_freeN(path_prefix);
- }
- return 0;
+ const bool is_idbase = RNA_struct_is_ID(ptr->type);
+ if (is_idbase) {
+ *r_path_full = path;
+ return 0;
+ }
+ else {
+ char *path_prefix = RNA_path_from_ID_to_struct(ptr);
+ if (path_prefix == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s could not make path for type %s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type));
+ return -1;
+ }
+
+ if (*path == '[') {
+ *r_path_full = BLI_string_joinN(path_prefix, path);
+ }
+ else {
+ *r_path_full = BLI_string_join_by_sep_charN('.', path_prefix, path);
+ }
+ MEM_freeN(path_prefix);
+ }
+ return 0;
}
-static int pyrna_struct_anim_args_parse_no_resolve_fallback(
- PointerRNA *ptr, const char *error_prefix, const char *path,
- const char **r_path_full, int *r_index)
+static int pyrna_struct_anim_args_parse_no_resolve_fallback(PointerRNA *ptr,
+ const char *error_prefix,
+ const char *path,
+ const char **r_path_full,
+ int *r_index)
{
- bool path_unresolved = false;
- if (pyrna_struct_anim_args_parse_ex(
- ptr, error_prefix, path,
- r_path_full, r_index, &path_unresolved) == -1)
- {
- if (path_unresolved == true) {
- if (pyrna_struct_anim_args_parse_no_resolve(
- ptr, error_prefix, path, r_path_full) == -1)
- {
- return -1;
- }
- }
- else {
- return -1;
- }
- }
- return 0;
+ bool path_unresolved = false;
+ if (pyrna_struct_anim_args_parse_ex(
+ ptr, error_prefix, path, r_path_full, r_index, &path_unresolved) == -1) {
+ if (path_unresolved == true) {
+ if (pyrna_struct_anim_args_parse_no_resolve(ptr, error_prefix, path, r_path_full) == -1) {
+ return -1;
+ }
+ }
+ else {
+ return -1;
+ }
+ }
+ return 0;
}
/* internal use for insert and delete */
-static int pyrna_struct_keyframe_parse(
- PointerRNA *ptr, PyObject *args, PyObject *kw, const char *parse_str, const char *error_prefix,
- /* return values */
- const char **r_path_full, int *r_index, float *r_cfra, const char **r_group_name, int *r_options)
+static int pyrna_struct_keyframe_parse(PointerRNA *ptr,
+ PyObject *args,
+ PyObject *kw,
+ const char *parse_str,
+ const char *error_prefix,
+ /* return values */
+ const char **r_path_full,
+ int *r_index,
+ float *r_cfra,
+ const char **r_group_name,
+ int *r_options)
{
- static const char *kwlist[] = {"data_path", "index", "frame", "group", "options", NULL};
- PyObject *pyoptions = NULL;
- const char *path;
-
- /* note, parse_str MUST start with 's|ifsO!' */
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, parse_str, (char **)kwlist, &path, r_index, r_cfra, r_group_name,
- &PySet_Type, &pyoptions))
- {
- return -1;
- }
-
- if (pyrna_struct_anim_args_parse(
- ptr, error_prefix, path,
- r_path_full, r_index) == -1)
- {
- return -1;
- }
-
- if (*r_cfra == FLT_MAX) {
- *r_cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
- }
-
- /* flag may be null (no option currently for remove keyframes e.g.). */
- if (r_options) {
- if (pyoptions &&
- (pyrna_set_to_enum_bitfield(
- rna_enum_keying_flag_items, pyoptions, r_options, error_prefix) == -1))
- {
- return -1;
- }
-
- *r_options |= INSERTKEY_NO_USERPREF;
- }
-
- return 0; /* success */
+ static const char *kwlist[] = {"data_path", "index", "frame", "group", "options", NULL};
+ PyObject *pyoptions = NULL;
+ const char *path;
+
+ /* note, parse_str MUST start with 's|ifsO!' */
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ parse_str,
+ (char **)kwlist,
+ &path,
+ r_index,
+ r_cfra,
+ r_group_name,
+ &PySet_Type,
+ &pyoptions)) {
+ return -1;
+ }
+
+ if (pyrna_struct_anim_args_parse(ptr, error_prefix, path, r_path_full, r_index) == -1) {
+ return -1;
+ }
+
+ if (*r_cfra == FLT_MAX) {
+ *r_cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
+ }
+
+ /* flag may be null (no option currently for remove keyframes e.g.). */
+ if (r_options) {
+ if (pyoptions && (pyrna_set_to_enum_bitfield(
+ rna_enum_keying_flag_items, pyoptions, r_options, error_prefix) == -1)) {
+ return -1;
+ }
+
+ *r_options |= INSERTKEY_NO_USERPREF;
+ }
+
+ return 0; /* success */
}
char pyrna_struct_keyframe_insert_doc[] =
-".. method:: keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
-"\n"
-" Insert a keyframe on the property given, adding fcurves and animation data when necessary.\n"
-"\n"
-" :arg data_path: path to the property to key, analogous to the fcurve's data path.\n"
-" :type data_path: string\n"
-" :arg index: array index of the property to key.\n"
-" Defaults to -1 which will key all indices or a single channel if the property is not an array.\n"
-" :type index: int\n"
-" :arg frame: The frame on which the keyframe is inserted, defaulting to the current frame.\n"
-" :type frame: float\n"
-" :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
-" :type group: str\n"
-" :arg options: Optional flags:\n"
-"\n"
-" - ``INSERTKEY_NEEDED`` Only insert keyframes where they're needed in the relevant F-Curves.\n"
-" - ``INSERTKEY_VISUAL`` Insert keyframes based on 'visual transforms'.\n"
-" - ``INSERTKEY_XYZ_TO_RGB`` Color for newly added transformation F-Curves (Location, Rotation, Scale)\n"
-" and also Color is based on the transform axis.\n"
-" :type flag: set\n"
-" :return: Success of keyframe insertion.\n"
-" :rtype: boolean\n"
-;
+ ".. method:: keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame_current, "
+ "group=\"\")\n"
+ "\n"
+ " Insert a keyframe on the property given, adding fcurves and animation data when "
+ "necessary.\n"
+ "\n"
+ " :arg data_path: path to the property to key, analogous to the fcurve's data path.\n"
+ " :type data_path: string\n"
+ " :arg index: array index of the property to key.\n"
+ " Defaults to -1 which will key all indices or a single channel if the property is not "
+ "an array.\n"
+ " :type index: int\n"
+ " :arg frame: The frame on which the keyframe is inserted, defaulting to the current "
+ "frame.\n"
+ " :type frame: float\n"
+ " :arg group: The name of the group the F-Curve should be added to if it doesn't exist "
+ "yet.\n"
+ " :type group: str\n"
+ " :arg options: Optional flags:\n"
+ "\n"
+ " - ``INSERTKEY_NEEDED`` Only insert keyframes where they're needed in the relevant "
+ "F-Curves.\n"
+ " - ``INSERTKEY_VISUAL`` Insert keyframes based on 'visual transforms'.\n"
+ " - ``INSERTKEY_XYZ_TO_RGB`` Color for newly added transformation F-Curves (Location, "
+ "Rotation, Scale)\n"
+ " and also Color is based on the transform axis.\n"
+ " :type flag: set\n"
+ " :return: Success of keyframe insertion.\n"
+ " :rtype: boolean\n";
PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyObject *kw)
{
- /* args, pyrna_struct_keyframe_parse handles these */
- const char *path_full = NULL;
- int index = -1;
- float cfra = FLT_MAX;
- const char *group_name = NULL;
- char keytype = BEZT_KEYTYPE_KEYFRAME; /* XXX: Expose this as a one-off option... */
- int options = 0;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (pyrna_struct_keyframe_parse(
- &self->ptr, args, kw,
- "s|ifsO!:bpy_struct.keyframe_insert()", "bpy_struct.keyframe_insert()",
- &path_full, &index, &cfra, &group_name, &options) == -1)
- {
- return NULL;
- }
- else if (self->ptr.type == &RNA_NlaStrip) {
- /* Handle special properties for NLA Strips, whose F-Curves are stored on the
- * strips themselves. These are stored separately or else the properties will
- * not have any effect.
- */
- struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
- ReportList reports;
- short result = 0;
-
- PointerRNA ptr = self->ptr;
- PropertyRNA *prop = NULL;
- const char *prop_name;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- /* Retrieve the property identifier from the full path, since we can't get it any other way */
- prop_name = strrchr(path_full, '.');
- if ((prop_name >= path_full) &&
- (prop_name + 1 < path_full + strlen(path_full)))
- {
- prop = RNA_struct_find_property(&ptr, prop_name + 1);
- }
-
- if (prop) {
- NlaStrip *strip = (NlaStrip *)ptr.data;
- FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
-
- result = insert_keyframe_direct(depsgraph, &reports, ptr, prop, fcu, cfra, keytype, NULL, options);
- }
- else {
- BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
- }
- MEM_freeN((void *)path_full);
-
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
-
- return PyBool_FromLong(result);
- }
- else {
- ID *id = self->ptr.id.data;
- struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
- ReportList reports;
- short result;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- BLI_assert(BKE_id_is_in_global_main(id));
- result = insert_keyframe(G_MAIN, depsgraph, &reports, id, NULL, group_name, path_full, index, cfra, keytype, NULL, options);
- MEM_freeN((void *)path_full);
-
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
-
- return PyBool_FromLong(result);
- }
+ /* args, pyrna_struct_keyframe_parse handles these */
+ const char *path_full = NULL;
+ int index = -1;
+ float cfra = FLT_MAX;
+ const char *group_name = NULL;
+ char keytype = BEZT_KEYTYPE_KEYFRAME; /* XXX: Expose this as a one-off option... */
+ int options = 0;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (pyrna_struct_keyframe_parse(&self->ptr,
+ args,
+ kw,
+ "s|ifsO!:bpy_struct.keyframe_insert()",
+ "bpy_struct.keyframe_insert()",
+ &path_full,
+ &index,
+ &cfra,
+ &group_name,
+ &options) == -1) {
+ return NULL;
+ }
+ else if (self->ptr.type == &RNA_NlaStrip) {
+ /* Handle special properties for NLA Strips, whose F-Curves are stored on the
+ * strips themselves. These are stored separately or else the properties will
+ * not have any effect.
+ */
+ struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
+ ReportList reports;
+ short result = 0;
+
+ PointerRNA ptr = self->ptr;
+ PropertyRNA *prop = NULL;
+ const char *prop_name;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ /* Retrieve the property identifier from the full path, since we can't get it any other way */
+ prop_name = strrchr(path_full, '.');
+ if ((prop_name >= path_full) && (prop_name + 1 < path_full + strlen(path_full))) {
+ prop = RNA_struct_find_property(&ptr, prop_name + 1);
+ }
+
+ if (prop) {
+ NlaStrip *strip = (NlaStrip *)ptr.data;
+ FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
+
+ result = insert_keyframe_direct(
+ depsgraph, &reports, ptr, prop, fcu, cfra, keytype, NULL, options);
+ }
+ else {
+ BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
+ }
+ MEM_freeN((void *)path_full);
+
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
+
+ return PyBool_FromLong(result);
+ }
+ else {
+ ID *id = self->ptr.id.data;
+ struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
+ ReportList reports;
+ short result;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ BLI_assert(BKE_id_is_in_global_main(id));
+ result = insert_keyframe(G_MAIN,
+ depsgraph,
+ &reports,
+ id,
+ NULL,
+ group_name,
+ path_full,
+ index,
+ cfra,
+ keytype,
+ NULL,
+ options);
+ MEM_freeN((void *)path_full);
+
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
+
+ return PyBool_FromLong(result);
+ }
}
char pyrna_struct_keyframe_delete_doc[] =
-".. method:: keyframe_delete(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
-"\n"
-" Remove a keyframe from this properties fcurve.\n"
-"\n"
-" :arg data_path: path to the property to remove a key, analogous to the fcurve's data path.\n"
-" :type data_path: string\n"
-" :arg index: array index of the property to remove a key. Defaults to -1 removing all indices or a single channel if the property is not an array.\n"
-" :type index: int\n"
-" :arg frame: The frame on which the keyframe is deleted, defaulting to the current frame.\n"
-" :type frame: float\n"
-" :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
-" :type group: str\n"
-" :return: Success of keyframe deleation.\n"
-" :rtype: boolean\n"
-;
+ ".. method:: keyframe_delete(data_path, index=-1, frame=bpy.context.scene.frame_current, "
+ "group=\"\")\n"
+ "\n"
+ " Remove a keyframe from this properties fcurve.\n"
+ "\n"
+ " :arg data_path: path to the property to remove a key, analogous to the fcurve's data "
+ "path.\n"
+ " :type data_path: string\n"
+ " :arg index: array index of the property to remove a key. Defaults to -1 removing all "
+ "indices or a single channel if the property is not an array.\n"
+ " :type index: int\n"
+ " :arg frame: The frame on which the keyframe is deleted, defaulting to the current frame.\n"
+ " :type frame: float\n"
+ " :arg group: The name of the group the F-Curve should be added to if it doesn't exist "
+ "yet.\n"
+ " :type group: str\n"
+ " :return: Success of keyframe deleation.\n"
+ " :rtype: boolean\n";
PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyObject *kw)
{
- /* args, pyrna_struct_keyframe_parse handles these */
- const char *path_full = NULL;
- int index = -1;
- float cfra = FLT_MAX;
- const char *group_name = NULL;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (pyrna_struct_keyframe_parse(&self->ptr, args, kw,
- "s|ifsO!:bpy_struct.keyframe_delete()",
- "bpy_struct.keyframe_insert()",
- &path_full, &index, &cfra, &group_name, NULL) == -1)
- {
- return NULL;
- }
- else if (self->ptr.type == &RNA_NlaStrip) {
- /* Handle special properties for NLA Strips, whose F-Curves are stored on the
- * strips themselves. These are stored separately or else the properties will
- * not have any effect.
- */
- ReportList reports;
- short result = 0;
-
- PointerRNA ptr = self->ptr;
- PropertyRNA *prop = NULL;
- const char *prop_name;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- /* Retrieve the property identifier from the full path, since we can't get it any other way */
- prop_name = strrchr(path_full, '.');
- if ((prop_name >= path_full) &&
- (prop_name + 1 < path_full + strlen(path_full)))
- {
- prop = RNA_struct_find_property(&ptr, prop_name + 1);
- }
-
- if (prop) {
- ID *id = ptr.id.data;
- NlaStrip *strip = (NlaStrip *)ptr.data;
- FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
-
- BLI_assert(fcu != NULL); /* NOTE: This should be true, or else we wouldn't be able to get here */
-
- if (BKE_fcurve_is_protected(fcu)) {
- BKE_reportf(&reports, RPT_WARNING,
- "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'",
- strip->name, BKE_idcode_to_name(GS(id->name)), id->name + 2);
- }
- else {
- /* remove the keyframe directly
- * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve,
- * and delete_keyframe() expects the FCurve to be part of an action
- */
- bool found = false;
- int i;
-
- /* try to find index of beztriple to get rid of */
- i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
- if (found) {
- /* delete the key at the index (will sanity check + do recalc afterwards) */
- delete_fcurve_key(fcu, i, 1);
- result = true;
- }
- }
- }
- else {
- BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
- }
- MEM_freeN((void *)path_full);
-
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
-
- return PyBool_FromLong(result);
- }
- else {
- short result;
- ReportList reports;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- result = delete_keyframe(G.main, &reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0);
- MEM_freeN((void *)path_full);
-
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
-
- return PyBool_FromLong(result);
- }
-
+ /* args, pyrna_struct_keyframe_parse handles these */
+ const char *path_full = NULL;
+ int index = -1;
+ float cfra = FLT_MAX;
+ const char *group_name = NULL;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (pyrna_struct_keyframe_parse(&self->ptr,
+ args,
+ kw,
+ "s|ifsO!:bpy_struct.keyframe_delete()",
+ "bpy_struct.keyframe_insert()",
+ &path_full,
+ &index,
+ &cfra,
+ &group_name,
+ NULL) == -1) {
+ return NULL;
+ }
+ else if (self->ptr.type == &RNA_NlaStrip) {
+ /* Handle special properties for NLA Strips, whose F-Curves are stored on the
+ * strips themselves. These are stored separately or else the properties will
+ * not have any effect.
+ */
+ ReportList reports;
+ short result = 0;
+
+ PointerRNA ptr = self->ptr;
+ PropertyRNA *prop = NULL;
+ const char *prop_name;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ /* Retrieve the property identifier from the full path, since we can't get it any other way */
+ prop_name = strrchr(path_full, '.');
+ if ((prop_name >= path_full) && (prop_name + 1 < path_full + strlen(path_full))) {
+ prop = RNA_struct_find_property(&ptr, prop_name + 1);
+ }
+
+ if (prop) {
+ ID *id = ptr.id.data;
+ NlaStrip *strip = (NlaStrip *)ptr.data;
+ FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
+
+ BLI_assert(fcu !=
+ NULL); /* NOTE: This should be true, or else we wouldn't be able to get here */
+
+ if (BKE_fcurve_is_protected(fcu)) {
+ BKE_reportf(
+ &reports,
+ RPT_WARNING,
+ "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'",
+ strip->name,
+ BKE_idcode_to_name(GS(id->name)),
+ id->name + 2);
+ }
+ else {
+ /* remove the keyframe directly
+ * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve,
+ * and delete_keyframe() expects the FCurve to be part of an action
+ */
+ bool found = false;
+ int i;
+
+ /* try to find index of beztriple to get rid of */
+ i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
+ if (found) {
+ /* delete the key at the index (will sanity check + do recalc afterwards) */
+ delete_fcurve_key(fcu, i, 1);
+ result = true;
+ }
+ }
+ }
+ else {
+ BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
+ }
+ MEM_freeN((void *)path_full);
+
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
+
+ return PyBool_FromLong(result);
+ }
+ else {
+ short result;
+ ReportList reports;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ result = delete_keyframe(
+ G.main, &reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0);
+ MEM_freeN((void *)path_full);
+
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
+
+ return PyBool_FromLong(result);
+ }
}
char pyrna_struct_driver_add_doc[] =
-".. method:: driver_add(path, index=-1)\n"
-"\n"
-" Adds driver(s) to the given property\n"
-"\n"
-" :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
-" :type path: string\n"
-" :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
-" :type index: int\n"
-" :return: The driver(s) added.\n"
-" :rtype: :class:`bpy.types.FCurve` or list if index is -1 with an array property.\n"
-;
+ ".. method:: driver_add(path, index=-1)\n"
+ "\n"
+ " Adds driver(s) to the given property\n"
+ "\n"
+ " :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
+ " :type path: string\n"
+ " :arg index: array index of the property drive. Defaults to -1 for all indices or a single "
+ "channel if the property is not an array.\n"
+ " :type index: int\n"
+ " :return: The driver(s) added.\n"
+ " :rtype: :class:`bpy.types.FCurve` or list if index is -1 with an array property.\n";
PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
{
- const char *path, *path_full;
- int index = -1;
-
- PYRNA_STRUCT_CHECK_OBJ(self);
-
- if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index)) {
- return NULL;
- }
-
- if (pyrna_struct_anim_args_parse(
- &self->ptr, "bpy_struct.driver_add():", path,
- &path_full, &index) == -1)
- {
- return NULL;
- }
- else {
- PyObject *ret = NULL;
- ReportList reports;
- int result;
-
- BKE_reports_init(&reports, RPT_STORE);
-
- result = ANIM_add_driver(&reports, (ID *)self->ptr.id.data, path_full, index,
- CREATEDRIVER_WITH_FMODIFIER, DRIVER_TYPE_PYTHON);
-
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
-
- if (result) {
- ID *id = self->ptr.id.data;
- AnimData *adt = BKE_animdata_from_id(id);
- FCurve *fcu;
-
- PointerRNA tptr;
-
- if (index == -1) { /* all, use a list */
- int i = 0;
- ret = PyList_New(0);
- while ((fcu = list_find_fcurve(&adt->drivers, path_full, i++))) {
- RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
- PyList_APPEND(ret, pyrna_struct_CreatePyObject(&tptr));
- }
- }
- else {
- fcu = list_find_fcurve(&adt->drivers, path_full, index);
- RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
- ret = pyrna_struct_CreatePyObject(&tptr);
- }
-
- WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
- }
- else {
- /* XXX, should be handled by reports, */
- PyErr_SetString(PyExc_TypeError, "bpy_struct.driver_add(): failed because of an internal error");
- return NULL;
- }
-
- MEM_freeN((void *)path_full);
-
- return ret;
- }
+ const char *path, *path_full;
+ int index = -1;
+
+ PYRNA_STRUCT_CHECK_OBJ(self);
+
+ if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index)) {
+ return NULL;
+ }
+
+ if (pyrna_struct_anim_args_parse(
+ &self->ptr, "bpy_struct.driver_add():", path, &path_full, &index) == -1) {
+ return NULL;
+ }
+ else {
+ PyObject *ret = NULL;
+ ReportList reports;
+ int result;
+
+ BKE_reports_init(&reports, RPT_STORE);
+
+ result = ANIM_add_driver(&reports,
+ (ID *)self->ptr.id.data,
+ path_full,
+ index,
+ CREATEDRIVER_WITH_FMODIFIER,
+ DRIVER_TYPE_PYTHON);
+
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
+
+ if (result) {
+ ID *id = self->ptr.id.data;
+ AnimData *adt = BKE_animdata_from_id(id);
+ FCurve *fcu;
+
+ PointerRNA tptr;
+
+ if (index == -1) { /* all, use a list */
+ int i = 0;
+ ret = PyList_New(0);
+ while ((fcu = list_find_fcurve(&adt->drivers, path_full, i++))) {
+ RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
+ PyList_APPEND(ret, pyrna_struct_CreatePyObject(&tptr));
+ }
+ }
+ else {
+ fcu = list_find_fcurve(&adt->drivers, path_full, index);
+ RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
+ ret = pyrna_struct_CreatePyObject(&tptr);
+ }
+
+ WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
+ }
+ else {
+ /* XXX, should be handled by reports, */
+ PyErr_SetString(PyExc_TypeError,
+ "bpy_struct.driver_add(): failed because of an internal error");
+ return NULL;
+ }
+
+ MEM_freeN((void *)path_full);
+
+ return ret;
+ }
}
-
char pyrna_struct_driver_remove_doc[] =
-".. method:: driver_remove(path, index=-1)\n"
-"\n"
-" Remove driver(s) from the given property\n"
-"\n"
-" :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
-" :type path: string\n"
-" :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
-" :type index: int\n"
-" :return: Success of driver removal.\n"
-" :rtype: boolean\n"
-;
+ ".. method:: driver_remove(path, index=-1)\n"
+ "\n"
+ " Remove driver(s) from the given property\n"
+ "\n"
+ " :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
+ " :type path: string\n"
+ " :arg index: array index of the property drive. Defaults to -1 for all indices or a single "
+ "channel if the property is not an array.\n"
+ " :type index: int\n"
+ " :return: Success of driver removal.\n"
+ " :rtype: boolean\n";
PyObject *pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args)
{
- const char *path, *path_full;
- int index = -1;
+ const char *path, *path_full;
+ int index = -1;
- PYRNA_STRUCT_CHECK_OBJ(self);
+ PYRNA_STRUCT_CHECK_OBJ(self);
- if (!PyArg_ParseTuple(args, "s|i:driver_remove", &path, &index)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s|i:driver_remove", &path, &index)) {
+ return NULL;
+ }
- if (pyrna_struct_anim_args_parse_no_resolve_fallback(
- &self->ptr, "bpy_struct.driver_remove():", path,
- &path_full, &index) == -1)
- {
- return NULL;
- }
- else {
- short result;
- ReportList reports;
+ if (pyrna_struct_anim_args_parse_no_resolve_fallback(
+ &self->ptr, "bpy_struct.driver_remove():", path, &path_full, &index) == -1) {
+ return NULL;
+ }
+ else {
+ short result;
+ ReportList reports;
- BKE_reports_init(&reports, RPT_STORE);
+ BKE_reports_init(&reports, RPT_STORE);
- result = ANIM_remove_driver(&reports, (ID *)self->ptr.id.data, path_full, index, 0);
+ result = ANIM_remove_driver(&reports, (ID *)self->ptr.id.data, path_full, index, 0);
- if (path != path_full) {
- MEM_freeN((void *)path_full);
- }
+ if (path != path_full) {
+ MEM_freeN((void *)path_full);
+ }
- if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
- return NULL;
- }
+ if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1) {
+ return NULL;
+ }
- WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
+ WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
- return PyBool_FromLong(result);
- }
+ return PyBool_FromLong(result);
+ }
}
diff --git a/source/blender/python/intern/bpy_rna_anim.h b/source/blender/python/intern/bpy_rna_anim.h
index 5145d16eafb..7630c268bbe 100644
--- a/source/blender/python/intern/bpy_rna_anim.h
+++ b/source/blender/python/intern/bpy_rna_anim.h
@@ -31,4 +31,4 @@ PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyOb
PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args);
PyObject *pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args);
-#endif /* __BPY_RNA_ANIM_H__ */
+#endif /* __BPY_RNA_ANIM_H__ */
diff --git a/source/blender/python/intern/bpy_rna_array.c b/source/blender/python/intern/bpy_rna_array.c
index 4cc3c4c0fae..7097999201a 100644
--- a/source/blender/python/intern/bpy_rna_array.c
+++ b/source/blender/python/intern/bpy_rna_array.c
@@ -54,22 +54,22 @@ typedef void (*RNA_SetArrayFunc)(PointerRNA *, PropertyRNA *, const char *);
typedef void (*RNA_SetIndexFunc)(PointerRNA *, PropertyRNA *, int index, void *);
struct ItemConvertArgData {
- union {
- struct {
- int range[2];
- } int_data;
- struct {
- float range[2];
- } float_data;
- };
+ union {
+ struct {
+ int range[2];
+ } int_data;
+ struct {
+ float range[2];
+ } float_data;
+ };
};
/**
* Callback and args needed to apply the value (clamp range for now)
*/
typedef struct ItemConvert_FuncArg {
- ItemConvertFunc func;
- struct ItemConvertArgData arg;
+ ItemConvertFunc func;
+ struct ItemConvertArgData arg;
} ItemConvert_FuncArg;
/*
@@ -87,655 +87,797 @@ typedef struct ItemConvert_FuncArg {
/* arr[3] = x, self->arraydim is 0, lvalue_dim is 1 */
/* Ensures that a python sequence has expected number of items/sub-items and items are of desired type. */
-static int validate_array_type(PyObject *seq, int dim, int totdim, int dimsize[], const bool is_dynamic,
- ItemTypeCheckFunc check_item_type, const char *item_type_str, const char *error_prefix)
+static int validate_array_type(PyObject *seq,
+ int dim,
+ int totdim,
+ int dimsize[],
+ const bool is_dynamic,
+ ItemTypeCheckFunc check_item_type,
+ const char *item_type_str,
+ const char *error_prefix)
{
- Py_ssize_t i;
-
- /* not the last dimension */
- if (dim + 1 < totdim) {
- /* check that a sequence contains dimsize[dim] items */
- const int seq_size = PySequence_Size(seq);
- if (seq_size == -1) {
- PyErr_Format(PyExc_ValueError, "%s sequence expected at dimension %d, not '%s'",
- error_prefix, dim + 1, Py_TYPE(seq)->tp_name);
- return -1;
- }
- for (i = 0; i < seq_size; i++) {
- Py_ssize_t item_seq_size;
- PyObject *item;
- bool ok = true;
- item = PySequence_GetItem(seq, i);
-
- if (item == NULL) {
- PyErr_Format(PyExc_TypeError, "%s sequence type '%s' failed to retrieve index %d",
- error_prefix, Py_TYPE(seq)->tp_name, i);
- ok = 0;
- }
- else if ((item_seq_size = PySequence_Size(item)) == -1) {
- /* BLI_snprintf(error_str, error_str_size, "expected a sequence of %s", item_type_str); */
- PyErr_Format(PyExc_TypeError, "%s expected a sequence of %s, not %s",
- error_prefix, item_type_str, Py_TYPE(item)->tp_name);
- ok = 0;
- }
- /* arr[3][4][5]
- * dimsize[1] = 4
- * dimsize[2] = 5
- *
- * dim = 0 */
- else if (item_seq_size != dimsize[dim + 1]) {
- /* BLI_snprintf(error_str, error_str_size,
- * "sequences of dimension %d should contain %d items",
- * dim + 1, dimsize[dim + 1]); */
- PyErr_Format(PyExc_ValueError, "%s sequences of dimension %d should contain %d items, not %d",
- error_prefix, dim + 1, dimsize[dim + 1], item_seq_size);
- ok = 0;
- }
- else if (validate_array_type(item, dim + 1, totdim, dimsize, is_dynamic,
- check_item_type, item_type_str, error_prefix) == -1)
- {
- ok = 0;
- }
-
- Py_XDECREF(item);
-
- if (!ok) {
- return -1;
- }
- }
- }
- else {
- /* check that items are of correct type */
- const int seq_size = PySequence_Size(seq);
- if (seq_size == -1) {
- PyErr_Format(PyExc_ValueError, "%s sequence expected at dimension %d, not '%s'",
- error_prefix, dim + 1, Py_TYPE(seq)->tp_name);
- return -1;
- }
- else if ((seq_size != dimsize[dim]) && (is_dynamic == false)) {
- PyErr_Format(PyExc_ValueError, "%s sequences of dimension %d should contain %d items, not %d",
- error_prefix, dim, dimsize[dim], seq_size);
- return -1;
- }
-
- for (i = 0; i < seq_size; i++) {
- PyObject *item = PySequence_GetItem(seq, i);
-
- if (item == NULL) {
- PyErr_Format(PyExc_TypeError, "%s sequence type '%s' failed to retrieve index %d",
- error_prefix, Py_TYPE(seq)->tp_name, i);
- return -1;
- }
- else if (!check_item_type(item)) {
- Py_DECREF(item);
-
- /* BLI_snprintf(error_str, error_str_size, "sequence items should be of type %s", item_type_str); */
- PyErr_Format(PyExc_TypeError, "%s expected sequence items of type %s, not %s",
- error_prefix, item_type_str, Py_TYPE(item)->tp_name);
- return -1;
- }
-
- Py_DECREF(item);
- }
- }
-
- return 0; /* ok */
+ Py_ssize_t i;
+
+ /* not the last dimension */
+ if (dim + 1 < totdim) {
+ /* check that a sequence contains dimsize[dim] items */
+ const int seq_size = PySequence_Size(seq);
+ if (seq_size == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "%s sequence expected at dimension %d, not '%s'",
+ error_prefix,
+ dim + 1,
+ Py_TYPE(seq)->tp_name);
+ return -1;
+ }
+ for (i = 0; i < seq_size; i++) {
+ Py_ssize_t item_seq_size;
+ PyObject *item;
+ bool ok = true;
+ item = PySequence_GetItem(seq, i);
+
+ if (item == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s sequence type '%s' failed to retrieve index %d",
+ error_prefix,
+ Py_TYPE(seq)->tp_name,
+ i);
+ ok = 0;
+ }
+ else if ((item_seq_size = PySequence_Size(item)) == -1) {
+ /* BLI_snprintf(error_str, error_str_size, "expected a sequence of %s", item_type_str); */
+ PyErr_Format(PyExc_TypeError,
+ "%s expected a sequence of %s, not %s",
+ error_prefix,
+ item_type_str,
+ Py_TYPE(item)->tp_name);
+ ok = 0;
+ }
+ /* arr[3][4][5]
+ * dimsize[1] = 4
+ * dimsize[2] = 5
+ *
+ * dim = 0 */
+ else if (item_seq_size != dimsize[dim + 1]) {
+ /* BLI_snprintf(error_str, error_str_size,
+ * "sequences of dimension %d should contain %d items",
+ * dim + 1, dimsize[dim + 1]); */
+ PyErr_Format(PyExc_ValueError,
+ "%s sequences of dimension %d should contain %d items, not %d",
+ error_prefix,
+ dim + 1,
+ dimsize[dim + 1],
+ item_seq_size);
+ ok = 0;
+ }
+ else if (validate_array_type(item,
+ dim + 1,
+ totdim,
+ dimsize,
+ is_dynamic,
+ check_item_type,
+ item_type_str,
+ error_prefix) == -1) {
+ ok = 0;
+ }
+
+ Py_XDECREF(item);
+
+ if (!ok) {
+ return -1;
+ }
+ }
+ }
+ else {
+ /* check that items are of correct type */
+ const int seq_size = PySequence_Size(seq);
+ if (seq_size == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "%s sequence expected at dimension %d, not '%s'",
+ error_prefix,
+ dim + 1,
+ Py_TYPE(seq)->tp_name);
+ return -1;
+ }
+ else if ((seq_size != dimsize[dim]) && (is_dynamic == false)) {
+ PyErr_Format(PyExc_ValueError,
+ "%s sequences of dimension %d should contain %d items, not %d",
+ error_prefix,
+ dim,
+ dimsize[dim],
+ seq_size);
+ return -1;
+ }
+
+ for (i = 0; i < seq_size; i++) {
+ PyObject *item = PySequence_GetItem(seq, i);
+
+ if (item == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s sequence type '%s' failed to retrieve index %d",
+ error_prefix,
+ Py_TYPE(seq)->tp_name,
+ i);
+ return -1;
+ }
+ else if (!check_item_type(item)) {
+ Py_DECREF(item);
+
+ /* BLI_snprintf(error_str, error_str_size, "sequence items should be of type %s", item_type_str); */
+ PyErr_Format(PyExc_TypeError,
+ "%s expected sequence items of type %s, not %s",
+ error_prefix,
+ item_type_str,
+ Py_TYPE(item)->tp_name);
+ return -1;
+ }
+
+ Py_DECREF(item);
+ }
+ }
+
+ return 0; /* ok */
}
/* Returns the number of items in a single- or multi-dimensional sequence. */
static int count_items(PyObject *seq, int dim)
{
- int totitem = 0;
-
- if (dim > 1) {
- const Py_ssize_t seq_size = PySequence_Size(seq);
- Py_ssize_t i;
- for (i = 0; i < seq_size; i++) {
- PyObject *item = PySequence_GetItem(seq, i);
- if (item) {
- const int tot = count_items(item, dim - 1);
- Py_DECREF(item);
- if (tot != -1) {
- totitem += tot;
- }
- else {
- totitem = -1;
- break;
- }
- }
- else {
- totitem = -1;
- break;
- }
- }
- }
- else {
- totitem = PySequence_Size(seq);
- }
-
- return totitem;
+ int totitem = 0;
+
+ if (dim > 1) {
+ const Py_ssize_t seq_size = PySequence_Size(seq);
+ Py_ssize_t i;
+ for (i = 0; i < seq_size; i++) {
+ PyObject *item = PySequence_GetItem(seq, i);
+ if (item) {
+ const int tot = count_items(item, dim - 1);
+ Py_DECREF(item);
+ if (tot != -1) {
+ totitem += tot;
+ }
+ else {
+ totitem = -1;
+ break;
+ }
+ }
+ else {
+ totitem = -1;
+ break;
+ }
+ }
+ }
+ else {
+ totitem = PySequence_Size(seq);
+ }
+
+ return totitem;
}
/* Modifies property array length if needed and PROP_DYNAMIC flag is set. */
-static int validate_array_length(PyObject *rvalue, PointerRNA *ptr, PropertyRNA *prop,
- int lvalue_dim, int *totitem, const char *error_prefix)
+static int validate_array_length(PyObject *rvalue,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int lvalue_dim,
+ int *totitem,
+ const char *error_prefix)
{
- int dimsize[MAX_ARRAY_DIMENSION];
- int tot, totdim, len;
-
- totdim = RNA_property_array_dimension(ptr, prop, dimsize);
- tot = count_items(rvalue, totdim - lvalue_dim);
-
- if (tot == -1) {
- PyErr_Format(PyExc_ValueError, "%s %.200s.%.200s, error validating the sequence length",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
- return -1;
- }
- else if ((RNA_property_flag(prop) & PROP_DYNAMIC) && lvalue_dim == 0) {
- if (RNA_property_array_length(ptr, prop) != tot) {
+ int dimsize[MAX_ARRAY_DIMENSION];
+ int tot, totdim, len;
+
+ totdim = RNA_property_array_dimension(ptr, prop, dimsize);
+ tot = count_items(rvalue, totdim - lvalue_dim);
+
+ if (tot == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "%s %.200s.%.200s, error validating the sequence length",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ return -1;
+ }
+ else if ((RNA_property_flag(prop) & PROP_DYNAMIC) && lvalue_dim == 0) {
+ if (RNA_property_array_length(ptr, prop) != tot) {
#if 0
- /* length is flexible */
- if (!RNA_property_dynamic_array_set_length(ptr, prop, tot)) {
- /* BLI_snprintf(error_str, error_str_size,
- * "%s.%s: array length cannot be changed to %d",
- * RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), tot); */
- PyErr_Format(PyExc_ValueError, "%s %s.%s: array length cannot be changed to %d",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), tot);
- return -1;
- }
+ /* length is flexible */
+ if (!RNA_property_dynamic_array_set_length(ptr, prop, tot)) {
+ /* BLI_snprintf(error_str, error_str_size,
+ * "%s.%s: array length cannot be changed to %d",
+ * RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), tot); */
+ PyErr_Format(PyExc_ValueError, "%s %s.%s: array length cannot be changed to %d",
+ error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), tot);
+ return -1;
+ }
#else
- *totitem = tot;
- return 0;
+ *totitem = tot;
+ return 0;
#endif
- }
-
- len = tot;
- }
- else {
- /* length is a constraint */
- if (!lvalue_dim) {
- len = RNA_property_array_length(ptr, prop);
- }
- /* array item assignment */
- else {
- int i;
-
- len = 1;
-
- /* arr[3][4][5]
- *
- * arr[2] = x
- * dimsize = {4, 5}
- * dimsize[1] = 4
- * dimsize[2] = 5
- * lvalue_dim = 0, totdim = 3
- *
- * arr[2][3] = x
- * lvalue_dim = 1
- *
- * arr[2][3][4] = x
- * lvalue_dim = 2 */
- for (i = lvalue_dim; i < totdim; i++) {
- len *= dimsize[i];
- }
- }
-
- if (tot != len) {
- /* BLI_snprintf(error_str, error_str_size, "sequence must have length of %d", len); */
- PyErr_Format(PyExc_ValueError, "%s %.200s.%.200s, sequence must have %d items total, not %d",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), len, tot);
- return -1;
- }
- }
-
- *totitem = len;
-
- return 0;
+ }
+
+ len = tot;
+ }
+ else {
+ /* length is a constraint */
+ if (!lvalue_dim) {
+ len = RNA_property_array_length(ptr, prop);
+ }
+ /* array item assignment */
+ else {
+ int i;
+
+ len = 1;
+
+ /* arr[3][4][5]
+ *
+ * arr[2] = x
+ * dimsize = {4, 5}
+ * dimsize[1] = 4
+ * dimsize[2] = 5
+ * lvalue_dim = 0, totdim = 3
+ *
+ * arr[2][3] = x
+ * lvalue_dim = 1
+ *
+ * arr[2][3][4] = x
+ * lvalue_dim = 2 */
+ for (i = lvalue_dim; i < totdim; i++) {
+ len *= dimsize[i];
+ }
+ }
+
+ if (tot != len) {
+ /* BLI_snprintf(error_str, error_str_size, "sequence must have length of %d", len); */
+ PyErr_Format(PyExc_ValueError,
+ "%s %.200s.%.200s, sequence must have %d items total, not %d",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ len,
+ tot);
+ return -1;
+ }
+ }
+
+ *totitem = len;
+
+ return 0;
}
-static int validate_array(PyObject *rvalue, PointerRNA *ptr, PropertyRNA *prop,
- int lvalue_dim, ItemTypeCheckFunc check_item_type, const char *item_type_str, int *totitem,
+static int validate_array(PyObject *rvalue,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int lvalue_dim,
+ ItemTypeCheckFunc check_item_type,
+ const char *item_type_str,
+ int *totitem,
const char *error_prefix)
{
- int dimsize[MAX_ARRAY_DIMENSION];
- int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
-
- /* validate type first because length validation may modify property array length */
+ int dimsize[MAX_ARRAY_DIMENSION];
+ int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
+ /* validate type first because length validation may modify property array length */
#ifdef USE_MATHUTILS
- if (lvalue_dim == 0) { /* only valid for first level array */
- if (MatrixObject_Check(rvalue)) {
- MatrixObject *pymat = (MatrixObject *)rvalue;
-
- if (BaseMath_ReadCallback(pymat) == -1) {
- return -1;
- }
-
- if (RNA_property_type(prop) != PROP_FLOAT) {
- PyErr_Format(PyExc_ValueError, "%s %.200s.%.200s, matrix assign to non float array",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
- return -1;
- }
- else if (totdim != 2) {
- PyErr_Format(PyExc_ValueError, "%s %.200s.%.200s, matrix assign array with %d dimensions",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), totdim);
- return -1;
- }
- else if (pymat->num_col != dimsize[0] || pymat->num_row != dimsize[1]) {
- PyErr_Format(PyExc_ValueError, "%s %.200s.%.200s, matrix assign dimension size mismatch, "
- "is %dx%d, expected be %dx%d",
- error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop),
- pymat->num_col, pymat->num_row, dimsize[0], dimsize[1]);
- return -1;
- }
- else {
- *totitem = dimsize[0] * dimsize[1];
- return 0;
- }
- }
- }
+ if (lvalue_dim == 0) { /* only valid for first level array */
+ if (MatrixObject_Check(rvalue)) {
+ MatrixObject *pymat = (MatrixObject *)rvalue;
+
+ if (BaseMath_ReadCallback(pymat) == -1) {
+ return -1;
+ }
+
+ if (RNA_property_type(prop) != PROP_FLOAT) {
+ PyErr_Format(PyExc_ValueError,
+ "%s %.200s.%.200s, matrix assign to non float array",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop));
+ return -1;
+ }
+ else if (totdim != 2) {
+ PyErr_Format(PyExc_ValueError,
+ "%s %.200s.%.200s, matrix assign array with %d dimensions",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ totdim);
+ return -1;
+ }
+ else if (pymat->num_col != dimsize[0] || pymat->num_row != dimsize[1]) {
+ PyErr_Format(PyExc_ValueError,
+ "%s %.200s.%.200s, matrix assign dimension size mismatch, "
+ "is %dx%d, expected be %dx%d",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ pymat->num_col,
+ pymat->num_row,
+ dimsize[0],
+ dimsize[1]);
+ return -1;
+ }
+ else {
+ *totitem = dimsize[0] * dimsize[1];
+ return 0;
+ }
+ }
+ }
#endif /* USE_MATHUTILS */
-
- {
- const int prop_flag = RNA_property_flag(prop);
- if (validate_array_type(rvalue, lvalue_dim, totdim, dimsize, (prop_flag & PROP_DYNAMIC) != 0,
- check_item_type, item_type_str, error_prefix) == -1)
- {
- return -1;
- }
-
- return validate_array_length(rvalue, ptr, prop, lvalue_dim, totitem, error_prefix);
- }
+ {
+ const int prop_flag = RNA_property_flag(prop);
+ if (validate_array_type(rvalue,
+ lvalue_dim,
+ totdim,
+ dimsize,
+ (prop_flag & PROP_DYNAMIC) != 0,
+ check_item_type,
+ item_type_str,
+ error_prefix) == -1) {
+ return -1;
+ }
+
+ return validate_array_length(rvalue, ptr, prop, lvalue_dim, totitem, error_prefix);
+ }
}
-static char *copy_value_single(
- PyObject *item, PointerRNA *ptr, PropertyRNA *prop,
- char *data, unsigned int item_size, int *index,
- const ItemConvert_FuncArg *convert_item, RNA_SetIndexFunc rna_set_index)
+static char *copy_value_single(PyObject *item,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ char *data,
+ unsigned int item_size,
+ int *index,
+ const ItemConvert_FuncArg *convert_item,
+ RNA_SetIndexFunc rna_set_index)
{
- if (!data) {
- union { float fl; int i; } value_buf;
- char *value = (void *)&value_buf;
-
- convert_item->func(&convert_item->arg, item, value);
- rna_set_index(ptr, prop, *index, value);
- (*index) += 1;
- }
- else {
- convert_item->func(&convert_item->arg, item, data);
- data += item_size;
- }
-
- return data;
+ if (!data) {
+ union {
+ float fl;
+ int i;
+ } value_buf;
+ char *value = (void *)&value_buf;
+
+ convert_item->func(&convert_item->arg, item, value);
+ rna_set_index(ptr, prop, *index, value);
+ (*index) += 1;
+ }
+ else {
+ convert_item->func(&convert_item->arg, item, data);
+ data += item_size;
+ }
+
+ return data;
}
-static char *copy_values(
- PyObject *seq, PointerRNA *ptr, PropertyRNA *prop,
- int dim, char *data, unsigned int item_size, int *index,
- const ItemConvert_FuncArg *convert_item, RNA_SetIndexFunc rna_set_index)
+static char *copy_values(PyObject *seq,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int dim,
+ char *data,
+ unsigned int item_size,
+ int *index,
+ const ItemConvert_FuncArg *convert_item,
+ RNA_SetIndexFunc rna_set_index)
{
- int totdim = RNA_property_array_dimension(ptr, prop, NULL);
- const Py_ssize_t seq_size = PySequence_Size(seq);
- Py_ssize_t i;
-
- /* Regarding PySequence_GetItem() failing.
- *
- * This should never be NULL since we validated it, _but_ some tricky python
- * developer could write their own sequence type which succeeds on
- * validating but fails later somehow, so include checks for safety.
- */
+ int totdim = RNA_property_array_dimension(ptr, prop, NULL);
+ const Py_ssize_t seq_size = PySequence_Size(seq);
+ Py_ssize_t i;
- /* Note that 'data can be NULL' */
+ /* Regarding PySequence_GetItem() failing.
+ *
+ * This should never be NULL since we validated it, _but_ some tricky python
+ * developer could write their own sequence type which succeeds on
+ * validating but fails later somehow, so include checks for safety.
+ */
- if (seq_size == -1) {
- return NULL;
- }
+ /* Note that 'data can be NULL' */
+ if (seq_size == -1) {
+ return NULL;
+ }
#ifdef USE_MATHUTILS
- if (dim == 0) {
- if (MatrixObject_Check(seq)) {
- MatrixObject *pymat = (MatrixObject *)seq;
- size_t allocsize = pymat->num_col * pymat->num_row * sizeof(float);
+ if (dim == 0) {
+ if (MatrixObject_Check(seq)) {
+ MatrixObject *pymat = (MatrixObject *)seq;
+ size_t allocsize = pymat->num_col * pymat->num_row * sizeof(float);
- /* read callback already done by validate */
- /* since this is the first iteration we can assume data is allocated */
- memcpy(data, pymat->matrix, allocsize);
+ /* read callback already done by validate */
+ /* since this is the first iteration we can assume data is allocated */
+ memcpy(data, pymat->matrix, allocsize);
- /* not really needed but do for completeness */
- data += allocsize;
+ /* not really needed but do for completeness */
+ data += allocsize;
- return data;
- }
- }
+ return data;
+ }
+ }
#endif /* USE_MATHUTILS */
-
- for (i = 0; i < seq_size; i++) {
- PyObject *item = PySequence_GetItem(seq, i);
- if (item) {
- if (dim + 1 < totdim) {
- data = copy_values(item, ptr, prop, dim + 1, data, item_size, index, convert_item, rna_set_index);
- }
- else {
- data = copy_value_single(item, ptr, prop, data, item_size, index, convert_item, rna_set_index);
- }
-
- Py_DECREF(item);
-
- /* data may be NULL, but the for loop checks */
- }
- else {
- return NULL;
- }
- }
-
- return data;
+ for (i = 0; i < seq_size; i++) {
+ PyObject *item = PySequence_GetItem(seq, i);
+ if (item) {
+ if (dim + 1 < totdim) {
+ data = copy_values(
+ item, ptr, prop, dim + 1, data, item_size, index, convert_item, rna_set_index);
+ }
+ else {
+ data = copy_value_single(
+ item, ptr, prop, data, item_size, index, convert_item, rna_set_index);
+ }
+
+ Py_DECREF(item);
+
+ /* data may be NULL, but the for loop checks */
+ }
+ else {
+ return NULL;
+ }
+ }
+
+ return data;
}
-static int py_to_array(
- PyObject *seq, PointerRNA *ptr, PropertyRNA *prop,
- char *param_data, ItemTypeCheckFunc check_item_type, const char *item_type_str, int item_size,
- const ItemConvert_FuncArg *convert_item, RNA_SetArrayFunc rna_set_array, const char *error_prefix)
+static int py_to_array(PyObject *seq,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ char *param_data,
+ ItemTypeCheckFunc check_item_type,
+ const char *item_type_str,
+ int item_size,
+ const ItemConvert_FuncArg *convert_item,
+ RNA_SetArrayFunc rna_set_array,
+ const char *error_prefix)
{
- /*int totdim, dim_size[MAX_ARRAY_DIMENSION];*/
- int totitem;
- char *data = NULL;
-
- /*totdim = RNA_property_array_dimension(ptr, prop, dim_size);*/ /*UNUSED*/
-
- if (validate_array(seq, ptr, prop, 0, check_item_type, item_type_str, &totitem, error_prefix) == -1) {
- return -1;
- }
-
- if (totitem) {
- /* note: this code is confusing */
- if (param_data && RNA_property_flag(prop) & PROP_DYNAMIC) {
- /* not freeing allocated mem, RNA_parameter_list_free() will do this */
- ParameterDynAlloc *param_alloc = (ParameterDynAlloc *)param_data;
- param_alloc->array_tot = (int)totitem;
- param_alloc->array = MEM_callocN(item_size * totitem, "py_to_array dyn"); /* freeing param list will free */
-
- data = param_alloc->array;
- }
- else if (param_data) {
- data = param_data;
- }
- else {
- data = PyMem_MALLOC(item_size * totitem);
- }
-
- /* will only fail in very rare cases since we already validated the
- * python data, the check here is mainly for completeness. */
- if (copy_values(seq, ptr, prop, 0, data, item_size, NULL, convert_item, NULL) != NULL) {
- if (param_data == NULL) {
- /* NULL can only pass through in case RNA property arraylength is 0 (impossible?) */
- rna_set_array(ptr, prop, data);
- PyMem_FREE(data);
- }
- }
- else {
- if (param_data == NULL) {
- PyMem_FREE(data);
- }
-
- PyErr_Format(PyExc_TypeError, "%s internal error parsing sequence of type '%s' after successful validation",
- error_prefix, Py_TYPE(seq)->tp_name);
- return -1;
- }
- }
-
- return 0;
+ /*int totdim, dim_size[MAX_ARRAY_DIMENSION];*/
+ int totitem;
+ char *data = NULL;
+
+ /*totdim = RNA_property_array_dimension(ptr, prop, dim_size);*/ /*UNUSED*/
+
+ if (validate_array(seq, ptr, prop, 0, check_item_type, item_type_str, &totitem, error_prefix) ==
+ -1) {
+ return -1;
+ }
+
+ if (totitem) {
+ /* note: this code is confusing */
+ if (param_data && RNA_property_flag(prop) & PROP_DYNAMIC) {
+ /* not freeing allocated mem, RNA_parameter_list_free() will do this */
+ ParameterDynAlloc *param_alloc = (ParameterDynAlloc *)param_data;
+ param_alloc->array_tot = (int)totitem;
+ param_alloc->array = MEM_callocN(item_size * totitem,
+ "py_to_array dyn"); /* freeing param list will free */
+
+ data = param_alloc->array;
+ }
+ else if (param_data) {
+ data = param_data;
+ }
+ else {
+ data = PyMem_MALLOC(item_size * totitem);
+ }
+
+ /* will only fail in very rare cases since we already validated the
+ * python data, the check here is mainly for completeness. */
+ if (copy_values(seq, ptr, prop, 0, data, item_size, NULL, convert_item, NULL) != NULL) {
+ if (param_data == NULL) {
+ /* NULL can only pass through in case RNA property arraylength is 0 (impossible?) */
+ rna_set_array(ptr, prop, data);
+ PyMem_FREE(data);
+ }
+ }
+ else {
+ if (param_data == NULL) {
+ PyMem_FREE(data);
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "%s internal error parsing sequence of type '%s' after successful validation",
+ error_prefix,
+ Py_TYPE(seq)->tp_name);
+ return -1;
+ }
+ }
+
+ return 0;
}
-static int py_to_array_index(
- PyObject *py, PointerRNA *ptr, PropertyRNA *prop,
- int lvalue_dim, int arrayoffset, int index,
- ItemTypeCheckFunc check_item_type, const char *item_type_str,
- const ItemConvert_FuncArg *convert_item, RNA_SetIndexFunc rna_set_index, const char *error_prefix)
+static int py_to_array_index(PyObject *py,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int lvalue_dim,
+ int arrayoffset,
+ int index,
+ ItemTypeCheckFunc check_item_type,
+ const char *item_type_str,
+ const ItemConvert_FuncArg *convert_item,
+ RNA_SetIndexFunc rna_set_index,
+ const char *error_prefix)
{
- int totdim, dimsize[MAX_ARRAY_DIMENSION];
- int totitem, i;
-
- totdim = RNA_property_array_dimension(ptr, prop, dimsize);
-
- /* convert index */
-
- /* arr[3][4][5]
- *
- * arr[2] = x
- * lvalue_dim = 0, index = 0 + 2 * 4 * 5
- *
- * arr[2][3] = x
- * lvalue_dim = 1, index = 40 + 3 * 5 */
-
- lvalue_dim++;
-
- for (i = lvalue_dim; i < totdim; i++) {
- index *= dimsize[i];
- }
-
- index += arrayoffset;
-
- if (lvalue_dim == totdim) { /* single item, assign directly */
- if (!check_item_type(py)) {
- PyErr_Format(PyExc_TypeError, "%s %.200s.%.200s, expected a %s type, not %s",
- error_prefix, RNA_struct_identifier(ptr->type),
- RNA_property_identifier(prop), item_type_str,
- Py_TYPE(py)->tp_name);
- return -1;
- }
- copy_value_single(py, ptr, prop, NULL, 0, &index, convert_item, rna_set_index);
- }
- else {
- if (validate_array(py, ptr, prop, lvalue_dim, check_item_type, item_type_str, &totitem, error_prefix) == -1) {
- return -1;
- }
-
- if (totitem) {
- copy_values(py, ptr, prop, lvalue_dim, NULL, 0, &index, convert_item, rna_set_index);
- }
- }
- return 0;
+ int totdim, dimsize[MAX_ARRAY_DIMENSION];
+ int totitem, i;
+
+ totdim = RNA_property_array_dimension(ptr, prop, dimsize);
+
+ /* convert index */
+
+ /* arr[3][4][5]
+ *
+ * arr[2] = x
+ * lvalue_dim = 0, index = 0 + 2 * 4 * 5
+ *
+ * arr[2][3] = x
+ * lvalue_dim = 1, index = 40 + 3 * 5 */
+
+ lvalue_dim++;
+
+ for (i = lvalue_dim; i < totdim; i++) {
+ index *= dimsize[i];
+ }
+
+ index += arrayoffset;
+
+ if (lvalue_dim == totdim) { /* single item, assign directly */
+ if (!check_item_type(py)) {
+ PyErr_Format(PyExc_TypeError,
+ "%s %.200s.%.200s, expected a %s type, not %s",
+ error_prefix,
+ RNA_struct_identifier(ptr->type),
+ RNA_property_identifier(prop),
+ item_type_str,
+ Py_TYPE(py)->tp_name);
+ return -1;
+ }
+ copy_value_single(py, ptr, prop, NULL, 0, &index, convert_item, rna_set_index);
+ }
+ else {
+ if (validate_array(
+ py, ptr, prop, lvalue_dim, check_item_type, item_type_str, &totitem, error_prefix) ==
+ -1) {
+ return -1;
+ }
+
+ if (totitem) {
+ copy_values(py, ptr, prop, lvalue_dim, NULL, 0, &index, convert_item, rna_set_index);
+ }
+ }
+ return 0;
}
static void py_to_float(const struct ItemConvertArgData *arg, PyObject *py, char *data)
{
- const float *range = arg->float_data.range;
- float value = (float)PyFloat_AsDouble(py);
- CLAMP(value, range[0], range[1]);
- *(float *)data = value;
+ const float *range = arg->float_data.range;
+ float value = (float)PyFloat_AsDouble(py);
+ CLAMP(value, range[0], range[1]);
+ *(float *)data = value;
}
static void py_to_int(const struct ItemConvertArgData *arg, PyObject *py, char *data)
{
- const int *range = arg->int_data.range;
- int value = PyC_Long_AsI32(py);
- CLAMP(value, range[0], range[1]);
- *(int *)data = value;
+ const int *range = arg->int_data.range;
+ int value = PyC_Long_AsI32(py);
+ CLAMP(value, range[0], range[1]);
+ *(int *)data = value;
}
static void py_to_bool(const struct ItemConvertArgData *UNUSED(arg), PyObject *py, char *data)
{
- *(bool *)data = (bool)PyObject_IsTrue(py);
+ *(bool *)data = (bool)PyObject_IsTrue(py);
}
static int py_float_check(PyObject *py)
{
- /* accept both floats and integers */
- return PyNumber_Check(py);
+ /* accept both floats and integers */
+ return PyNumber_Check(py);
}
static int py_int_check(PyObject *py)
{
- /* accept only integers */
- return PyLong_Check(py);
+ /* accept only integers */
+ return PyLong_Check(py);
}
static int py_bool_check(PyObject *py)
{
- return PyBool_Check(py);
+ return PyBool_Check(py);
}
static void float_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, void *value)
{
- RNA_property_float_set_index(ptr, prop, index, *(float *)value);
+ RNA_property_float_set_index(ptr, prop, index, *(float *)value);
}
static void int_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, void *value)
{
- RNA_property_int_set_index(ptr, prop, index, *(int *)value);
+ RNA_property_int_set_index(ptr, prop, index, *(int *)value);
}
static void bool_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, void *value)
{
- RNA_property_boolean_set_index(ptr, prop, index, *(bool *)value);
+ RNA_property_boolean_set_index(ptr, prop, index, *(bool *)value);
}
-static void convert_item_init_float(
- PointerRNA *ptr, PropertyRNA *prop,
- ItemConvert_FuncArg *convert_item)
+static void convert_item_init_float(PointerRNA *ptr,
+ PropertyRNA *prop,
+ ItemConvert_FuncArg *convert_item)
{
- float *range = convert_item->arg.float_data.range;
- convert_item->func = py_to_float;
- RNA_property_float_range(ptr, prop, &range[0], &range[1]);
+ float *range = convert_item->arg.float_data.range;
+ convert_item->func = py_to_float;
+ RNA_property_float_range(ptr, prop, &range[0], &range[1]);
}
-static void convert_item_init_int(
- PointerRNA *ptr, PropertyRNA *prop,
- ItemConvert_FuncArg *convert_item)
+static void convert_item_init_int(PointerRNA *ptr,
+ PropertyRNA *prop,
+ ItemConvert_FuncArg *convert_item)
{
- int *range = convert_item->arg.int_data.range;
- convert_item->func = py_to_int;
- RNA_property_int_range(ptr, prop, &range[0], &range[1]);
+ int *range = convert_item->arg.int_data.range;
+ convert_item->func = py_to_int;
+ RNA_property_int_range(ptr, prop, &range[0], &range[1]);
}
-static void convert_item_init_bool(
- PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
- ItemConvert_FuncArg *convert_item)
+static void convert_item_init_bool(PointerRNA *UNUSED(ptr),
+ PropertyRNA *UNUSED(prop),
+ ItemConvert_FuncArg *convert_item)
{
- convert_item->func = py_to_bool;
+ convert_item->func = py_to_bool;
}
-int pyrna_py_to_array(PointerRNA *ptr, PropertyRNA *prop, char *param_data,
- PyObject *py, const char *error_prefix)
+int pyrna_py_to_array(
+ PointerRNA *ptr, PropertyRNA *prop, char *param_data, PyObject *py, const char *error_prefix)
{
- int ret;
- switch (RNA_property_type(prop)) {
- case PROP_FLOAT:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_float(ptr, prop, &convert_item);
-
- ret = py_to_array(
- py, ptr, prop, param_data, py_float_check, "float", sizeof(float),
- &convert_item, (RNA_SetArrayFunc)RNA_property_float_set_array, error_prefix);
- break;
- }
- case PROP_INT:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_int(ptr, prop, &convert_item);
-
- ret = py_to_array(
- py, ptr, prop, param_data, py_int_check, "int", sizeof(int),
- &convert_item, (RNA_SetArrayFunc)RNA_property_int_set_array, error_prefix);
- break;
- }
- case PROP_BOOLEAN:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_bool(ptr, prop, &convert_item);
-
- ret = py_to_array(
- py, ptr, prop, param_data, py_bool_check, "boolean", sizeof(bool),
- &convert_item, (RNA_SetArrayFunc)RNA_property_boolean_set_array, error_prefix);
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_TypeError, "not an array type");
- ret = -1;
- break;
- }
- }
-
- return ret;
+ int ret;
+ switch (RNA_property_type(prop)) {
+ case PROP_FLOAT: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_float(ptr, prop, &convert_item);
+
+ ret = py_to_array(py,
+ ptr,
+ prop,
+ param_data,
+ py_float_check,
+ "float",
+ sizeof(float),
+ &convert_item,
+ (RNA_SetArrayFunc)RNA_property_float_set_array,
+ error_prefix);
+ break;
+ }
+ case PROP_INT: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_int(ptr, prop, &convert_item);
+
+ ret = py_to_array(py,
+ ptr,
+ prop,
+ param_data,
+ py_int_check,
+ "int",
+ sizeof(int),
+ &convert_item,
+ (RNA_SetArrayFunc)RNA_property_int_set_array,
+ error_prefix);
+ break;
+ }
+ case PROP_BOOLEAN: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_bool(ptr, prop, &convert_item);
+
+ ret = py_to_array(py,
+ ptr,
+ prop,
+ param_data,
+ py_bool_check,
+ "boolean",
+ sizeof(bool),
+ &convert_item,
+ (RNA_SetArrayFunc)RNA_property_boolean_set_array,
+ error_prefix);
+ break;
+ }
+ default: {
+ PyErr_SetString(PyExc_TypeError, "not an array type");
+ ret = -1;
+ break;
+ }
+ }
+
+ return ret;
}
-int pyrna_py_to_array_index(PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset, int index,
- PyObject *py, const char *error_prefix)
+int pyrna_py_to_array_index(PointerRNA *ptr,
+ PropertyRNA *prop,
+ int arraydim,
+ int arrayoffset,
+ int index,
+ PyObject *py,
+ const char *error_prefix)
{
- int ret;
- switch (RNA_property_type(prop)) {
- case PROP_FLOAT:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_float(ptr, prop, &convert_item);
-
- ret = py_to_array_index(
- py, ptr, prop, arraydim, arrayoffset, index,
- py_float_check, "float",
- &convert_item, float_set_index, error_prefix);
- break;
- }
- case PROP_INT:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_int(ptr, prop, &convert_item);
-
- ret = py_to_array_index(
- py, ptr, prop, arraydim, arrayoffset, index,
- py_int_check, "int",
- &convert_item, int_set_index, error_prefix);
- break;
- }
- case PROP_BOOLEAN:
- {
- ItemConvert_FuncArg convert_item;
- convert_item_init_bool(ptr, prop, &convert_item);
-
- ret = py_to_array_index(
- py, ptr, prop, arraydim, arrayoffset, index,
- py_bool_check, "boolean",
- &convert_item, bool_set_index, error_prefix);
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_TypeError, "not an array type");
- ret = -1;
- break;
- }
- }
-
- return ret;
+ int ret;
+ switch (RNA_property_type(prop)) {
+ case PROP_FLOAT: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_float(ptr, prop, &convert_item);
+
+ ret = py_to_array_index(py,
+ ptr,
+ prop,
+ arraydim,
+ arrayoffset,
+ index,
+ py_float_check,
+ "float",
+ &convert_item,
+ float_set_index,
+ error_prefix);
+ break;
+ }
+ case PROP_INT: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_int(ptr, prop, &convert_item);
+
+ ret = py_to_array_index(py,
+ ptr,
+ prop,
+ arraydim,
+ arrayoffset,
+ index,
+ py_int_check,
+ "int",
+ &convert_item,
+ int_set_index,
+ error_prefix);
+ break;
+ }
+ case PROP_BOOLEAN: {
+ ItemConvert_FuncArg convert_item;
+ convert_item_init_bool(ptr, prop, &convert_item);
+
+ ret = py_to_array_index(py,
+ ptr,
+ prop,
+ arraydim,
+ arrayoffset,
+ index,
+ py_bool_check,
+ "boolean",
+ &convert_item,
+ bool_set_index,
+ error_prefix);
+ break;
+ }
+ default: {
+ PyErr_SetString(PyExc_TypeError, "not an array type");
+ ret = -1;
+ break;
+ }
+ }
+
+ return ret;
}
PyObject *pyrna_array_index(PointerRNA *ptr, PropertyRNA *prop, int index)
{
- PyObject *item;
-
- switch (RNA_property_type(prop)) {
- case PROP_FLOAT:
- item = PyFloat_FromDouble(RNA_property_float_get_index(ptr, prop, index));
- break;
- case PROP_BOOLEAN:
- item = PyBool_FromLong(RNA_property_boolean_get_index(ptr, prop, index));
- break;
- case PROP_INT:
- item = PyLong_FromLong(RNA_property_int_get_index(ptr, prop, index));
- break;
- default:
- PyErr_SetString(PyExc_TypeError, "not an array type");
- item = NULL;
- break;
- }
-
- return item;
+ PyObject *item;
+
+ switch (RNA_property_type(prop)) {
+ case PROP_FLOAT:
+ item = PyFloat_FromDouble(RNA_property_float_get_index(ptr, prop, index));
+ break;
+ case PROP_BOOLEAN:
+ item = PyBool_FromLong(RNA_property_boolean_get_index(ptr, prop, index));
+ break;
+ case PROP_INT:
+ item = PyLong_FromLong(RNA_property_int_get_index(ptr, prop, index));
+ break;
+ default:
+ PyErr_SetString(PyExc_TypeError, "not an array type");
+ item = NULL;
+ break;
+ }
+
+ return item;
}
#if 0
@@ -743,222 +885,222 @@ PyObject *pyrna_array_index(PointerRNA *ptr, PropertyRNA *prop, int index)
/* Given an array property, creates an N-dimensional tuple of values. */
static PyObject *pyrna_py_from_array_internal(PointerRNA *ptr, PropertyRNA *prop, int dim, int *index)
{
- PyObject *tuple;
- int i, len;
- int totdim = RNA_property_array_dimension(ptr, prop, NULL);
+ PyObject *tuple;
+ int i, len;
+ int totdim = RNA_property_array_dimension(ptr, prop, NULL);
- len = RNA_property_multi_array_length(ptr, prop, dim);
+ len = RNA_property_multi_array_length(ptr, prop, dim);
- tuple = PyTuple_New(len);
+ tuple = PyTuple_New(len);
- for (i = 0; i < len; i++) {
- PyObject *item;
+ for (i = 0; i < len; i++) {
+ PyObject *item;
- if (dim + 1 < totdim) {
- item = pyrna_py_from_array_internal(ptr, prop, dim + 1, index);
- }
- else {
- item = pyrna_array_index(ptr, prop, *index);
- *index = *index + 1;
- }
+ if (dim + 1 < totdim) {
+ item = pyrna_py_from_array_internal(ptr, prop, dim + 1, index);
+ }
+ else {
+ item = pyrna_array_index(ptr, prop, *index);
+ *index = *index + 1;
+ }
- if (!item) {
- Py_DECREF(tuple);
- return NULL;
- }
+ if (!item) {
+ Py_DECREF(tuple);
+ return NULL;
+ }
- PyTuple_SET_ITEM(tuple, i, item);
- }
+ PyTuple_SET_ITEM(tuple, i, item);
+ }
- return tuple;
+ return tuple;
}
#endif
-PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, int index)
+PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self,
+ PointerRNA *ptr,
+ PropertyRNA *prop,
+ int index)
{
- int totdim, arraydim, arrayoffset, dimsize[MAX_ARRAY_DIMENSION], i, len;
- BPy_PropertyArrayRNA *ret = NULL;
-
- arraydim = self ? self->arraydim : 0;
- arrayoffset = self ? self->arrayoffset : 0;
-
- /* just in case check */
- len = RNA_property_multi_array_length(ptr, prop, arraydim);
- if (index >= len || index < 0) {
- /* this shouldn't happen because higher level funcs must check for invalid index */
- CLOG_WARN(BPY_LOG_RNA, "invalid index %d for array with length=%d", index, len);
-
- PyErr_SetString(PyExc_IndexError, "out of range");
- return NULL;
- }
-
- totdim = RNA_property_array_dimension(ptr, prop, dimsize);
-
- if (arraydim + 1 < totdim) {
- ret = (BPy_PropertyArrayRNA *)pyrna_prop_CreatePyObject(ptr, prop);
- ret->arraydim = arraydim + 1;
-
- /* arr[3][4][5]
- *
- * x = arr[2]
- * index = 0 + 2 * 4 * 5
- *
- * x = arr[2][3]
- * index = offset + 3 * 5 */
-
- for (i = arraydim + 1; i < totdim; i++) {
- index *= dimsize[i];
- }
-
- ret->arrayoffset = arrayoffset + index;
- }
- else {
- index = arrayoffset + index;
- ret = (BPy_PropertyArrayRNA *)pyrna_array_index(ptr, prop, index);
- }
-
- return (PyObject *)ret;
+ int totdim, arraydim, arrayoffset, dimsize[MAX_ARRAY_DIMENSION], i, len;
+ BPy_PropertyArrayRNA *ret = NULL;
+
+ arraydim = self ? self->arraydim : 0;
+ arrayoffset = self ? self->arrayoffset : 0;
+
+ /* just in case check */
+ len = RNA_property_multi_array_length(ptr, prop, arraydim);
+ if (index >= len || index < 0) {
+ /* this shouldn't happen because higher level funcs must check for invalid index */
+ CLOG_WARN(BPY_LOG_RNA, "invalid index %d for array with length=%d", index, len);
+
+ PyErr_SetString(PyExc_IndexError, "out of range");
+ return NULL;
+ }
+
+ totdim = RNA_property_array_dimension(ptr, prop, dimsize);
+
+ if (arraydim + 1 < totdim) {
+ ret = (BPy_PropertyArrayRNA *)pyrna_prop_CreatePyObject(ptr, prop);
+ ret->arraydim = arraydim + 1;
+
+ /* arr[3][4][5]
+ *
+ * x = arr[2]
+ * index = 0 + 2 * 4 * 5
+ *
+ * x = arr[2][3]
+ * index = offset + 3 * 5 */
+
+ for (i = arraydim + 1; i < totdim; i++) {
+ index *= dimsize[i];
+ }
+
+ ret->arrayoffset = arrayoffset + index;
+ }
+ else {
+ index = arrayoffset + index;
+ ret = (BPy_PropertyArrayRNA *)pyrna_array_index(ptr, prop, index);
+ }
+
+ return (PyObject *)ret;
}
PyObject *pyrna_py_from_array(PointerRNA *ptr, PropertyRNA *prop)
{
- PyObject *ret;
+ PyObject *ret;
- ret = pyrna_math_object_from_array(ptr, prop);
+ ret = pyrna_math_object_from_array(ptr, prop);
- /* is this a maths object? */
- if (ret) {
- return ret;
- }
+ /* is this a maths object? */
+ if (ret) {
+ return ret;
+ }
- return pyrna_prop_CreatePyObject(ptr, prop);
+ return pyrna_prop_CreatePyObject(ptr, prop);
}
/* TODO, multi-dimensional arrays */
int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
{
- int len = RNA_property_array_length(ptr, prop);
- int type;
- int i;
-
- if (len == 0) {
- /* possible with dynamic arrays */
- return 0;
- }
-
- if (RNA_property_array_dimension(ptr, prop, NULL) > 1) {
- PyErr_SetString(PyExc_TypeError, "PropertyRNA - multi dimensional arrays not supported yet");
- return -1;
- }
-
- type = RNA_property_type(prop);
-
- switch (type) {
- case PROP_FLOAT:
- {
- float value_f = PyFloat_AsDouble(value);
- if (value_f == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- return 0;
- }
- else {
- float tmp[32];
- float *tmp_arr;
-
- if (len * sizeof(float) > sizeof(tmp)) {
- tmp_arr = PyMem_MALLOC(len * sizeof(float));
- }
- else {
- tmp_arr = tmp;
- }
-
- RNA_property_float_get_array(ptr, prop, tmp_arr);
-
- for (i = 0; i < len; i++) {
- if (tmp_arr[i] == value_f) {
- break;
- }
- }
-
- if (tmp_arr != tmp) {
- PyMem_FREE(tmp_arr);
- }
-
- return i < len ? 1 : 0;
- }
- break;
- }
- case PROP_INT:
- {
- int value_i = PyC_Long_AsI32(value);
- if (value_i == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- return 0;
- }
- else {
- int tmp[32];
- int *tmp_arr;
-
- if (len * sizeof(int) > sizeof(tmp)) {
- tmp_arr = PyMem_MALLOC(len * sizeof(int));
- }
- else {
- tmp_arr = tmp;
- }
-
- RNA_property_int_get_array(ptr, prop, tmp_arr);
-
- for (i = 0; i < len; i++) {
- if (tmp_arr[i] == value_i) {
- break;
- }
- }
-
- if (tmp_arr != tmp) {
- PyMem_FREE(tmp_arr);
- }
-
- return i < len ? 1 : 0;
- }
- break;
- }
- case PROP_BOOLEAN:
- {
- int value_i = PyC_Long_AsBool(value);
- if (value_i == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- return 0;
- }
- else {
- bool tmp[32];
- bool *tmp_arr;
-
- if (len * sizeof(bool) > sizeof(tmp)) {
- tmp_arr = PyMem_MALLOC(len * sizeof(bool));
- }
- else {
- tmp_arr = tmp;
- }
-
- RNA_property_boolean_get_array(ptr, prop, tmp_arr);
-
- for (i = 0; i < len; i++) {
- if (tmp_arr[i] == value_i) {
- break;
- }
- }
-
- if (tmp_arr != tmp) {
- PyMem_FREE(tmp_arr);
- }
-
- return i < len ? 1 : 0;
- }
- break;
- }
- }
-
- /* should never reach this */
- PyErr_SetString(PyExc_TypeError, "PropertyRNA - type not in float/bool/int");
- return -1;
+ int len = RNA_property_array_length(ptr, prop);
+ int type;
+ int i;
+
+ if (len == 0) {
+ /* possible with dynamic arrays */
+ return 0;
+ }
+
+ if (RNA_property_array_dimension(ptr, prop, NULL) > 1) {
+ PyErr_SetString(PyExc_TypeError, "PropertyRNA - multi dimensional arrays not supported yet");
+ return -1;
+ }
+
+ type = RNA_property_type(prop);
+
+ switch (type) {
+ case PROP_FLOAT: {
+ float value_f = PyFloat_AsDouble(value);
+ if (value_f == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ return 0;
+ }
+ else {
+ float tmp[32];
+ float *tmp_arr;
+
+ if (len * sizeof(float) > sizeof(tmp)) {
+ tmp_arr = PyMem_MALLOC(len * sizeof(float));
+ }
+ else {
+ tmp_arr = tmp;
+ }
+
+ RNA_property_float_get_array(ptr, prop, tmp_arr);
+
+ for (i = 0; i < len; i++) {
+ if (tmp_arr[i] == value_f) {
+ break;
+ }
+ }
+
+ if (tmp_arr != tmp) {
+ PyMem_FREE(tmp_arr);
+ }
+
+ return i < len ? 1 : 0;
+ }
+ break;
+ }
+ case PROP_INT: {
+ int value_i = PyC_Long_AsI32(value);
+ if (value_i == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ return 0;
+ }
+ else {
+ int tmp[32];
+ int *tmp_arr;
+
+ if (len * sizeof(int) > sizeof(tmp)) {
+ tmp_arr = PyMem_MALLOC(len * sizeof(int));
+ }
+ else {
+ tmp_arr = tmp;
+ }
+
+ RNA_property_int_get_array(ptr, prop, tmp_arr);
+
+ for (i = 0; i < len; i++) {
+ if (tmp_arr[i] == value_i) {
+ break;
+ }
+ }
+
+ if (tmp_arr != tmp) {
+ PyMem_FREE(tmp_arr);
+ }
+
+ return i < len ? 1 : 0;
+ }
+ break;
+ }
+ case PROP_BOOLEAN: {
+ int value_i = PyC_Long_AsBool(value);
+ if (value_i == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ return 0;
+ }
+ else {
+ bool tmp[32];
+ bool *tmp_arr;
+
+ if (len * sizeof(bool) > sizeof(tmp)) {
+ tmp_arr = PyMem_MALLOC(len * sizeof(bool));
+ }
+ else {
+ tmp_arr = tmp;
+ }
+
+ RNA_property_boolean_get_array(ptr, prop, tmp_arr);
+
+ for (i = 0; i < len; i++) {
+ if (tmp_arr[i] == value_i) {
+ break;
+ }
+ }
+
+ if (tmp_arr != tmp) {
+ PyMem_FREE(tmp_arr);
+ }
+
+ return i < len ? 1 : 0;
+ }
+ break;
+ }
+ }
+
+ /* should never reach this */
+ PyErr_SetString(PyExc_TypeError, "PropertyRNA - type not in float/bool/int");
+ return -1;
}
diff --git a/source/blender/python/intern/bpy_rna_callback.c b/source/blender/python/intern/bpy_rna_callback.c
index 30ea657200c..b24a28229aa 100644
--- a/source/blender/python/intern/bpy_rna_callback.c
+++ b/source/blender/python/intern/bpy_rna_callback.c
@@ -21,7 +21,6 @@
* extended later.
*/
-
#include <Python.h>
#include "RNA_types.h"
@@ -52,396 +51,429 @@ static const char *rna_capsual_id = "RNA_HANDLE";
static const char *rna_capsual_id_invalid = "RNA_HANDLE_REMOVED";
static const EnumPropertyItem region_draw_mode_items[] = {
- {REGION_DRAW_POST_PIXEL, "POST_PIXEL", 0, "Post Pixel", ""},
- {REGION_DRAW_POST_VIEW, "POST_VIEW", 0, "Post View", ""},
- {REGION_DRAW_PRE_VIEW, "PRE_VIEW", 0, "Pre View", ""},
- {0, NULL, 0, NULL, NULL},
+ {REGION_DRAW_POST_PIXEL, "POST_PIXEL", 0, "Post Pixel", ""},
+ {REGION_DRAW_POST_VIEW, "POST_VIEW", 0, "Post View", ""},
+ {REGION_DRAW_PRE_VIEW, "PRE_VIEW", 0, "Pre View", ""},
+ {0, NULL, 0, NULL, NULL},
};
static void cb_region_draw(const bContext *C, ARegion *UNUSED(ar), void *customdata)
{
- PyObject *cb_func, *cb_args, *result;
- PyGILState_STATE gilstate;
+ PyObject *cb_func, *cb_args, *result;
+ PyGILState_STATE gilstate;
- bpy_context_set((bContext *)C, &gilstate);
+ bpy_context_set((bContext *)C, &gilstate);
- cb_func = PyTuple_GET_ITEM((PyObject *)customdata, 1);
- cb_args = PyTuple_GET_ITEM((PyObject *)customdata, 2);
- result = PyObject_CallObject(cb_func, cb_args);
+ cb_func = PyTuple_GET_ITEM((PyObject *)customdata, 1);
+ cb_args = PyTuple_GET_ITEM((PyObject *)customdata, 2);
+ result = PyObject_CallObject(cb_func, cb_args);
- if (result) {
- Py_DECREF(result);
- }
- else {
- PyErr_Print();
- PyErr_Clear();
- }
+ if (result) {
+ Py_DECREF(result);
+ }
+ else {
+ PyErr_Print();
+ PyErr_Clear();
+ }
- bpy_context_clear((bContext *)C, &gilstate);
+ bpy_context_clear((bContext *)C, &gilstate);
}
/* We could make generic utility */
static PyObject *PyC_Tuple_CopySized(PyObject *src, int len_dst)
{
- PyObject *dst = PyTuple_New(len_dst);
- int len_src = PyTuple_GET_SIZE(src);
- BLI_assert(len_src <= len_dst);
- for (int i = 0; i < len_src; i++) {
- PyObject *item = PyTuple_GET_ITEM(src, i);
- PyTuple_SET_ITEM(dst, i, item);
- Py_INCREF(item);
- }
- return dst;
+ PyObject *dst = PyTuple_New(len_dst);
+ int len_src = PyTuple_GET_SIZE(src);
+ BLI_assert(len_src <= len_dst);
+ for (int i = 0; i < len_src; i++) {
+ PyObject *item = PyTuple_GET_ITEM(src, i);
+ PyTuple_SET_ITEM(dst, i, item);
+ Py_INCREF(item);
+ }
+ return dst;
}
static void cb_wm_cursor_draw(bContext *C, int x, int y, void *customdata)
{
- PyObject *cb_func, *cb_args, *result;
- PyGILState_STATE gilstate;
+ PyObject *cb_func, *cb_args, *result;
+ PyGILState_STATE gilstate;
- bpy_context_set((bContext *)C, &gilstate);
+ bpy_context_set((bContext *)C, &gilstate);
- cb_func = PyTuple_GET_ITEM((PyObject *)customdata, 1);
- cb_args = PyTuple_GET_ITEM((PyObject *)customdata, 2);
+ cb_func = PyTuple_GET_ITEM((PyObject *)customdata, 1);
+ cb_args = PyTuple_GET_ITEM((PyObject *)customdata, 2);
- const int cb_args_len = PyTuple_GET_SIZE(cb_args);
+ const int cb_args_len = PyTuple_GET_SIZE(cb_args);
- PyObject *cb_args_xy = PyTuple_New(2);
- PyTuple_SET_ITEMS(cb_args_xy, PyLong_FromLong(x), PyLong_FromLong(y));
+ PyObject *cb_args_xy = PyTuple_New(2);
+ PyTuple_SET_ITEMS(cb_args_xy, PyLong_FromLong(x), PyLong_FromLong(y));
- PyObject *cb_args_with_xy = PyC_Tuple_CopySized(cb_args, cb_args_len + 1);
- PyTuple_SET_ITEM(cb_args_with_xy, cb_args_len, cb_args_xy);
+ PyObject *cb_args_with_xy = PyC_Tuple_CopySized(cb_args, cb_args_len + 1);
+ PyTuple_SET_ITEM(cb_args_with_xy, cb_args_len, cb_args_xy);
- result = PyObject_CallObject(cb_func, cb_args_with_xy);
+ result = PyObject_CallObject(cb_func, cb_args_with_xy);
- Py_DECREF(cb_args_with_xy);
+ Py_DECREF(cb_args_with_xy);
- if (result) {
- Py_DECREF(result);
- }
- else {
- PyErr_Print();
- PyErr_Clear();
- }
+ if (result) {
+ Py_DECREF(result);
+ }
+ else {
+ PyErr_Print();
+ PyErr_Clear();
+ }
- bpy_context_clear((bContext *)C, &gilstate);
+ bpy_context_clear((bContext *)C, &gilstate);
}
#if 0
PyObject *pyrna_callback_add(BPy_StructRNA *self, PyObject *args)
{
- void *handle;
-
- PyObject *cb_func, *cb_args;
- char *cb_event_str = NULL;
- int cb_event;
-
- if (!PyArg_ParseTuple(args, "OO!|s:bpy_struct.callback_add", &cb_func, &PyTuple_Type, &cb_args, &cb_event_str)) {
- return NULL;
- }
-
- if (!PyCallable_Check(cb_func)) {
- PyErr_SetString(PyExc_TypeError, "callback_add(): first argument isn't callable");
- return NULL;
- }
-
- if (RNA_struct_is_a(self->ptr.type, &RNA_Region)) {
- if (cb_event_str) {
- if (pyrna_enum_value_from_id(
- region_draw_mode_items, cb_event_str,
- &cb_event, "bpy_struct.callback_add()") == -1)
- {
- return NULL;
- }
- }
- else {
- cb_event = REGION_DRAW_POST_PIXEL;
- }
-
- handle = ED_region_draw_cb_activate(((ARegion *)self->ptr.data)->type, cb_region_draw, (void *)args, cb_event);
- Py_INCREF(args);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
- return NULL;
- }
-
- return PyCapsule_New((void *)handle, rna_capsual_id, NULL);
+ void *handle;
+
+ PyObject *cb_func, *cb_args;
+ char *cb_event_str = NULL;
+ int cb_event;
+
+ if (!PyArg_ParseTuple(args, "OO!|s:bpy_struct.callback_add", &cb_func, &PyTuple_Type, &cb_args, &cb_event_str)) {
+ return NULL;
+ }
+
+ if (!PyCallable_Check(cb_func)) {
+ PyErr_SetString(PyExc_TypeError, "callback_add(): first argument isn't callable");
+ return NULL;
+ }
+
+ if (RNA_struct_is_a(self->ptr.type, &RNA_Region)) {
+ if (cb_event_str) {
+ if (pyrna_enum_value_from_id(
+ region_draw_mode_items, cb_event_str,
+ &cb_event, "bpy_struct.callback_add()") == -1)
+ {
+ return NULL;
+ }
+ }
+ else {
+ cb_event = REGION_DRAW_POST_PIXEL;
+ }
+
+ handle = ED_region_draw_cb_activate(((ARegion *)self->ptr.data)->type, cb_region_draw, (void *)args, cb_event);
+ Py_INCREF(args);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
+ return NULL;
+ }
+
+ return PyCapsule_New((void *)handle, rna_capsual_id, NULL);
}
PyObject *pyrna_callback_remove(BPy_StructRNA *self, PyObject *args)
{
- PyObject *py_handle;
- void *handle;
- void *customdata;
+ PyObject *py_handle;
+ void *handle;
+ void *customdata;
- if (!PyArg_ParseTuple(args, "O!:callback_remove", &PyCapsule_Type, &py_handle)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O!:callback_remove", &PyCapsule_Type, &py_handle)) {
+ return NULL;
+ }
- handle = PyCapsule_GetPointer(py_handle, rna_capsual_id);
+ handle = PyCapsule_GetPointer(py_handle, rna_capsual_id);
- if (handle == NULL) {
- PyErr_SetString(PyExc_ValueError, "callback_remove(handle): NULL handle given, invalid or already removed");
- return NULL;
- }
+ if (handle == NULL) {
+ PyErr_SetString(PyExc_ValueError, "callback_remove(handle): NULL handle given, invalid or already removed");
+ return NULL;
+ }
- if (RNA_struct_is_a(self->ptr.type, &RNA_Region)) {
- customdata = ED_region_draw_cb_customdata(handle);
- Py_DECREF((PyObject *)customdata);
+ if (RNA_struct_is_a(self->ptr.type, &RNA_Region)) {
+ customdata = ED_region_draw_cb_customdata(handle);
+ Py_DECREF((PyObject *)customdata);
- ED_region_draw_cb_exit(((ARegion *)self->ptr.data)->type, handle);
- }
- else {
- PyErr_SetString(PyExc_TypeError, "callback_remove(): type does not support callbacks");
- return NULL;
- }
+ ED_region_draw_cb_exit(((ARegion *)self->ptr.data)->type, handle);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "callback_remove(): type does not support callbacks");
+ return NULL;
+ }
- /* don't allow reuse */
- PyCapsule_SetName(py_handle, rna_capsual_id_invalid);
+ /* don't allow reuse */
+ PyCapsule_SetName(py_handle, rna_capsual_id_invalid);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
#endif
/* reverse of rna_Space_refine() */
static eSpace_Type rna_Space_refine_reverse(StructRNA *srna)
{
- if (srna == &RNA_SpaceView3D) { return SPACE_VIEW3D; }
- if (srna == &RNA_SpaceGraphEditor) { return SPACE_GRAPH; }
- if (srna == &RNA_SpaceOutliner) { return SPACE_OUTLINER; }
- if (srna == &RNA_SpaceProperties) { return SPACE_PROPERTIES; }
- if (srna == &RNA_SpaceFileBrowser) { return SPACE_FILE; }
- if (srna == &RNA_SpaceImageEditor) { return SPACE_IMAGE; }
- if (srna == &RNA_SpaceInfo) { return SPACE_INFO; }
- if (srna == &RNA_SpaceSequenceEditor) { return SPACE_SEQ; }
- if (srna == &RNA_SpaceTextEditor) { return SPACE_TEXT; }
- if (srna == &RNA_SpaceDopeSheetEditor) { return SPACE_ACTION; }
- if (srna == &RNA_SpaceNLA) { return SPACE_NLA; }
- if (srna == &RNA_SpaceNodeEditor) { return SPACE_NODE; }
- if (srna == &RNA_SpaceConsole) { return SPACE_CONSOLE; }
- if (srna == &RNA_SpacePreferences) { return SPACE_USERPREF; }
- if (srna == &RNA_SpaceClipEditor) { return SPACE_CLIP; }
- return SPACE_EMPTY;
+ if (srna == &RNA_SpaceView3D) {
+ return SPACE_VIEW3D;
+ }
+ if (srna == &RNA_SpaceGraphEditor) {
+ return SPACE_GRAPH;
+ }
+ if (srna == &RNA_SpaceOutliner) {
+ return SPACE_OUTLINER;
+ }
+ if (srna == &RNA_SpaceProperties) {
+ return SPACE_PROPERTIES;
+ }
+ if (srna == &RNA_SpaceFileBrowser) {
+ return SPACE_FILE;
+ }
+ if (srna == &RNA_SpaceImageEditor) {
+ return SPACE_IMAGE;
+ }
+ if (srna == &RNA_SpaceInfo) {
+ return SPACE_INFO;
+ }
+ if (srna == &RNA_SpaceSequenceEditor) {
+ return SPACE_SEQ;
+ }
+ if (srna == &RNA_SpaceTextEditor) {
+ return SPACE_TEXT;
+ }
+ if (srna == &RNA_SpaceDopeSheetEditor) {
+ return SPACE_ACTION;
+ }
+ if (srna == &RNA_SpaceNLA) {
+ return SPACE_NLA;
+ }
+ if (srna == &RNA_SpaceNodeEditor) {
+ return SPACE_NODE;
+ }
+ if (srna == &RNA_SpaceConsole) {
+ return SPACE_CONSOLE;
+ }
+ if (srna == &RNA_SpacePreferences) {
+ return SPACE_USERPREF;
+ }
+ if (srna == &RNA_SpaceClipEditor) {
+ return SPACE_CLIP;
+ }
+ return SPACE_EMPTY;
}
PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args)
{
- void *handle;
- PyObject *cls;
- PyObject *cb_func, *cb_args;
- StructRNA *srna;
-
- if (PyTuple_GET_SIZE(args) < 2) {
- PyErr_SetString(PyExc_ValueError, "handler_add(handler): expected at least 2 args");
- return NULL;
- }
-
- cls = PyTuple_GET_ITEM(args, 0);
- if (!(srna = pyrna_struct_as_srna(cls, false, "handler_add"))) {
- return NULL;
- }
- cb_func = PyTuple_GET_ITEM(args, 1);
- if (!PyCallable_Check(cb_func)) {
- PyErr_SetString(PyExc_TypeError, "first argument isn't callable");
- return NULL;
- }
-
- /* class specific callbacks */
-
- if (srna == &RNA_WindowManager) {
- const char *error_prefix = "WindowManager.draw_cursor_add";
- struct {
- const char *space_type_str;
- const char *region_type_str;
-
- int space_type;
- int region_type;
- } params = {
- .space_type_str = NULL,
- .region_type_str = NULL,
- .space_type = SPACE_TYPE_ANY,
- .region_type = RGN_TYPE_ANY,
- };
-
- if (!PyArg_ParseTuple(
- args, "OOO!|ss:WindowManager.draw_cursor_add",
- &cls, &cb_func, /* already assigned, no matter */
- &PyTuple_Type, &cb_args, &params.space_type_str, &params.region_type_str))
- {
- return NULL;
- }
-
- if (params.space_type_str && pyrna_enum_value_from_id(
- rna_enum_space_type_items, params.space_type_str,
- &params.space_type, error_prefix) == -1)
- {
- return NULL;
- }
- else if (params.region_type_str && pyrna_enum_value_from_id(
- rna_enum_region_type_items, params.region_type_str,
- &params.region_type, error_prefix) == -1)
- {
- return NULL;
- }
-
- bContext *C = BPy_GetContext();
- struct wmWindowManager *wm = CTX_wm_manager(C);
- handle = WM_paint_cursor_activate(
- wm,
- params.space_type, params.region_type,
- NULL, cb_wm_cursor_draw, (void *)args);
- }
- else if (RNA_struct_is_a(srna, &RNA_Space)) {
- const char *error_prefix = "Space.draw_handler_add";
- struct {
- const char *region_type_str;
- const char *event_str;
-
- int region_type;
- int event;
- } params;
-
- if (!PyArg_ParseTuple(
- args, "OOO!ss:Space.draw_handler_add",
- &cls, &cb_func, /* already assigned, no matter */
- &PyTuple_Type, &cb_args,
- &params.region_type_str, &params.event_str))
- {
- return NULL;
- }
-
- if (pyrna_enum_value_from_id(
- region_draw_mode_items, params.event_str,
- &params.event, error_prefix) == -1)
- {
- return NULL;
- }
- else if (pyrna_enum_value_from_id(
- rna_enum_region_type_items, params.region_type_str,
- &params.region_type, error_prefix) == -1)
- {
- return NULL;
- }
- else {
- const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
- if (spaceid == SPACE_EMPTY) {
- PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
- return NULL;
- }
- else {
- SpaceType *st = BKE_spacetype_from_id(spaceid);
- ARegionType *art = BKE_regiontype_from_id(st, params.region_type);
- if (art == NULL) {
- PyErr_Format(PyExc_TypeError, "region type '%.200s' not in space", params.region_type_str);
- return NULL;
- }
- handle = ED_region_draw_cb_activate(art, cb_region_draw, (void *)args, params.event);
- }
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
- return NULL;
- }
-
- PyObject *ret = PyCapsule_New((void *)handle, rna_capsual_id, NULL);
-
- /* Store 'args' in context as well as the handler custom-data,
- * because the handle may be freed by Blender (new file, new window... etc) */
- PyCapsule_SetContext(ret, args);
- Py_INCREF(args);
-
- return ret;
+ void *handle;
+ PyObject *cls;
+ PyObject *cb_func, *cb_args;
+ StructRNA *srna;
+
+ if (PyTuple_GET_SIZE(args) < 2) {
+ PyErr_SetString(PyExc_ValueError, "handler_add(handler): expected at least 2 args");
+ return NULL;
+ }
+
+ cls = PyTuple_GET_ITEM(args, 0);
+ if (!(srna = pyrna_struct_as_srna(cls, false, "handler_add"))) {
+ return NULL;
+ }
+ cb_func = PyTuple_GET_ITEM(args, 1);
+ if (!PyCallable_Check(cb_func)) {
+ PyErr_SetString(PyExc_TypeError, "first argument isn't callable");
+ return NULL;
+ }
+
+ /* class specific callbacks */
+
+ if (srna == &RNA_WindowManager) {
+ const char *error_prefix = "WindowManager.draw_cursor_add";
+ struct {
+ const char *space_type_str;
+ const char *region_type_str;
+
+ int space_type;
+ int region_type;
+ } params = {
+ .space_type_str = NULL,
+ .region_type_str = NULL,
+ .space_type = SPACE_TYPE_ANY,
+ .region_type = RGN_TYPE_ANY,
+ };
+
+ if (!PyArg_ParseTuple(args,
+ "OOO!|ss:WindowManager.draw_cursor_add",
+ &cls,
+ &cb_func, /* already assigned, no matter */
+ &PyTuple_Type,
+ &cb_args,
+ &params.space_type_str,
+ &params.region_type_str)) {
+ return NULL;
+ }
+
+ if (params.space_type_str && pyrna_enum_value_from_id(rna_enum_space_type_items,
+ params.space_type_str,
+ &params.space_type,
+ error_prefix) == -1) {
+ return NULL;
+ }
+ else if (params.region_type_str && pyrna_enum_value_from_id(rna_enum_region_type_items,
+ params.region_type_str,
+ &params.region_type,
+ error_prefix) == -1) {
+ return NULL;
+ }
+
+ bContext *C = BPy_GetContext();
+ struct wmWindowManager *wm = CTX_wm_manager(C);
+ handle = WM_paint_cursor_activate(
+ wm, params.space_type, params.region_type, NULL, cb_wm_cursor_draw, (void *)args);
+ }
+ else if (RNA_struct_is_a(srna, &RNA_Space)) {
+ const char *error_prefix = "Space.draw_handler_add";
+ struct {
+ const char *region_type_str;
+ const char *event_str;
+
+ int region_type;
+ int event;
+ } params;
+
+ if (!PyArg_ParseTuple(args,
+ "OOO!ss:Space.draw_handler_add",
+ &cls,
+ &cb_func, /* already assigned, no matter */
+ &PyTuple_Type,
+ &cb_args,
+ &params.region_type_str,
+ &params.event_str)) {
+ return NULL;
+ }
+
+ if (pyrna_enum_value_from_id(
+ region_draw_mode_items, params.event_str, &params.event, error_prefix) == -1) {
+ return NULL;
+ }
+ else if (pyrna_enum_value_from_id(rna_enum_region_type_items,
+ params.region_type_str,
+ &params.region_type,
+ error_prefix) == -1) {
+ return NULL;
+ }
+ else {
+ const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
+ if (spaceid == SPACE_EMPTY) {
+ PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
+ return NULL;
+ }
+ else {
+ SpaceType *st = BKE_spacetype_from_id(spaceid);
+ ARegionType *art = BKE_regiontype_from_id(st, params.region_type);
+ if (art == NULL) {
+ PyErr_Format(
+ PyExc_TypeError, "region type '%.200s' not in space", params.region_type_str);
+ return NULL;
+ }
+ handle = ED_region_draw_cb_activate(art, cb_region_draw, (void *)args, params.event);
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
+ return NULL;
+ }
+
+ PyObject *ret = PyCapsule_New((void *)handle, rna_capsual_id, NULL);
+
+ /* Store 'args' in context as well as the handler custom-data,
+ * because the handle may be freed by Blender (new file, new window... etc) */
+ PyCapsule_SetContext(ret, args);
+ Py_INCREF(args);
+
+ return ret;
}
PyObject *pyrna_callback_classmethod_remove(PyObject *UNUSED(self), PyObject *args)
{
- PyObject *cls;
- PyObject *py_handle;
- void *handle;
- StructRNA *srna;
- bool capsule_clear = false;
-
- if (PyTuple_GET_SIZE(args) < 2) {
- PyErr_SetString(PyExc_ValueError, "callback_remove(handler): expected at least 2 args");
- return NULL;
- }
-
- cls = PyTuple_GET_ITEM(args, 0);
- if (!(srna = pyrna_struct_as_srna(cls, false, "callback_remove"))) {
- return NULL;
- }
- py_handle = PyTuple_GET_ITEM(args, 1);
- handle = PyCapsule_GetPointer(py_handle, rna_capsual_id);
- if (handle == NULL) {
- PyErr_SetString(PyExc_ValueError, "callback_remove(handler): NULL handler given, invalid or already removed");
- return NULL;
- }
- PyObject *handle_args = PyCapsule_GetContext(py_handle);
-
- if (srna == &RNA_WindowManager) {
- if (!PyArg_ParseTuple(
- args, "OO!:WindowManager.draw_cursor_remove",
- &cls, &PyCapsule_Type, &py_handle))
- {
- return NULL;
- }
- bContext *C = BPy_GetContext();
- struct wmWindowManager *wm = CTX_wm_manager(C);
- WM_paint_cursor_end(wm, handle);
- capsule_clear = true;
- }
- else if (RNA_struct_is_a(srna, &RNA_Space)) {
- const char *error_prefix = "Space.draw_handler_remove";
- struct {
- const char *region_type_str;
-
- int region_type;
- } params;
-
- if (!PyArg_ParseTuple(
- args, "OO!s:Space.draw_handler_remove",
- &cls, &PyCapsule_Type, &py_handle, /* already assigned, no matter */
- &params.region_type_str))
- {
- return NULL;
- }
-
- if (pyrna_enum_value_from_id(
- rna_enum_region_type_items, params.region_type_str,
- &params.region_type, error_prefix) == -1)
- {
- return NULL;
- }
- else {
- const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
- if (spaceid == SPACE_EMPTY) {
- PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
- return NULL;
- }
- else {
- SpaceType *st = BKE_spacetype_from_id(spaceid);
- ARegionType *art = BKE_regiontype_from_id(st, params.region_type);
- if (art == NULL) {
- PyErr_Format(PyExc_TypeError, "region type '%.200s' not in space", params.region_type_str);
- return NULL;
- }
- ED_region_draw_cb_exit(art, handle);
- capsule_clear = true;
- }
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError, "callback_remove(): type does not support callbacks");
- return NULL;
- }
-
- /* don't allow reuse */
- if (capsule_clear) {
- Py_DECREF(handle_args);
- PyCapsule_SetName(py_handle, rna_capsual_id_invalid);
- }
-
- Py_RETURN_NONE;
+ PyObject *cls;
+ PyObject *py_handle;
+ void *handle;
+ StructRNA *srna;
+ bool capsule_clear = false;
+
+ if (PyTuple_GET_SIZE(args) < 2) {
+ PyErr_SetString(PyExc_ValueError, "callback_remove(handler): expected at least 2 args");
+ return NULL;
+ }
+
+ cls = PyTuple_GET_ITEM(args, 0);
+ if (!(srna = pyrna_struct_as_srna(cls, false, "callback_remove"))) {
+ return NULL;
+ }
+ py_handle = PyTuple_GET_ITEM(args, 1);
+ handle = PyCapsule_GetPointer(py_handle, rna_capsual_id);
+ if (handle == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "callback_remove(handler): NULL handler given, invalid or already removed");
+ return NULL;
+ }
+ PyObject *handle_args = PyCapsule_GetContext(py_handle);
+
+ if (srna == &RNA_WindowManager) {
+ if (!PyArg_ParseTuple(
+ args, "OO!:WindowManager.draw_cursor_remove", &cls, &PyCapsule_Type, &py_handle)) {
+ return NULL;
+ }
+ bContext *C = BPy_GetContext();
+ struct wmWindowManager *wm = CTX_wm_manager(C);
+ WM_paint_cursor_end(wm, handle);
+ capsule_clear = true;
+ }
+ else if (RNA_struct_is_a(srna, &RNA_Space)) {
+ const char *error_prefix = "Space.draw_handler_remove";
+ struct {
+ const char *region_type_str;
+
+ int region_type;
+ } params;
+
+ if (!PyArg_ParseTuple(args,
+ "OO!s:Space.draw_handler_remove",
+ &cls,
+ &PyCapsule_Type,
+ &py_handle, /* already assigned, no matter */
+ &params.region_type_str)) {
+ return NULL;
+ }
+
+ if (pyrna_enum_value_from_id(rna_enum_region_type_items,
+ params.region_type_str,
+ &params.region_type,
+ error_prefix) == -1) {
+ return NULL;
+ }
+ else {
+ const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
+ if (spaceid == SPACE_EMPTY) {
+ PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
+ return NULL;
+ }
+ else {
+ SpaceType *st = BKE_spacetype_from_id(spaceid);
+ ARegionType *art = BKE_regiontype_from_id(st, params.region_type);
+ if (art == NULL) {
+ PyErr_Format(
+ PyExc_TypeError, "region type '%.200s' not in space", params.region_type_str);
+ return NULL;
+ }
+ ED_region_draw_cb_exit(art, handle);
+ capsule_clear = true;
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "callback_remove(): type does not support callbacks");
+ return NULL;
+ }
+
+ /* don't allow reuse */
+ if (capsule_clear) {
+ Py_DECREF(handle_args);
+ PyCapsule_SetName(py_handle, rna_capsual_id_invalid);
+ }
+
+ Py_RETURN_NONE;
}
diff --git a/source/blender/python/intern/bpy_rna_callback.h b/source/blender/python/intern/bpy_rna_callback.h
index 6a13e2de9a7..71e1f71f8af 100644
--- a/source/blender/python/intern/bpy_rna_callback.h
+++ b/source/blender/python/intern/bpy_rna_callback.h
@@ -32,4 +32,4 @@ PyObject *pyrna_callback_remove(BPy_StructRNA *self, PyObject *args);
PyObject *pyrna_callback_classmethod_add(PyObject *cls, PyObject *args);
PyObject *pyrna_callback_classmethod_remove(PyObject *cls, PyObject *args);
-#endif /* __BPY_RNA_CALLBACK_H__ */
+#endif /* __BPY_RNA_CALLBACK_H__ */
diff --git a/source/blender/python/intern/bpy_rna_driver.c b/source/blender/python/intern/bpy_rna_driver.c
index 91030f7ac36..e9e8d05aa74 100644
--- a/source/blender/python/intern/bpy_rna_driver.c
+++ b/source/blender/python/intern/bpy_rna_driver.c
@@ -32,73 +32,69 @@
#include "bpy_rna.h"
-#include "bpy_rna_driver.h" /* own include */
-
+#include "bpy_rna_driver.h" /* own include */
/**
* A version of #driver_get_variable_value which returns a PyObject.
*/
-PyObject *pyrna_driver_get_variable_value(
- struct ChannelDriver *driver, struct DriverTarget *dtar)
+PyObject *pyrna_driver_get_variable_value(struct ChannelDriver *driver, struct DriverTarget *dtar)
{
- PyObject *driver_arg = NULL;
- PointerRNA ptr;
- PropertyRNA *prop = NULL;
- int index;
+ PyObject *driver_arg = NULL;
+ PointerRNA ptr;
+ PropertyRNA *prop = NULL;
+ int index;
- if (driver_get_variable_property(driver, dtar, &ptr, &prop, &index)) {
- if (prop) {
- if (index != -1) {
- if (index < RNA_property_array_length(&ptr, prop) && index >= 0) {
- /* object, property & index */
- driver_arg = pyrna_array_index(&ptr, prop, index);
- }
- else {
- /* out of range, pass */
- }
- }
- else {
- /* object & property */
- PropertyType type = RNA_property_type(prop);
- if (type == PROP_ENUM) {
- /* Note that enum's are converted to strings by default,
- * we want to avoid that, see: T52213 */
- driver_arg = PyLong_FromLong(RNA_property_enum_get(&ptr, prop));
- }
- else {
- driver_arg = pyrna_prop_to_py(&ptr, prop);
- }
- }
- }
- else {
- /* object only */
- driver_arg = pyrna_struct_CreatePyObject(&ptr);
- }
- }
- else {
- /* can't resolve path, pass */
- }
+ if (driver_get_variable_property(driver, dtar, &ptr, &prop, &index)) {
+ if (prop) {
+ if (index != -1) {
+ if (index < RNA_property_array_length(&ptr, prop) && index >= 0) {
+ /* object, property & index */
+ driver_arg = pyrna_array_index(&ptr, prop, index);
+ }
+ else {
+ /* out of range, pass */
+ }
+ }
+ else {
+ /* object & property */
+ PropertyType type = RNA_property_type(prop);
+ if (type == PROP_ENUM) {
+ /* Note that enum's are converted to strings by default,
+ * we want to avoid that, see: T52213 */
+ driver_arg = PyLong_FromLong(RNA_property_enum_get(&ptr, prop));
+ }
+ else {
+ driver_arg = pyrna_prop_to_py(&ptr, prop);
+ }
+ }
+ }
+ else {
+ /* object only */
+ driver_arg = pyrna_struct_CreatePyObject(&ptr);
+ }
+ }
+ else {
+ /* can't resolve path, pass */
+ }
- return driver_arg;
+ return driver_arg;
}
PyObject *pyrna_driver_self_from_anim_rna(PathResolvedRNA *anim_rna)
{
- return pyrna_struct_CreatePyObject(&anim_rna->ptr);
+ return pyrna_struct_CreatePyObject(&anim_rna->ptr);
}
bool pyrna_driver_is_equal_anim_rna(const PathResolvedRNA *anim_rna, const PyObject *py_anim_rna)
{
- if (BPy_StructRNA_Check(py_anim_rna)) {
- const PointerRNA *ptr_a = &anim_rna->ptr;
- const PointerRNA *ptr_b = &(((const BPy_StructRNA *)py_anim_rna)->ptr);
+ if (BPy_StructRNA_Check(py_anim_rna)) {
+ const PointerRNA *ptr_a = &anim_rna->ptr;
+ const PointerRNA *ptr_b = &(((const BPy_StructRNA *)py_anim_rna)->ptr);
- if ((ptr_a->id.data == ptr_b->id.data) &&
- (ptr_a->type == ptr_b->type) &&
- (ptr_a->data == ptr_b->data))
- {
- return true;
- }
- }
- return false;
+ if ((ptr_a->id.data == ptr_b->id.data) && (ptr_a->type == ptr_b->type) &&
+ (ptr_a->data == ptr_b->data)) {
+ return true;
+ }
+ }
+ return false;
}
diff --git a/source/blender/python/intern/bpy_rna_driver.h b/source/blender/python/intern/bpy_rna_driver.h
index 0bb34b8fe9a..36160d7c867 100644
--- a/source/blender/python/intern/bpy_rna_driver.h
+++ b/source/blender/python/intern/bpy_rna_driver.h
@@ -28,6 +28,7 @@ struct PathResolvedRNA;
PyObject *pyrna_driver_get_variable_value(struct ChannelDriver *driver, struct DriverTarget *dtar);
PyObject *pyrna_driver_self_from_anim_rna(struct PathResolvedRNA *anim_rna);
-bool pyrna_driver_is_equal_anim_rna(const struct PathResolvedRNA *anim_rna, const PyObject *py_anim_rna);
+bool pyrna_driver_is_equal_anim_rna(const struct PathResolvedRNA *anim_rna,
+ const PyObject *py_anim_rna);
-#endif /* __BPY_RNA_DRIVER_H__ */
+#endif /* __BPY_RNA_DRIVER_H__ */
diff --git a/source/blender/python/intern/bpy_rna_gizmo.c b/source/blender/python/intern/bpy_rna_gizmo.c
index 68511627d51..ec041b3054a 100644
--- a/source/blender/python/intern/bpy_rna_gizmo.c
+++ b/source/blender/python/intern/bpy_rna_gizmo.c
@@ -28,7 +28,6 @@
#include "BLI_utildefines.h"
#include "BLI_alloca.h"
-
#include "WM_api.h"
#include "WM_types.h"
@@ -44,280 +43,278 @@
#include "bpy_rna.h"
-
/* -------------------------------------------------------------------- */
/** \name Gizmo Target Property Define API
* \{ */
enum {
- BPY_GIZMO_FN_SLOT_GET = 0,
- BPY_GIZMO_FN_SLOT_SET,
- BPY_GIZMO_FN_SLOT_RANGE_GET,
+ BPY_GIZMO_FN_SLOT_GET = 0,
+ BPY_GIZMO_FN_SLOT_SET,
+ BPY_GIZMO_FN_SLOT_RANGE_GET,
};
#define BPY_GIZMO_FN_SLOT_LEN (BPY_GIZMO_FN_SLOT_RANGE_GET + 1)
struct BPyGizmoHandlerUserData {
- PyObject *fn_slots[BPY_GIZMO_FN_SLOT_LEN];
+ PyObject *fn_slots[BPY_GIZMO_FN_SLOT_LEN];
};
-static void py_rna_gizmo_handler_get_cb(
- const wmGizmo *UNUSED(gz), wmGizmoProperty *gz_prop,
- void *value_p)
+static void py_rna_gizmo_handler_get_cb(const wmGizmo *UNUSED(gz),
+ wmGizmoProperty *gz_prop,
+ void *value_p)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
- PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_GET], NULL);
- if (ret == NULL) {
- goto fail;
- }
-
- if (gz_prop->type->data_type == PROP_FLOAT) {
- float *value = value_p;
- if (gz_prop->type->array_length == 1) {
- if ((*value = PyFloat_AsDouble(ret)) == -1.0f && PyErr_Occurred()) {
- goto fail;
- }
- }
- else {
- if (PyC_AsArray(value, ret, gz_prop->type->array_length, &PyFloat_Type, false,
- "Gizmo get callback: ") == -1)
- {
- goto fail;
- }
- }
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
- goto fail;
- }
-
- Py_DECREF(ret);
-
- PyGILState_Release(gilstate);
- return;
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
+ PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_GET], NULL);
+ if (ret == NULL) {
+ goto fail;
+ }
+
+ if (gz_prop->type->data_type == PROP_FLOAT) {
+ float *value = value_p;
+ if (gz_prop->type->array_length == 1) {
+ if ((*value = PyFloat_AsDouble(ret)) == -1.0f && PyErr_Occurred()) {
+ goto fail;
+ }
+ }
+ else {
+ if (PyC_AsArray(value,
+ ret,
+ gz_prop->type->array_length,
+ &PyFloat_Type,
+ false,
+ "Gizmo get callback: ") == -1) {
+ goto fail;
+ }
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
+ goto fail;
+ }
+
+ Py_DECREF(ret);
+
+ PyGILState_Release(gilstate);
+ return;
fail:
- PyErr_Print();
- PyErr_Clear();
+ PyErr_Print();
+ PyErr_Clear();
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
}
-static void py_rna_gizmo_handler_set_cb(
- const wmGizmo *UNUSED(gz), wmGizmoProperty *gz_prop,
- const void *value_p)
+static void py_rna_gizmo_handler_set_cb(const wmGizmo *UNUSED(gz),
+ wmGizmoProperty *gz_prop,
+ const void *value_p)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
-
- PyObject *args = PyTuple_New(1);
-
- if (gz_prop->type->data_type == PROP_FLOAT) {
- const float *value = value_p;
- PyObject *py_value;
- if (gz_prop->type->array_length == 1) {
- py_value = PyFloat_FromDouble(*value);
- }
- else {
- py_value = PyC_Tuple_PackArray_F32(value, gz_prop->type->array_length);
- }
- if (py_value == NULL) {
- goto fail;
- }
- PyTuple_SET_ITEM(args, 0, py_value);
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
- goto fail;
- }
-
- PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_SET], args);
- if (ret == NULL) {
- goto fail;
- }
- Py_DECREF(ret);
-
- PyGILState_Release(gilstate);
- return;
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
+
+ PyObject *args = PyTuple_New(1);
+
+ if (gz_prop->type->data_type == PROP_FLOAT) {
+ const float *value = value_p;
+ PyObject *py_value;
+ if (gz_prop->type->array_length == 1) {
+ py_value = PyFloat_FromDouble(*value);
+ }
+ else {
+ py_value = PyC_Tuple_PackArray_F32(value, gz_prop->type->array_length);
+ }
+ if (py_value == NULL) {
+ goto fail;
+ }
+ PyTuple_SET_ITEM(args, 0, py_value);
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
+ goto fail;
+ }
+
+ PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_SET], args);
+ if (ret == NULL) {
+ goto fail;
+ }
+ Py_DECREF(ret);
+
+ PyGILState_Release(gilstate);
+ return;
fail:
- PyErr_Print();
- PyErr_Clear();
+ PyErr_Print();
+ PyErr_Clear();
- Py_DECREF(args);
+ Py_DECREF(args);
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
}
-static void py_rna_gizmo_handler_range_get_cb(
- const wmGizmo *UNUSED(gz), wmGizmoProperty *gz_prop,
- void *value_p)
+static void py_rna_gizmo_handler_range_get_cb(const wmGizmo *UNUSED(gz),
+ wmGizmoProperty *gz_prop,
+ void *value_p)
{
- struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
-
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_RANGE_GET], NULL);
- if (ret == NULL) {
- goto fail;
- }
-
- if (!PyTuple_Check(ret)) {
- PyErr_Format(PyExc_TypeError,
- "Expected a tuple, not %.200s",
- Py_TYPE(ret)->tp_name);
- goto fail;
- }
-
- if (PyTuple_GET_SIZE(ret) != 2) {
- PyErr_Format(PyExc_TypeError,
- "Expected a tuple of size 2, not %d",
- PyTuple_GET_SIZE(ret));
- goto fail;
- }
-
- if (gz_prop->type->data_type == PROP_FLOAT) {
- float range[2];
- for (int i = 0; i < 2; i++) {
- if (((range[i] = PyFloat_AsDouble(PyTuple_GET_ITEM(ret, i))) == -1.0f && PyErr_Occurred()) == 0) {
- /* pass */
- }
- else {
- goto fail;
- }
- }
- memcpy(value_p, range, sizeof(range));
- }
- else {
- PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
- goto fail;
- }
-
- Py_DECREF(ret);
- PyGILState_Release(gilstate);
- return;
+ struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
+
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ PyObject *ret = PyObject_CallObject(data->fn_slots[BPY_GIZMO_FN_SLOT_RANGE_GET], NULL);
+ if (ret == NULL) {
+ goto fail;
+ }
+
+ if (!PyTuple_Check(ret)) {
+ PyErr_Format(PyExc_TypeError, "Expected a tuple, not %.200s", Py_TYPE(ret)->tp_name);
+ goto fail;
+ }
+
+ if (PyTuple_GET_SIZE(ret) != 2) {
+ PyErr_Format(PyExc_TypeError, "Expected a tuple of size 2, not %d", PyTuple_GET_SIZE(ret));
+ goto fail;
+ }
+
+ if (gz_prop->type->data_type == PROP_FLOAT) {
+ float range[2];
+ for (int i = 0; i < 2; i++) {
+ if (((range[i] = PyFloat_AsDouble(PyTuple_GET_ITEM(ret, i))) == -1.0f && PyErr_Occurred()) ==
+ 0) {
+ /* pass */
+ }
+ else {
+ goto fail;
+ }
+ }
+ memcpy(value_p, range, sizeof(range));
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError, "internal error, unsupported type");
+ goto fail;
+ }
+
+ Py_DECREF(ret);
+ PyGILState_Release(gilstate);
+ return;
fail:
- Py_XDECREF(ret);
+ Py_XDECREF(ret);
- PyErr_Print();
- PyErr_Clear();
+ PyErr_Print();
+ PyErr_Clear();
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
}
-static void py_rna_gizmo_handler_free_cb(
- const wmGizmo *UNUSED(gz), wmGizmoProperty *gz_prop)
+static void py_rna_gizmo_handler_free_cb(const wmGizmo *UNUSED(gz), wmGizmoProperty *gz_prop)
{
- struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
+ struct BPyGizmoHandlerUserData *data = gz_prop->custom_func.user_data;
- PyGILState_STATE gilstate = PyGILState_Ensure();
- for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
- Py_XDECREF(data->fn_slots[i]);
- }
- PyGILState_Release(gilstate);
-
- MEM_freeN(data);
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+ for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
+ Py_XDECREF(data->fn_slots[i]);
+ }
+ PyGILState_Release(gilstate);
+ MEM_freeN(data);
}
-PyDoc_STRVAR(bpy_gizmo_target_set_handler_doc,
-".. method:: target_set_handler(target, get, set, range=None):\n"
-"\n"
-" Assigns callbacks to a gizmos property.\n"
-"\n"
-" :arg get: Function that returns the value for this property (single value or sequence).\n"
-" :type get: callable\n"
-" :arg set: Function that takes a single value argument and applies it.\n"
-" :type set: callable\n"
-" :arg range: Function that returns a (min, max) tuple for gizmos that use a range.\n"
-" :type range: callable\n"
-);
+PyDoc_STRVAR(
+ bpy_gizmo_target_set_handler_doc,
+ ".. method:: target_set_handler(target, get, set, range=None):\n"
+ "\n"
+ " Assigns callbacks to a gizmos property.\n"
+ "\n"
+ " :arg get: Function that returns the value for this property (single value or sequence).\n"
+ " :type get: callable\n"
+ " :arg set: Function that takes a single value argument and applies it.\n"
+ " :type set: callable\n"
+ " :arg range: Function that returns a (min, max) tuple for gizmos that use a range.\n"
+ " :type range: callable\n");
static PyObject *bpy_gizmo_target_set_handler(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
-
- struct {
- PyObject *self;
- char *target;
- PyObject *py_fn_slots[BPY_GIZMO_FN_SLOT_LEN];
- } params = {
- .self = NULL,
- .target = NULL,
- .py_fn_slots = {NULL},
- };
-
- /* Note: this is a counter-part to functions:
- * 'Gizmo.target_set_prop & target_set_operator'
- * (see: rna_wm_gizmo_api.c). conventions should match. */
- static const char * const _keywords[] = {"self", "target", "get", "set", "range", NULL};
- static _PyArg_Parser _parser = {"Os|$OOO:target_set_handler", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &params.self,
- &params.target,
- &params.py_fn_slots[BPY_GIZMO_FN_SLOT_GET],
- &params.py_fn_slots[BPY_GIZMO_FN_SLOT_SET],
- &params.py_fn_slots[BPY_GIZMO_FN_SLOT_RANGE_GET]))
- {
- goto fail;
- }
-
- wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
-
- const wmGizmoPropertyType *gz_prop_type =
- WM_gizmotype_target_property_find(gz->type, params.target);
- if (gz_prop_type == NULL) {
- PyErr_Format(PyExc_ValueError,
- "Gizmo target property '%s.%s' not found",
- gz->type->idname, params.target);
- goto fail;
- }
-
- {
- const int slots_required = 2;
- const int slots_start = 2;
- for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
- if (params.py_fn_slots[i] == NULL) {
- if (i < slots_required) {
- PyErr_Format(PyExc_ValueError, "Argument '%s' not given", _keywords[slots_start + i]);
- goto fail;
- }
- }
- else if (!PyCallable_Check(params.py_fn_slots[i])) {
- PyErr_Format(PyExc_ValueError, "Argument '%s' not callable", _keywords[slots_start + i]);
- goto fail;
- }
- }
- }
-
- struct BPyGizmoHandlerUserData *data = MEM_callocN(sizeof(*data), __func__);
-
- for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
- data->fn_slots[i] = params.py_fn_slots[i];
- Py_XINCREF(params.py_fn_slots[i]);
- }
-
- WM_gizmo_target_property_def_func_ptr(
- gz, gz_prop_type,
- &(const struct wmGizmoPropertyFnParams) {
- .value_get_fn = py_rna_gizmo_handler_get_cb,
- .value_set_fn = py_rna_gizmo_handler_set_cb,
- .range_get_fn = py_rna_gizmo_handler_range_get_cb,
- .free_fn = py_rna_gizmo_handler_free_cb,
- .user_data = data,
- });
-
- PyGILState_Release(gilstate);
-
- Py_RETURN_NONE;
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ struct {
+ PyObject *self;
+ char *target;
+ PyObject *py_fn_slots[BPY_GIZMO_FN_SLOT_LEN];
+ } params = {
+ .self = NULL,
+ .target = NULL,
+ .py_fn_slots = {NULL},
+ };
+
+ /* Note: this is a counter-part to functions:
+ * 'Gizmo.target_set_prop & target_set_operator'
+ * (see: rna_wm_gizmo_api.c). conventions should match. */
+ static const char *const _keywords[] = {"self", "target", "get", "set", "range", NULL};
+ static _PyArg_Parser _parser = {"Os|$OOO:target_set_handler", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &params.self,
+ &params.target,
+ &params.py_fn_slots[BPY_GIZMO_FN_SLOT_GET],
+ &params.py_fn_slots[BPY_GIZMO_FN_SLOT_SET],
+ &params.py_fn_slots[BPY_GIZMO_FN_SLOT_RANGE_GET])) {
+ goto fail;
+ }
+
+ wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
+
+ const wmGizmoPropertyType *gz_prop_type = WM_gizmotype_target_property_find(gz->type,
+ params.target);
+ if (gz_prop_type == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "Gizmo target property '%s.%s' not found",
+ gz->type->idname,
+ params.target);
+ goto fail;
+ }
+
+ {
+ const int slots_required = 2;
+ const int slots_start = 2;
+ for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
+ if (params.py_fn_slots[i] == NULL) {
+ if (i < slots_required) {
+ PyErr_Format(PyExc_ValueError, "Argument '%s' not given", _keywords[slots_start + i]);
+ goto fail;
+ }
+ }
+ else if (!PyCallable_Check(params.py_fn_slots[i])) {
+ PyErr_Format(PyExc_ValueError, "Argument '%s' not callable", _keywords[slots_start + i]);
+ goto fail;
+ }
+ }
+ }
+
+ struct BPyGizmoHandlerUserData *data = MEM_callocN(sizeof(*data), __func__);
+
+ for (int i = 0; i < BPY_GIZMO_FN_SLOT_LEN; i++) {
+ data->fn_slots[i] = params.py_fn_slots[i];
+ Py_XINCREF(params.py_fn_slots[i]);
+ }
+
+ WM_gizmo_target_property_def_func_ptr(gz,
+ gz_prop_type,
+ &(const struct wmGizmoPropertyFnParams){
+ .value_get_fn = py_rna_gizmo_handler_get_cb,
+ .value_set_fn = py_rna_gizmo_handler_set_cb,
+ .range_get_fn = py_rna_gizmo_handler_range_get_cb,
+ .free_fn = py_rna_gizmo_handler_free_cb,
+ .user_data = data,
+ });
+
+ PyGILState_Release(gilstate);
+
+ Py_RETURN_NONE;
fail:
- PyGILState_Release(gilstate);
- return NULL;
+ PyGILState_Release(gilstate);
+ return NULL;
}
/** \} */
@@ -327,233 +324,222 @@ fail:
* \{ */
PyDoc_STRVAR(bpy_gizmo_target_get_value_doc,
-".. method:: target_get_value(target):\n"
-"\n"
-" Get the value of this target property.\n"
-"\n"
-" :arg target: Target property name.\n"
-" :type target: string\n"
-" :return: The value of the target property.\n"
-" :rtype: Single value or array based on the target type\n"
-);
+ ".. method:: target_get_value(target):\n"
+ "\n"
+ " Get the value of this target property.\n"
+ "\n"
+ " :arg target: Target property name.\n"
+ " :type target: string\n"
+ " :return: The value of the target property.\n"
+ " :rtype: Single value or array based on the target type\n");
static PyObject *bpy_gizmo_target_get_value(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- struct {
- PyObject *self;
- char *target;
- } params = {
- .self = NULL,
- .target = NULL,
- };
-
- static const char * const _keywords[] = {"self", "target", NULL};
- static _PyArg_Parser _parser = {"Os:target_get_value", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &params.self,
- &params.target))
- {
- goto fail;
- }
-
- wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
-
- wmGizmoProperty *gz_prop =
- WM_gizmo_target_property_find(gz, params.target);
- if (gz_prop == NULL) {
- PyErr_Format(PyExc_ValueError,
- "Gizmo target property '%s.%s' not found",
- gz->type->idname, params.target);
- goto fail;
- }
-
- const int array_len = WM_gizmo_target_property_array_length(gz, gz_prop);
- switch (gz_prop->type->data_type) {
- case PROP_FLOAT:
- {
- if (array_len != 0) {
- float *value = BLI_array_alloca(value, array_len);
- WM_gizmo_target_property_float_get_array(gz, gz_prop, value);
- return PyC_Tuple_PackArray_F32(value, array_len);
- }
- else {
- float value = WM_gizmo_target_property_float_get(gz, gz_prop);
- return PyFloat_FromDouble(value);
- }
- break;
- }
- default:
- {
- PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
- goto fail;
- }
- }
+ struct {
+ PyObject *self;
+ char *target;
+ } params = {
+ .self = NULL,
+ .target = NULL,
+ };
+
+ static const char *const _keywords[] = {"self", "target", NULL};
+ static _PyArg_Parser _parser = {"Os:target_get_value", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &params.self, &params.target)) {
+ goto fail;
+ }
+
+ wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
+
+ wmGizmoProperty *gz_prop = WM_gizmo_target_property_find(gz, params.target);
+ if (gz_prop == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "Gizmo target property '%s.%s' not found",
+ gz->type->idname,
+ params.target);
+ goto fail;
+ }
+
+ const int array_len = WM_gizmo_target_property_array_length(gz, gz_prop);
+ switch (gz_prop->type->data_type) {
+ case PROP_FLOAT: {
+ if (array_len != 0) {
+ float *value = BLI_array_alloca(value, array_len);
+ WM_gizmo_target_property_float_get_array(gz, gz_prop, value);
+ return PyC_Tuple_PackArray_F32(value, array_len);
+ }
+ else {
+ float value = WM_gizmo_target_property_float_get(gz, gz_prop);
+ return PyFloat_FromDouble(value);
+ }
+ break;
+ }
+ default: {
+ PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
+ goto fail;
+ }
+ }
fail:
- return NULL;
+ return NULL;
}
PyDoc_STRVAR(bpy_gizmo_target_set_value_doc,
-".. method:: target_set_value(target):\n"
-"\n"
-" Set the value of this target property.\n"
-"\n"
-" :arg target: Target property name.\n"
-" :type target: string\n"
-);
+ ".. method:: target_set_value(target):\n"
+ "\n"
+ " Set the value of this target property.\n"
+ "\n"
+ " :arg target: Target property name.\n"
+ " :type target: string\n");
static PyObject *bpy_gizmo_target_set_value(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- struct {
- PyObject *self;
- char *target;
- PyObject *value;
- } params = {
- .self = NULL,
- .target = NULL,
- .value = NULL,
- };
-
- static const char * const _keywords[] = {"self", "target", "value", NULL};
- static _PyArg_Parser _parser = {"OsO:target_set_value", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &params.self,
- &params.target,
- &params.value))
- {
- goto fail;
- }
-
- wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
-
- wmGizmoProperty *gz_prop =
- WM_gizmo_target_property_find(gz, params.target);
- if (gz_prop == NULL) {
- PyErr_Format(PyExc_ValueError,
- "Gizmo target property '%s.%s' not found",
- gz->type->idname, params.target);
- goto fail;
- }
-
- const int array_len = WM_gizmo_target_property_array_length(gz, gz_prop);
- switch (gz_prop->type->data_type) {
- case PROP_FLOAT:
- {
- if (array_len != 0) {
- float *value = BLI_array_alloca(value, array_len);
- if (PyC_AsArray(value, params.value, gz_prop->type->array_length, &PyFloat_Type, false,
- "Gizmo target property array") == -1)
- {
- goto fail;
- }
- WM_gizmo_target_property_float_set_array(BPy_GetContext(), gz, gz_prop, value);
- }
- else {
- float value;
- if ((value = PyFloat_AsDouble(params.value)) == -1.0f && PyErr_Occurred()) {
- goto fail;
- }
- WM_gizmo_target_property_float_set(BPy_GetContext(), gz, gz_prop, value);
- }
- Py_RETURN_NONE;
- }
- default:
- {
- PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
- goto fail;
- }
- }
+ struct {
+ PyObject *self;
+ char *target;
+ PyObject *value;
+ } params = {
+ .self = NULL,
+ .target = NULL,
+ .value = NULL,
+ };
+
+ static const char *const _keywords[] = {"self", "target", "value", NULL};
+ static _PyArg_Parser _parser = {"OsO:target_set_value", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &params.self, &params.target, &params.value)) {
+ goto fail;
+ }
+
+ wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
+
+ wmGizmoProperty *gz_prop = WM_gizmo_target_property_find(gz, params.target);
+ if (gz_prop == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "Gizmo target property '%s.%s' not found",
+ gz->type->idname,
+ params.target);
+ goto fail;
+ }
+
+ const int array_len = WM_gizmo_target_property_array_length(gz, gz_prop);
+ switch (gz_prop->type->data_type) {
+ case PROP_FLOAT: {
+ if (array_len != 0) {
+ float *value = BLI_array_alloca(value, array_len);
+ if (PyC_AsArray(value,
+ params.value,
+ gz_prop->type->array_length,
+ &PyFloat_Type,
+ false,
+ "Gizmo target property array") == -1) {
+ goto fail;
+ }
+ WM_gizmo_target_property_float_set_array(BPy_GetContext(), gz, gz_prop, value);
+ }
+ else {
+ float value;
+ if ((value = PyFloat_AsDouble(params.value)) == -1.0f && PyErr_Occurred()) {
+ goto fail;
+ }
+ WM_gizmo_target_property_float_set(BPy_GetContext(), gz, gz_prop, value);
+ }
+ Py_RETURN_NONE;
+ }
+ default: {
+ PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
+ goto fail;
+ }
+ }
fail:
- return NULL;
+ return NULL;
}
-
PyDoc_STRVAR(bpy_gizmo_target_get_range_doc,
-".. method:: target_get_range(target):\n"
-"\n"
-" Get the range for this target property.\n"
-"\n"
-" :arg target: Target property name.\n"
-" :return: The range of this property (min, max).\n"
-" :rtype: tuple pair.\n"
-);
+ ".. method:: target_get_range(target):\n"
+ "\n"
+ " Get the range for this target property.\n"
+ "\n"
+ " :arg target: Target property name.\n"
+ " :return: The range of this property (min, max).\n"
+ " :rtype: tuple pair.\n");
static PyObject *bpy_gizmo_target_get_range(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- struct {
- PyObject *self;
- char *target;
- } params = {
- .self = NULL,
- .target = NULL,
- };
-
- static const char * const _keywords[] = {"self", "target", NULL};
- static _PyArg_Parser _parser = {"Os:target_get_range", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &params.self,
- &params.target))
- {
- goto fail;
- }
-
- wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
-
- wmGizmoProperty *gz_prop =
- WM_gizmo_target_property_find(gz, params.target);
- if (gz_prop == NULL) {
- PyErr_Format(PyExc_ValueError,
- "Gizmo target property '%s.%s' not found",
- gz->type->idname, params.target);
- goto fail;
- }
-
- switch (gz_prop->type->data_type) {
- case PROP_FLOAT:
- {
- float range[2];
- WM_gizmo_target_property_float_range_get(gz, gz_prop, range);
- return PyC_Tuple_PackArray_F32(range, 2);
- }
- default:
- {
- PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
- goto fail;
- }
- }
+ struct {
+ PyObject *self;
+ char *target;
+ } params = {
+ .self = NULL,
+ .target = NULL,
+ };
+
+ static const char *const _keywords[] = {"self", "target", NULL};
+ static _PyArg_Parser _parser = {"Os:target_get_range", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &params.self, &params.target)) {
+ goto fail;
+ }
+
+ wmGizmo *gz = ((BPy_StructRNA *)params.self)->ptr.data;
+
+ wmGizmoProperty *gz_prop = WM_gizmo_target_property_find(gz, params.target);
+ if (gz_prop == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "Gizmo target property '%s.%s' not found",
+ gz->type->idname,
+ params.target);
+ goto fail;
+ }
+
+ switch (gz_prop->type->data_type) {
+ case PROP_FLOAT: {
+ float range[2];
+ WM_gizmo_target_property_float_range_get(gz, gz_prop, range);
+ return PyC_Tuple_PackArray_F32(range, 2);
+ }
+ default: {
+ PyErr_SetString(PyExc_RuntimeError, "Not yet supported type");
+ goto fail;
+ }
+ }
fail:
- return NULL;
+ return NULL;
}
/** \} */
int BPY_rna_gizmo_module(PyObject *mod_par)
{
- static PyMethodDef method_def_array[] = {
- /* Gizmo Target Property Define API */
- {"target_set_handler", (PyCFunction)bpy_gizmo_target_set_handler,
- METH_VARARGS | METH_KEYWORDS, bpy_gizmo_target_set_handler_doc},
- /* Gizmo Target Property Access API */
- {"target_get_value", (PyCFunction)bpy_gizmo_target_get_value,
- METH_VARARGS | METH_KEYWORDS, bpy_gizmo_target_get_value_doc},
- {"target_set_value", (PyCFunction)bpy_gizmo_target_set_value,
- METH_VARARGS | METH_KEYWORDS, bpy_gizmo_target_set_value_doc},
- {"target_get_range", (PyCFunction)bpy_gizmo_target_get_range,
- METH_VARARGS | METH_KEYWORDS, bpy_gizmo_target_get_range_doc},
- /* no sentinel needed. */
- };
-
- for (int i = 0; i < ARRAY_SIZE(method_def_array); i++) {
- PyMethodDef *m = &method_def_array[i];
- PyObject *func = PyCFunction_New(m, NULL);
- PyObject *func_inst = PyInstanceMethod_New(func);
- char name_prefix[128];
- PyOS_snprintf(name_prefix, sizeof(name_prefix), "_rna_gizmo_%s", m->ml_name);
- /* TODO, return a type that binds nearly to a method. */
- PyModule_AddObject(mod_par, name_prefix, func_inst);
- }
-
- return 0;
+ static PyMethodDef method_def_array[] = {
+ /* Gizmo Target Property Define API */
+ {"target_set_handler",
+ (PyCFunction)bpy_gizmo_target_set_handler,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_gizmo_target_set_handler_doc},
+ /* Gizmo Target Property Access API */
+ {"target_get_value",
+ (PyCFunction)bpy_gizmo_target_get_value,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_gizmo_target_get_value_doc},
+ {"target_set_value",
+ (PyCFunction)bpy_gizmo_target_set_value,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_gizmo_target_set_value_doc},
+ {"target_get_range",
+ (PyCFunction)bpy_gizmo_target_get_range,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_gizmo_target_get_range_doc},
+ /* no sentinel needed. */
+ };
+
+ for (int i = 0; i < ARRAY_SIZE(method_def_array); i++) {
+ PyMethodDef *m = &method_def_array[i];
+ PyObject *func = PyCFunction_New(m, NULL);
+ PyObject *func_inst = PyInstanceMethod_New(func);
+ char name_prefix[128];
+ PyOS_snprintf(name_prefix, sizeof(name_prefix), "_rna_gizmo_%s", m->ml_name);
+ /* TODO, return a type that binds nearly to a method. */
+ PyModule_AddObject(mod_par, name_prefix, func_inst);
+ }
+
+ return 0;
}
diff --git a/source/blender/python/intern/bpy_rna_gizmo.h b/source/blender/python/intern/bpy_rna_gizmo.h
index 2eb02008eb1..293ab38a6ab 100644
--- a/source/blender/python/intern/bpy_rna_gizmo.h
+++ b/source/blender/python/intern/bpy_rna_gizmo.h
@@ -23,4 +23,4 @@
int BPY_rna_gizmo_module(PyObject *);
-#endif /* __BPY_RNA_GIZMO_H__ */
+#endif /* __BPY_RNA_GIZMO_H__ */
diff --git a/source/blender/python/intern/bpy_rna_id_collection.c b/source/blender/python/intern/bpy_rna_id_collection.c
index 7a5849f818d..bb7604aea97 100644
--- a/source/blender/python/intern/bpy_rna_id_collection.c
+++ b/source/blender/python/intern/bpy_rna_id_collection.c
@@ -54,336 +54,337 @@
#include "bpy_rna.h"
typedef struct IDUserMapData {
- /* place-holder key only used for lookups to avoid creating new data only for lookups
- * (never return its contents) */
- PyObject *py_id_key_lookup_only;
+ /* place-holder key only used for lookups to avoid creating new data only for lookups
+ * (never return its contents) */
+ PyObject *py_id_key_lookup_only;
- /* we loop over data-blocks that this ID points to (do build a reverse lookup table) */
- PyObject *py_id_curr;
- ID *id_curr;
+ /* we loop over data-blocks that this ID points to (do build a reverse lookup table) */
+ PyObject *py_id_curr;
+ ID *id_curr;
- /* filter the values we add into the set */
- BLI_bitmap *types_bitmap;
+ /* filter the values we add into the set */
+ BLI_bitmap *types_bitmap;
- PyObject *user_map; /* set to fill in as we iterate */
- bool is_subset; /* true when we're only mapping a subset of all the ID's (subset arg is passed) */
+ PyObject *user_map; /* set to fill in as we iterate */
+ bool
+ is_subset; /* true when we're only mapping a subset of all the ID's (subset arg is passed) */
} IDUserMapData;
-
static int id_code_as_index(const short idcode)
{
- return (int)*((unsigned short *)&idcode);
+ return (int)*((unsigned short *)&idcode);
}
static bool id_check_type(const ID *id, const BLI_bitmap *types_bitmap)
{
- return BLI_BITMAP_TEST_BOOL(types_bitmap, id_code_as_index(GS(id->name)));
+ return BLI_BITMAP_TEST_BOOL(types_bitmap, id_code_as_index(GS(id->name)));
}
-static int foreach_libblock_id_user_map_callback(
- void *user_data, ID *self_id, ID **id_p, int UNUSED(cb_flag))
+static int foreach_libblock_id_user_map_callback(void *user_data,
+ ID *self_id,
+ ID **id_p,
+ int UNUSED(cb_flag))
{
- IDUserMapData *data = user_data;
-
- if (*id_p) {
-
- if (data->types_bitmap) {
- if (!id_check_type(*id_p, data->types_bitmap)) {
- return IDWALK_RET_NOP;
- }
- }
-
- if ((GS(self_id->name) == ID_OB) && (id_p == (ID **)&((Object *)self_id)->proxy_from)) {
- /* We skip proxy_from here, since it's some internal pointer which is not relevant info for py/API level. */
- return IDWALK_RET_NOP;
- }
- else if ((GS(self_id->name) == ID_KE) && (id_p == (ID **)&((Key *)self_id)->from)) {
- /* We skip from here, since it's some internal pointer which is not relevant info for py/API level. */
- return IDWALK_RET_NOP;
- }
-
- /* pyrna_struct_hash() uses ptr.data only,
- * but pyrna_struct_richcmp() uses also ptr.type,
- * so we need to create a valid PointerRNA here...
- */
- PyObject *key = data->py_id_key_lookup_only;
- RNA_id_pointer_create(*id_p, &((BPy_StructRNA *)key)->ptr);
-
- PyObject *set;
- if ((set = PyDict_GetItem(data->user_map, key)) == NULL) {
-
- /* limit to key's added already */
- if (data->is_subset) {
- return IDWALK_RET_NOP;
- }
-
- /* Cannot use our placeholder key here! */
- key = pyrna_id_CreatePyObject(*id_p);
- set = PySet_New(NULL);
- PyDict_SetItem(data->user_map, key, set);
- Py_DECREF(set);
- Py_DECREF(key);
- }
-
- if (data->py_id_curr == NULL) {
- data->py_id_curr = pyrna_id_CreatePyObject(data->id_curr);
- }
-
- PySet_Add(set, data->py_id_curr);
- }
-
- return IDWALK_RET_NOP;
+ IDUserMapData *data = user_data;
+
+ if (*id_p) {
+
+ if (data->types_bitmap) {
+ if (!id_check_type(*id_p, data->types_bitmap)) {
+ return IDWALK_RET_NOP;
+ }
+ }
+
+ if ((GS(self_id->name) == ID_OB) && (id_p == (ID **)&((Object *)self_id)->proxy_from)) {
+ /* We skip proxy_from here, since it's some internal pointer which is not relevant info for py/API level. */
+ return IDWALK_RET_NOP;
+ }
+ else if ((GS(self_id->name) == ID_KE) && (id_p == (ID **)&((Key *)self_id)->from)) {
+ /* We skip from here, since it's some internal pointer which is not relevant info for py/API level. */
+ return IDWALK_RET_NOP;
+ }
+
+ /* pyrna_struct_hash() uses ptr.data only,
+ * but pyrna_struct_richcmp() uses also ptr.type,
+ * so we need to create a valid PointerRNA here...
+ */
+ PyObject *key = data->py_id_key_lookup_only;
+ RNA_id_pointer_create(*id_p, &((BPy_StructRNA *)key)->ptr);
+
+ PyObject *set;
+ if ((set = PyDict_GetItem(data->user_map, key)) == NULL) {
+
+ /* limit to key's added already */
+ if (data->is_subset) {
+ return IDWALK_RET_NOP;
+ }
+
+ /* Cannot use our placeholder key here! */
+ key = pyrna_id_CreatePyObject(*id_p);
+ set = PySet_New(NULL);
+ PyDict_SetItem(data->user_map, key, set);
+ Py_DECREF(set);
+ Py_DECREF(key);
+ }
+
+ if (data->py_id_curr == NULL) {
+ data->py_id_curr = pyrna_id_CreatePyObject(data->id_curr);
+ }
+
+ PySet_Add(set, data->py_id_curr);
+ }
+
+ return IDWALK_RET_NOP;
}
PyDoc_STRVAR(bpy_user_map_doc,
-".. method:: user_map([subset=(id1, id2, ...)], key_types={..}, value_types={..})\n"
-"\n"
-" Returns a mapping of all ID datablocks in current ``bpy.data`` to a set of all datablocks using them.\n"
-"\n"
-" For list of valid set members for key_types & value_types, see: :class:`bpy.types.KeyingSetPath.id_type`.\n"
-"\n"
-" :arg subset: When passed, only these data-blocks and their users will be included as keys/values in the map.\n"
-" :type subset: sequence\n"
-" :arg key_types: Filter the keys mapped by ID types.\n"
-" :type key_types: set of strings\n"
-" :arg value_types: Filter the values in the set by ID types.\n"
-" :type value_types: set of strings\n"
-" :return: dictionary of :class:`bpy.types.ID` instances, with sets of ID's as their values.\n"
-" :rtype: dict\n"
-);
+ ".. method:: user_map([subset=(id1, id2, ...)], key_types={..}, value_types={..})\n"
+ "\n"
+ " Returns a mapping of all ID datablocks in current ``bpy.data`` to a set of all "
+ "datablocks using them.\n"
+ "\n"
+ " For list of valid set members for key_types & value_types, see: "
+ ":class:`bpy.types.KeyingSetPath.id_type`.\n"
+ "\n"
+ " :arg subset: When passed, only these data-blocks and their users will be "
+ "included as keys/values in the map.\n"
+ " :type subset: sequence\n"
+ " :arg key_types: Filter the keys mapped by ID types.\n"
+ " :type key_types: set of strings\n"
+ " :arg value_types: Filter the values in the set by ID types.\n"
+ " :type value_types: set of strings\n"
+ " :return: dictionary of :class:`bpy.types.ID` instances, with sets of ID's as "
+ "their values.\n"
+ " :rtype: dict\n");
static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
{
-#if 0 /* If someone knows how to get a proper 'self' in that case... */
- BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
- Main *bmain = pyrna->ptr.data;
+#if 0 /* If someone knows how to get a proper 'self' in that case... */
+ BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
+ Main *bmain = pyrna->ptr.data;
#else
- Main *bmain = G_MAIN; /* XXX Ugly, but should work! */
+ Main *bmain = G_MAIN; /* XXX Ugly, but should work! */
#endif
- ListBase *lb;
- ID *id;
-
- PyObject *subset = NULL;
-
- PyObject *key_types = NULL;
- PyObject *val_types = NULL;
- BLI_bitmap *key_types_bitmap = NULL;
- BLI_bitmap *val_types_bitmap = NULL;
-
- PyObject *ret = NULL;
-
- IDUserMapData data_cb = {NULL};
-
- static const char *_keywords[] = {"subset", "key_types", "value_types", NULL};
- static _PyArg_Parser _parser = {"|O$O!O!:user_map", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &subset,
- &PySet_Type, &key_types,
- &PySet_Type, &val_types))
- {
- return NULL;
- }
-
- if (key_types) {
- key_types_bitmap = pyrna_set_to_enum_bitmap(
- rna_enum_id_type_items, key_types, sizeof(short), true, USHRT_MAX, "key types");
- if (key_types_bitmap == NULL) {
- goto error;
- }
- }
-
- if (val_types) {
- val_types_bitmap = pyrna_set_to_enum_bitmap(
- rna_enum_id_type_items, val_types, sizeof(short), true, USHRT_MAX, "value types");
- if (val_types_bitmap == NULL) {
- goto error;
- }
- }
-
- if (subset) {
- PyObject *subset_fast = PySequence_Fast(subset, "user_map");
- if (subset_fast == NULL) {
- goto error;
- }
-
- PyObject **subset_array = PySequence_Fast_ITEMS(subset_fast);
- Py_ssize_t subset_len = PySequence_Fast_GET_SIZE(subset_fast);
-
- data_cb.user_map = _PyDict_NewPresized(subset_len);
- data_cb.is_subset = true;
- for (; subset_len; subset_array++, subset_len--) {
- PyObject *set = PySet_New(NULL);
- PyDict_SetItem(data_cb.user_map, *subset_array, set);
- Py_DECREF(set);
- }
- Py_DECREF(subset_fast);
- }
- else {
- data_cb.user_map = PyDict_New();
- }
-
- data_cb.types_bitmap = key_types_bitmap;
-
- FOREACH_MAIN_LISTBASE_BEGIN(bmain, lb)
- {
- FOREACH_MAIN_LISTBASE_ID_BEGIN(lb, id)
- {
- /* We cannot skip here in case we have some filter on key types... */
- if (key_types_bitmap == NULL && val_types_bitmap != NULL) {
- if (!id_check_type(id, val_types_bitmap)) {
- break;
- }
- }
-
- /* One-time init, ID is just used as placeholder here, we abuse this in iterator callback
- * to avoid having to rebuild a complete bpyrna object each time for the key searching
- * (where only ID pointer value is used). */
- if (data_cb.py_id_key_lookup_only == NULL) {
- data_cb.py_id_key_lookup_only = pyrna_id_CreatePyObject(id);
- }
-
- if (!data_cb.is_subset &&
- /* We do not want to pre-add keys of flitered out types. */
- (key_types_bitmap == NULL || id_check_type(id, key_types_bitmap)) &&
- /* We do not want to pre-add keys when we have filter on value types, but not on key types. */
- (val_types_bitmap == NULL || key_types_bitmap != NULL))
- {
- PyObject *key = data_cb.py_id_key_lookup_only;
- PyObject *set;
-
- RNA_id_pointer_create(id, &((BPy_StructRNA *)key)->ptr);
-
- /* We have to insert the key now, otherwise ID unused would be missing from final dict... */
- if ((set = PyDict_GetItem(data_cb.user_map, key)) == NULL) {
- /* Cannot use our placeholder key here! */
- key = pyrna_id_CreatePyObject(id);
- set = PySet_New(NULL);
- PyDict_SetItem(data_cb.user_map, key, set);
- Py_DECREF(set);
- Py_DECREF(key);
- }
- }
-
- if (val_types_bitmap != NULL && !id_check_type(id, val_types_bitmap)) {
- continue;
- }
-
- data_cb.id_curr = id;
- BKE_library_foreach_ID_link(NULL, id, foreach_libblock_id_user_map_callback, &data_cb, IDWALK_CB_NOP);
-
- if (data_cb.py_id_curr) {
- Py_DECREF(data_cb.py_id_curr);
- data_cb.py_id_curr = NULL;
- }
- }
- FOREACH_MAIN_LISTBASE_ID_END;
- }
- FOREACH_MAIN_LISTBASE_ID_END;
-
- ret = data_cb.user_map;
+ ListBase *lb;
+ ID *id;
+
+ PyObject *subset = NULL;
+
+ PyObject *key_types = NULL;
+ PyObject *val_types = NULL;
+ BLI_bitmap *key_types_bitmap = NULL;
+ BLI_bitmap *val_types_bitmap = NULL;
+
+ PyObject *ret = NULL;
+
+ IDUserMapData data_cb = {NULL};
+
+ static const char *_keywords[] = {"subset", "key_types", "value_types", NULL};
+ static _PyArg_Parser _parser = {"|O$O!O!:user_map", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kwds, &_parser, &subset, &PySet_Type, &key_types, &PySet_Type, &val_types)) {
+ return NULL;
+ }
+
+ if (key_types) {
+ key_types_bitmap = pyrna_set_to_enum_bitmap(
+ rna_enum_id_type_items, key_types, sizeof(short), true, USHRT_MAX, "key types");
+ if (key_types_bitmap == NULL) {
+ goto error;
+ }
+ }
+
+ if (val_types) {
+ val_types_bitmap = pyrna_set_to_enum_bitmap(
+ rna_enum_id_type_items, val_types, sizeof(short), true, USHRT_MAX, "value types");
+ if (val_types_bitmap == NULL) {
+ goto error;
+ }
+ }
+
+ if (subset) {
+ PyObject *subset_fast = PySequence_Fast(subset, "user_map");
+ if (subset_fast == NULL) {
+ goto error;
+ }
+
+ PyObject **subset_array = PySequence_Fast_ITEMS(subset_fast);
+ Py_ssize_t subset_len = PySequence_Fast_GET_SIZE(subset_fast);
+
+ data_cb.user_map = _PyDict_NewPresized(subset_len);
+ data_cb.is_subset = true;
+ for (; subset_len; subset_array++, subset_len--) {
+ PyObject *set = PySet_New(NULL);
+ PyDict_SetItem(data_cb.user_map, *subset_array, set);
+ Py_DECREF(set);
+ }
+ Py_DECREF(subset_fast);
+ }
+ else {
+ data_cb.user_map = PyDict_New();
+ }
+
+ data_cb.types_bitmap = key_types_bitmap;
+
+ FOREACH_MAIN_LISTBASE_BEGIN(bmain, lb)
+ {
+ FOREACH_MAIN_LISTBASE_ID_BEGIN(lb, id)
+ {
+ /* We cannot skip here in case we have some filter on key types... */
+ if (key_types_bitmap == NULL && val_types_bitmap != NULL) {
+ if (!id_check_type(id, val_types_bitmap)) {
+ break;
+ }
+ }
+
+ /* One-time init, ID is just used as placeholder here, we abuse this in iterator callback
+ * to avoid having to rebuild a complete bpyrna object each time for the key searching
+ * (where only ID pointer value is used). */
+ if (data_cb.py_id_key_lookup_only == NULL) {
+ data_cb.py_id_key_lookup_only = pyrna_id_CreatePyObject(id);
+ }
+
+ if (!data_cb.is_subset &&
+ /* We do not want to pre-add keys of flitered out types. */
+ (key_types_bitmap == NULL || id_check_type(id, key_types_bitmap)) &&
+ /* We do not want to pre-add keys when we have filter on value types, but not on key types. */
+ (val_types_bitmap == NULL || key_types_bitmap != NULL)) {
+ PyObject *key = data_cb.py_id_key_lookup_only;
+ PyObject *set;
+
+ RNA_id_pointer_create(id, &((BPy_StructRNA *)key)->ptr);
+
+ /* We have to insert the key now, otherwise ID unused would be missing from final dict... */
+ if ((set = PyDict_GetItem(data_cb.user_map, key)) == NULL) {
+ /* Cannot use our placeholder key here! */
+ key = pyrna_id_CreatePyObject(id);
+ set = PySet_New(NULL);
+ PyDict_SetItem(data_cb.user_map, key, set);
+ Py_DECREF(set);
+ Py_DECREF(key);
+ }
+ }
+
+ if (val_types_bitmap != NULL && !id_check_type(id, val_types_bitmap)) {
+ continue;
+ }
+
+ data_cb.id_curr = id;
+ BKE_library_foreach_ID_link(
+ NULL, id, foreach_libblock_id_user_map_callback, &data_cb, IDWALK_CB_NOP);
+
+ if (data_cb.py_id_curr) {
+ Py_DECREF(data_cb.py_id_curr);
+ data_cb.py_id_curr = NULL;
+ }
+ }
+ FOREACH_MAIN_LISTBASE_ID_END;
+ }
+ FOREACH_MAIN_LISTBASE_ID_END;
+
+ ret = data_cb.user_map;
error:
- if (data_cb.py_id_key_lookup_only != NULL) {
- Py_XDECREF(data_cb.py_id_key_lookup_only);
- }
+ if (data_cb.py_id_key_lookup_only != NULL) {
+ Py_XDECREF(data_cb.py_id_key_lookup_only);
+ }
- if (key_types_bitmap != NULL) {
- MEM_freeN(key_types_bitmap);
- }
+ if (key_types_bitmap != NULL) {
+ MEM_freeN(key_types_bitmap);
+ }
- if (val_types_bitmap != NULL) {
- MEM_freeN(val_types_bitmap);
- }
+ if (val_types_bitmap != NULL) {
+ MEM_freeN(val_types_bitmap);
+ }
- return ret;
+ return ret;
}
PyDoc_STRVAR(bpy_batch_remove_doc,
-".. method:: batch_remove(ids=(id1, id2, ...))\n"
-"\n"
-" Remove (delete) several IDs at once.\n"
-"\n"
-" WARNING: Considered experimental feature currently.\n"
-"\n"
-" Note that this function is quicker than individual calls to :func:`remove()` (from :class:`bpy.types.BlendData`\n"
-" ID collections), but less safe/versatile (it can break Blender, e.g. by removing all scenes...).\n"
-"\n"
-" :arg ids: Iterables of IDs (types can be mixed).\n"
-" :type subset: sequence\n"
-);
+ ".. method:: batch_remove(ids=(id1, id2, ...))\n"
+ "\n"
+ " Remove (delete) several IDs at once.\n"
+ "\n"
+ " WARNING: Considered experimental feature currently.\n"
+ "\n"
+ " Note that this function is quicker than individual calls to :func:`remove()` "
+ "(from :class:`bpy.types.BlendData`\n"
+ " ID collections), but less safe/versatile (it can break Blender, e.g. by removing "
+ "all scenes...).\n"
+ "\n"
+ " :arg ids: Iterables of IDs (types can be mixed).\n"
+ " :type subset: sequence\n");
static PyObject *bpy_batch_remove(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
{
-#if 0 /* If someone knows how to get a proper 'self' in that case... */
- BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
- Main *bmain = pyrna->ptr.data;
+#if 0 /* If someone knows how to get a proper 'self' in that case... */
+ BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
+ Main *bmain = pyrna->ptr.data;
#else
- Main *bmain = G_MAIN; /* XXX Ugly, but should work! */
+ Main *bmain = G_MAIN; /* XXX Ugly, but should work! */
#endif
- PyObject *ids = NULL;
-
- PyObject *ret = NULL;
-
- static const char *_keywords[] = {"ids", NULL};
- static _PyArg_Parser _parser = {"O:user_map", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kwds, &_parser,
- &ids))
- {
- return ret;
- }
-
- if (ids) {
- BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
-
- PyObject *ids_fast = PySequence_Fast(ids, "batch_remove");
- if (ids_fast == NULL) {
- goto error;
- }
-
- PyObject **ids_array = PySequence_Fast_ITEMS(ids_fast);
- Py_ssize_t ids_len = PySequence_Fast_GET_SIZE(ids_fast);
-
- for (; ids_len; ids_array++, ids_len--) {
- ID *id;
- if (!pyrna_id_FromPyObject(*ids_array, &id)) {
- PyErr_Format(PyExc_TypeError,
- "Expected an ID type, not %.200s",
- Py_TYPE(*ids_array)->tp_name);
- Py_DECREF(ids_fast);
- goto error;
- }
-
- id->tag |= LIB_TAG_DOIT;
- }
- Py_DECREF(ids_fast);
-
- BKE_id_multi_tagged_delete(bmain);
- /* Force full redraw, mandatory to avoid crashes when running this from UI... */
- WM_main_add_notifier(NC_WINDOW, NULL);
- }
- else {
- goto error;
- }
-
- Py_INCREF(Py_None);
- ret = Py_None;
+ PyObject *ids = NULL;
+
+ PyObject *ret = NULL;
+
+ static const char *_keywords[] = {"ids", NULL};
+ static _PyArg_Parser _parser = {"O:user_map", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args, kwds, &_parser, &ids)) {
+ return ret;
+ }
+
+ if (ids) {
+ BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
+
+ PyObject *ids_fast = PySequence_Fast(ids, "batch_remove");
+ if (ids_fast == NULL) {
+ goto error;
+ }
+
+ PyObject **ids_array = PySequence_Fast_ITEMS(ids_fast);
+ Py_ssize_t ids_len = PySequence_Fast_GET_SIZE(ids_fast);
+
+ for (; ids_len; ids_array++, ids_len--) {
+ ID *id;
+ if (!pyrna_id_FromPyObject(*ids_array, &id)) {
+ PyErr_Format(
+ PyExc_TypeError, "Expected an ID type, not %.200s", Py_TYPE(*ids_array)->tp_name);
+ Py_DECREF(ids_fast);
+ goto error;
+ }
+
+ id->tag |= LIB_TAG_DOIT;
+ }
+ Py_DECREF(ids_fast);
+
+ BKE_id_multi_tagged_delete(bmain);
+ /* Force full redraw, mandatory to avoid crashes when running this from UI... */
+ WM_main_add_notifier(NC_WINDOW, NULL);
+ }
+ else {
+ goto error;
+ }
+
+ Py_INCREF(Py_None);
+ ret = Py_None;
error:
- return ret;
+ return ret;
}
int BPY_rna_id_collection_module(PyObject *mod_par)
{
- static PyMethodDef user_map = {
- "user_map", (PyCFunction)bpy_user_map, METH_VARARGS | METH_KEYWORDS, bpy_user_map_doc};
+ static PyMethodDef user_map = {
+ "user_map", (PyCFunction)bpy_user_map, METH_VARARGS | METH_KEYWORDS, bpy_user_map_doc};
- PyModule_AddObject(mod_par, "_rna_id_collection_user_map", PyCFunction_New(&user_map, NULL));
+ PyModule_AddObject(mod_par, "_rna_id_collection_user_map", PyCFunction_New(&user_map, NULL));
- static PyMethodDef batch_remove = {
- "batch_remove", (PyCFunction)bpy_batch_remove, METH_VARARGS | METH_KEYWORDS, bpy_batch_remove_doc};
+ static PyMethodDef batch_remove = {"batch_remove",
+ (PyCFunction)bpy_batch_remove,
+ METH_VARARGS | METH_KEYWORDS,
+ bpy_batch_remove_doc};
- PyModule_AddObject(mod_par, "_rna_id_collection_batch_remove", PyCFunction_New(&batch_remove, NULL));
+ PyModule_AddObject(
+ mod_par, "_rna_id_collection_batch_remove", PyCFunction_New(&batch_remove, NULL));
- return 0;
+ return 0;
}
diff --git a/source/blender/python/intern/bpy_rna_id_collection.h b/source/blender/python/intern/bpy_rna_id_collection.h
index b66629fc790..8cb375960a9 100644
--- a/source/blender/python/intern/bpy_rna_id_collection.h
+++ b/source/blender/python/intern/bpy_rna_id_collection.h
@@ -23,4 +23,4 @@
int BPY_rna_id_collection_module(PyObject *);
-#endif /* __BPY_RNA_ID_COLLECTION_H__ */
+#endif /* __BPY_RNA_ID_COLLECTION_H__ */
diff --git a/source/blender/python/intern/bpy_traceback.c b/source/blender/python/intern/bpy_traceback.c
index 77cd8d8a9b7..c9c9e4adafb 100644
--- a/source/blender/python/intern/bpy_traceback.c
+++ b/source/blender/python/intern/bpy_traceback.c
@@ -21,167 +21,170 @@
* trace.
*/
-
#include <Python.h>
#include <frameobject.h>
#include "BLI_utildefines.h"
#include "BLI_path_util.h"
#ifdef WIN32
-# include "BLI_string.h" /* BLI_strcasecmp */
+# include "BLI_string.h" /* BLI_strcasecmp */
#endif
#include "bpy_traceback.h"
static const char *traceback_filepath(PyTracebackObject *tb, PyObject **coerce)
{
- return PyBytes_AS_STRING((*coerce = PyUnicode_EncodeFSDefault(tb->tb_frame->f_code->co_filename)));
+ return PyBytes_AS_STRING(
+ (*coerce = PyUnicode_EncodeFSDefault(tb->tb_frame->f_code->co_filename)));
}
/* copied from pythonrun.c, 3.4.0 */
_Py_static_string(PyId_string, "<string>");
-static int
-parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
- int *lineno, int *offset, PyObject **text)
+static int parse_syntax_error(PyObject *err,
+ PyObject **message,
+ PyObject **filename,
+ int *lineno,
+ int *offset,
+ PyObject **text)
{
- long hold;
- PyObject *v;
- _Py_IDENTIFIER(msg);
- _Py_IDENTIFIER(filename);
- _Py_IDENTIFIER(lineno);
- _Py_IDENTIFIER(offset);
- _Py_IDENTIFIER(text);
-
- *message = NULL;
- *filename = NULL;
-
- /* new style errors. `err' is an instance */
- *message = _PyObject_GetAttrId(err, &PyId_msg);
- if (!*message) {
- goto finally;
- }
-
- v = _PyObject_GetAttrId(err, &PyId_filename);
- if (!v) {
- goto finally;
- }
- if (v == Py_None) {
- Py_DECREF(v);
- *filename = _PyUnicode_FromId(&PyId_string);
- if (*filename == NULL) {
- goto finally;
- }
- Py_INCREF(*filename);
- }
- else {
- *filename = v;
- }
-
- v = _PyObject_GetAttrId(err, &PyId_lineno);
- if (!v) {
- goto finally;
- }
- hold = PyLong_AsLong(v);
- Py_DECREF(v);
- if (hold < 0 && PyErr_Occurred()) {
- goto finally;
- }
- *lineno = (int)hold;
-
- v = _PyObject_GetAttrId(err, &PyId_offset);
- if (!v) {
- goto finally;
- }
- if (v == Py_None) {
- *offset = -1;
- Py_DECREF(v);
- } else {
- hold = PyLong_AsLong(v);
- Py_DECREF(v);
- if (hold < 0 && PyErr_Occurred()) {
- goto finally;
- }
- *offset = (int)hold;
- }
-
- v = _PyObject_GetAttrId(err, &PyId_text);
- if (!v) {
- goto finally;
- }
- if (v == Py_None) {
- Py_DECREF(v);
- *text = NULL;
- }
- else {
- *text = v;
- }
- return 1;
+ long hold;
+ PyObject *v;
+ _Py_IDENTIFIER(msg);
+ _Py_IDENTIFIER(filename);
+ _Py_IDENTIFIER(lineno);
+ _Py_IDENTIFIER(offset);
+ _Py_IDENTIFIER(text);
+
+ *message = NULL;
+ *filename = NULL;
+
+ /* new style errors. `err' is an instance */
+ *message = _PyObject_GetAttrId(err, &PyId_msg);
+ if (!*message) {
+ goto finally;
+ }
+
+ v = _PyObject_GetAttrId(err, &PyId_filename);
+ if (!v) {
+ goto finally;
+ }
+ if (v == Py_None) {
+ Py_DECREF(v);
+ *filename = _PyUnicode_FromId(&PyId_string);
+ if (*filename == NULL) {
+ goto finally;
+ }
+ Py_INCREF(*filename);
+ }
+ else {
+ *filename = v;
+ }
+
+ v = _PyObject_GetAttrId(err, &PyId_lineno);
+ if (!v) {
+ goto finally;
+ }
+ hold = PyLong_AsLong(v);
+ Py_DECREF(v);
+ if (hold < 0 && PyErr_Occurred()) {
+ goto finally;
+ }
+ *lineno = (int)hold;
+
+ v = _PyObject_GetAttrId(err, &PyId_offset);
+ if (!v) {
+ goto finally;
+ }
+ if (v == Py_None) {
+ *offset = -1;
+ Py_DECREF(v);
+ }
+ else {
+ hold = PyLong_AsLong(v);
+ Py_DECREF(v);
+ if (hold < 0 && PyErr_Occurred()) {
+ goto finally;
+ }
+ *offset = (int)hold;
+ }
+
+ v = _PyObject_GetAttrId(err, &PyId_text);
+ if (!v) {
+ goto finally;
+ }
+ if (v == Py_None) {
+ Py_DECREF(v);
+ *text = NULL;
+ }
+ else {
+ *text = v;
+ }
+ return 1;
finally:
- Py_XDECREF(*message);
- Py_XDECREF(*filename);
- return 0;
+ Py_XDECREF(*message);
+ Py_XDECREF(*filename);
+ return 0;
}
/* end copied function! */
-
void python_script_error_jump(const char *filepath, int *lineno, int *offset)
{
- PyObject *exception, *value;
- PyTracebackObject *tb;
-
- *lineno = -1;
- *offset = 0;
-
- PyErr_Fetch(&exception, &value, (PyObject **)&tb);
-
- if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
- /* no traceback available when SyntaxError.
- * python has no api's to this. reference parse_syntax_error() from pythonrun.c */
- PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
- PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
-
- if (value) { /* should always be true */
- PyObject *message;
- PyObject *filename_py, *text_py;
-
- if (parse_syntax_error(value, &message, &filename_py, lineno, offset, &text_py)) {
- const char *filename = _PyUnicode_AsString(filename_py);
- /* python adds a '/', prefix, so check for both */
- if ((BLI_path_cmp(filename, filepath) == 0) ||
- ((filename[0] == '\\' || filename[0] == '/') && BLI_path_cmp(filename + 1, filepath) == 0))
- {
- /* good */
- }
- else {
- *lineno = -1;
- }
- }
- else {
- *lineno = -1;
- }
- }
- }
- else {
- PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
- PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
- PyErr_Print();
-
- for (tb = (PyTracebackObject *)PySys_GetObject("last_traceback");
- tb && (PyObject *)tb != Py_None;
- tb = tb->tb_next)
- {
- PyObject *coerce;
- const char *tb_filepath = traceback_filepath(tb, &coerce);
- const int match = ((BLI_path_cmp(tb_filepath, filepath) == 0) ||
- ((tb_filepath[0] == '\\' || tb_filepath[0] == '/') && BLI_path_cmp(tb_filepath + 1, filepath) == 0));
- Py_DECREF(coerce);
-
- if (match) {
- *lineno = tb->tb_lineno;
- /* used to break here, but better find the inner most line */
- }
- }
- }
+ PyObject *exception, *value;
+ PyTracebackObject *tb;
+
+ *lineno = -1;
+ *offset = 0;
+
+ PyErr_Fetch(&exception, &value, (PyObject **)&tb);
+
+ if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
+ /* no traceback available when SyntaxError.
+ * python has no api's to this. reference parse_syntax_error() from pythonrun.c */
+ PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
+ PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
+
+ if (value) { /* should always be true */
+ PyObject *message;
+ PyObject *filename_py, *text_py;
+
+ if (parse_syntax_error(value, &message, &filename_py, lineno, offset, &text_py)) {
+ const char *filename = _PyUnicode_AsString(filename_py);
+ /* python adds a '/', prefix, so check for both */
+ if ((BLI_path_cmp(filename, filepath) == 0) ||
+ ((filename[0] == '\\' || filename[0] == '/') &&
+ BLI_path_cmp(filename + 1, filepath) == 0)) {
+ /* good */
+ }
+ else {
+ *lineno = -1;
+ }
+ }
+ else {
+ *lineno = -1;
+ }
+ }
+ }
+ else {
+ PyErr_NormalizeException(&exception, &value, (PyObject **)&tb);
+ PyErr_Restore(exception, value, (PyObject *)tb); /* takes away reference! */
+ PyErr_Print();
+
+ for (tb = (PyTracebackObject *)PySys_GetObject("last_traceback");
+ tb && (PyObject *)tb != Py_None;
+ tb = tb->tb_next) {
+ PyObject *coerce;
+ const char *tb_filepath = traceback_filepath(tb, &coerce);
+ const int match = ((BLI_path_cmp(tb_filepath, filepath) == 0) ||
+ ((tb_filepath[0] == '\\' || tb_filepath[0] == '/') &&
+ BLI_path_cmp(tb_filepath + 1, filepath) == 0));
+ Py_DECREF(coerce);
+
+ if (match) {
+ *lineno = tb->tb_lineno;
+ /* used to break here, but better find the inner most line */
+ }
+ }
+ }
}
diff --git a/source/blender/python/intern/bpy_traceback.h b/source/blender/python/intern/bpy_traceback.h
index 118b594b6d9..11295706240 100644
--- a/source/blender/python/intern/bpy_traceback.h
+++ b/source/blender/python/intern/bpy_traceback.h
@@ -18,10 +18,9 @@
* \ingroup pythonintern
*/
-
#ifndef __BPY_TRACEBACK_H__
#define __BPY_TRACEBACK_H__
void python_script_error_jump(const char *filepath, int *lineno, int *offset);
-#endif /* __BPY_TRACEBACK_H__ */
+#endif /* __BPY_TRACEBACK_H__ */
diff --git a/source/blender/python/intern/bpy_utils_previews.c b/source/blender/python/intern/bpy_utils_previews.c
index 338e915780d..7423e55d253 100644
--- a/source/blender/python/intern/bpy_utils_previews.c
+++ b/source/blender/python/intern/bpy_utils_previews.c
@@ -50,133 +50,140 @@
#define STR_SOURCE_TYPES "'IMAGE', 'MOVIE', 'BLEND', 'FONT'"
PyDoc_STRVAR(bpy_utils_previews_new_doc,
-".. method:: new(name)\n"
-"\n"
-" Generate a new empty preview, or return existing one matching ``name``.\n"
-"\n"
-" :arg name: The name (unique id) identifying the preview.\n"
-" :type name: string\n"
-" :return: The Preview matching given name, or a new empty one.\n"
-" :rtype: :class:`bpy.types.ImagePreview`\n"
-);
+ ".. method:: new(name)\n"
+ "\n"
+ " Generate a new empty preview, or return existing one matching ``name``.\n"
+ "\n"
+ " :arg name: The name (unique id) identifying the preview.\n"
+ " :type name: string\n"
+ " :return: The Preview matching given name, or a new empty one.\n"
+ " :rtype: :class:`bpy.types.ImagePreview`\n");
static PyObject *bpy_utils_previews_new(PyObject *UNUSED(self), PyObject *args)
{
- char *name;
- PreviewImage *prv;
- PointerRNA ptr;
+ char *name;
+ PreviewImage *prv;
+ PointerRNA ptr;
- if (!PyArg_ParseTuple(args, "s:new", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:new", &name)) {
+ return NULL;
+ }
- prv = BKE_previewimg_cached_ensure(name);
- RNA_pointer_create(NULL, &RNA_ImagePreview, prv, &ptr);
+ prv = BKE_previewimg_cached_ensure(name);
+ RNA_pointer_create(NULL, &RNA_ImagePreview, prv, &ptr);
- return pyrna_struct_CreatePyObject(&ptr);
+ return pyrna_struct_CreatePyObject(&ptr);
}
-PyDoc_STRVAR(bpy_utils_previews_load_doc,
-".. method:: load(name, filepath, filetype, force_reload=False)\n"
-"\n"
-" Generate a new preview from given file path, or return existing one matching ``name``.\n"
-"\n"
-" :arg name: The name (unique id) identifying the preview.\n"
-" :type name: string\n"
-" :arg filepath: The file path to generate the preview from.\n"
-" :type filepath: string\n"
-" :arg filetype: The type of file, needed to generate the preview in [" STR_SOURCE_TYPES "].\n"
-" :type filetype: string\n"
-" :arg force_reload: If True, force running thumbnail manager even if preview already exists in cache.\n"
-" :type force_reload: bool\n"
-" :return: The Preview matching given name, or a new empty one.\n"
-" :rtype: :class:`bpy.types.ImagePreview`\n"
-);
+PyDoc_STRVAR(
+ bpy_utils_previews_load_doc,
+ ".. method:: load(name, filepath, filetype, force_reload=False)\n"
+ "\n"
+ " Generate a new preview from given file path, or return existing one matching ``name``.\n"
+ "\n"
+ " :arg name: The name (unique id) identifying the preview.\n"
+ " :type name: string\n"
+ " :arg filepath: The file path to generate the preview from.\n"
+ " :type filepath: string\n"
+ " :arg filetype: The type of file, needed to generate the preview in [" STR_SOURCE_TYPES
+ "].\n"
+ " :type filetype: string\n"
+ " :arg force_reload: If True, force running thumbnail manager even if preview already "
+ "exists in cache.\n"
+ " :type force_reload: bool\n"
+ " :return: The Preview matching given name, or a new empty one.\n"
+ " :rtype: :class:`bpy.types.ImagePreview`\n");
static PyObject *bpy_utils_previews_load(PyObject *UNUSED(self), PyObject *args)
{
- char *name, *path, *path_type_s;
- int path_type, force_reload = false;
-
- PreviewImage *prv;
- PointerRNA ptr;
-
- if (!PyArg_ParseTuple( args, "sss|p:load", &name, &path, &path_type_s, &force_reload)) {
- return NULL;
- }
-
- if (STREQ(path_type_s, "IMAGE")) {
- path_type = THB_SOURCE_IMAGE;
- }
- else if (STREQ(path_type_s, "MOVIE")) {
- path_type = THB_SOURCE_MOVIE;
- }
- else if (STREQ(path_type_s, "BLEND")) {
- path_type = THB_SOURCE_BLEND;
- }
- else if (STREQ(path_type_s, "FONT")) {
- path_type = THB_SOURCE_FONT;
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "load: invalid '%s' filetype, only [" STR_SOURCE_TYPES "] "
- "are supported", path_type_s);
- return NULL;
- }
-
- prv = BKE_previewimg_cached_thumbnail_read(name, path, path_type, force_reload);
- RNA_pointer_create(NULL, &RNA_ImagePreview, prv, &ptr);
-
- return pyrna_struct_CreatePyObject(&ptr);
+ char *name, *path, *path_type_s;
+ int path_type, force_reload = false;
+
+ PreviewImage *prv;
+ PointerRNA ptr;
+
+ if (!PyArg_ParseTuple(args, "sss|p:load", &name, &path, &path_type_s, &force_reload)) {
+ return NULL;
+ }
+
+ if (STREQ(path_type_s, "IMAGE")) {
+ path_type = THB_SOURCE_IMAGE;
+ }
+ else if (STREQ(path_type_s, "MOVIE")) {
+ path_type = THB_SOURCE_MOVIE;
+ }
+ else if (STREQ(path_type_s, "BLEND")) {
+ path_type = THB_SOURCE_BLEND;
+ }
+ else if (STREQ(path_type_s, "FONT")) {
+ path_type = THB_SOURCE_FONT;
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "load: invalid '%s' filetype, only [" STR_SOURCE_TYPES
+ "] "
+ "are supported",
+ path_type_s);
+ return NULL;
+ }
+
+ prv = BKE_previewimg_cached_thumbnail_read(name, path, path_type, force_reload);
+ RNA_pointer_create(NULL, &RNA_ImagePreview, prv, &ptr);
+
+ return pyrna_struct_CreatePyObject(&ptr);
}
PyDoc_STRVAR(bpy_utils_previews_release_doc,
-".. method:: release(name)\n"
-"\n"
-" Release (free) a previously created preview.\n"
-"\n"
-"\n"
-" :arg name: The name (unique id) identifying the preview.\n"
-" :type name: string\n"
-);
+ ".. method:: release(name)\n"
+ "\n"
+ " Release (free) a previously created preview.\n"
+ "\n"
+ "\n"
+ " :arg name: The name (unique id) identifying the preview.\n"
+ " :type name: string\n");
static PyObject *bpy_utils_previews_release(PyObject *UNUSED(self), PyObject *args)
{
- char *name;
+ char *name;
- if (!PyArg_ParseTuple(args, "s:release", &name)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s:release", &name)) {
+ return NULL;
+ }
- BKE_previewimg_cached_release(name);
+ BKE_previewimg_cached_release(name);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef bpy_utils_previews_methods[] = {
- /* Can't use METH_KEYWORDS alone, see http://bugs.python.org/issue11587 */
- {"new", (PyCFunction)bpy_utils_previews_new, METH_VARARGS, bpy_utils_previews_new_doc},
- {"load", (PyCFunction)bpy_utils_previews_load, METH_VARARGS, bpy_utils_previews_load_doc},
- {"release", (PyCFunction)bpy_utils_previews_release, METH_VARARGS, bpy_utils_previews_release_doc},
- {NULL, NULL, 0, NULL},
+ /* Can't use METH_KEYWORDS alone, see http://bugs.python.org/issue11587 */
+ {"new", (PyCFunction)bpy_utils_previews_new, METH_VARARGS, bpy_utils_previews_new_doc},
+ {"load", (PyCFunction)bpy_utils_previews_load, METH_VARARGS, bpy_utils_previews_load_doc},
+ {"release",
+ (PyCFunction)bpy_utils_previews_release,
+ METH_VARARGS,
+ bpy_utils_previews_release_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(bpy_utils_previews_doc,
-"This object contains basic static methods to handle cached (non-ID) previews in Blender\n"
-"(low-level API, not exposed to final users)."
-);
+PyDoc_STRVAR(
+ bpy_utils_previews_doc,
+ "This object contains basic static methods to handle cached (non-ID) previews in Blender\n"
+ "(low-level API, not exposed to final users).");
static struct PyModuleDef bpy_utils_previews_module = {
- PyModuleDef_HEAD_INIT,
- "bpy._utils_previews",
- bpy_utils_previews_doc,
- 0,
- bpy_utils_previews_methods,
- NULL, NULL, NULL, NULL,
+ PyModuleDef_HEAD_INIT,
+ "bpy._utils_previews",
+ bpy_utils_previews_doc,
+ 0,
+ bpy_utils_previews_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
-
PyObject *BPY_utils_previews_module(void)
{
- PyObject *submodule;
+ PyObject *submodule;
- submodule = PyModule_Create(&bpy_utils_previews_module);
+ submodule = PyModule_Create(&bpy_utils_previews_module);
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/intern/bpy_utils_units.c b/source/blender/python/intern/bpy_utils_units.c
index abae53088a8..b80ea50dd09 100644
--- a/source/blender/python/intern/bpy_utils_units.c
+++ b/source/blender/python/intern/bpy_utils_units.c
@@ -43,25 +43,25 @@ static PyTypeObject BPyUnitsCategoriesType;
/* XXX Maybe better as externs of BKE_unit.h ? */
static const char *bpyunits_usystem_items[] = {
- "NONE",
- "METRIC",
- "IMPERIAL",
- NULL,
+ "NONE",
+ "METRIC",
+ "IMPERIAL",
+ NULL,
};
static const char *bpyunits_ucategorie_items[] = {
- "NONE",
- "LENGTH",
- "AREA",
- "VOLUME",
- "MASS",
- "ROTATION",
- "TIME",
- "VELOCITY",
- "ACCELERATION",
- "CAMERA",
- "POWER",
- NULL,
+ "NONE",
+ "LENGTH",
+ "AREA",
+ "VOLUME",
+ "MASS",
+ "ROTATION",
+ "TIME",
+ "VELOCITY",
+ "ACCELERATION",
+ "CAMERA",
+ "POWER",
+ NULL,
};
/**
@@ -73,261 +73,282 @@ static PyStructSequence_Field bpyunits_systems_fields[ARRAY_SIZE(bpyunits_usyste
static PyStructSequence_Field bpyunits_categories_fields[ARRAY_SIZE(bpyunits_ucategorie_items)];
static PyStructSequence_Desc bpyunits_systems_desc = {
- (char *)"bpy.utils.units.systems", /* name */
- (char *)"This named tuple contains all pre-defined unit systems", /* doc */
- bpyunits_systems_fields, /* fields */
- ARRAY_SIZE(bpyunits_systems_fields) - 1,
+ (char *)"bpy.utils.units.systems", /* name */
+ (char *)"This named tuple contains all pre-defined unit systems", /* doc */
+ bpyunits_systems_fields, /* fields */
+ ARRAY_SIZE(bpyunits_systems_fields) - 1,
};
static PyStructSequence_Desc bpyunits_categories_desc = {
- (char *)"bpy.utils.units.categories", /* name */
- (char *)"This named tuple contains all pre-defined unit names", /* doc */
- bpyunits_categories_fields, /* fields */
- ARRAY_SIZE(bpyunits_categories_fields) - 1,
+ (char *)"bpy.utils.units.categories", /* name */
+ (char *)"This named tuple contains all pre-defined unit names", /* doc */
+ bpyunits_categories_fields, /* fields */
+ ARRAY_SIZE(bpyunits_categories_fields) - 1,
};
/**
* Simple utility function to initialize #PyStructSequence_Desc
*/
-static PyObject *py_structseq_from_strings(
- PyTypeObject *py_type,
- PyStructSequence_Desc *py_sseq_desc,
- const char **str_items)
+static PyObject *py_structseq_from_strings(PyTypeObject *py_type,
+ PyStructSequence_Desc *py_sseq_desc,
+ const char **str_items)
{
- PyObject *py_struct_seq;
- int pos = 0;
+ PyObject *py_struct_seq;
+ int pos = 0;
- const char **str_iter;
- PyStructSequence_Field *desc;
+ const char **str_iter;
+ PyStructSequence_Field *desc;
- /* initialize array */
- /* We really populate the contexts' fields here! */
- for (str_iter = str_items, desc = py_sseq_desc->fields; *str_iter; str_iter++, desc++) {
- desc->name = (char *)*str_iter;
- desc->doc = NULL;
- }
- /* end sentinel */
- desc->name = desc->doc = NULL;
+ /* initialize array */
+ /* We really populate the contexts' fields here! */
+ for (str_iter = str_items, desc = py_sseq_desc->fields; *str_iter; str_iter++, desc++) {
+ desc->name = (char *)*str_iter;
+ desc->doc = NULL;
+ }
+ /* end sentinel */
+ desc->name = desc->doc = NULL;
- PyStructSequence_InitType(py_type, py_sseq_desc);
+ PyStructSequence_InitType(py_type, py_sseq_desc);
- /* initialize pytype */
- py_struct_seq = PyStructSequence_New(py_type);
- BLI_assert(py_struct_seq != NULL);
+ /* initialize pytype */
+ py_struct_seq = PyStructSequence_New(py_type);
+ BLI_assert(py_struct_seq != NULL);
- for (str_iter = str_items; *str_iter; str_iter++) {
- PyStructSequence_SET_ITEM(py_struct_seq, pos++, PyUnicode_FromString((*str_iter)));
- }
+ for (str_iter = str_items; *str_iter; str_iter++) {
+ PyStructSequence_SET_ITEM(py_struct_seq, pos++, PyUnicode_FromString((*str_iter)));
+ }
- return py_struct_seq;
+ return py_struct_seq;
}
static bool bpyunits_validate(const char *usys_str, const char *ucat_str, int *r_usys, int *r_ucat)
{
- *r_usys = BLI_str_index_in_array(usys_str, bpyunits_usystem_items);
- if (*r_usys < 0) {
- PyErr_Format(PyExc_ValueError,
- "Unknown unit system specified: %.200s.",
- usys_str);
- return false;
- }
-
- *r_ucat = BLI_str_index_in_array(ucat_str, bpyunits_ucategorie_items);
- if (*r_ucat < 0) {
- PyErr_Format(PyExc_ValueError,
- "Unknown unit category specified: %.200s.",
- ucat_str);
- return false;
- }
-
- if (!bUnit_IsValid(*r_usys, *r_ucat)) {
- PyErr_Format(PyExc_ValueError,
- "%.200s / %.200s unit system/category combination is not valid.",
- usys_str, ucat_str);
- return false;
- }
-
- return true;
+ *r_usys = BLI_str_index_in_array(usys_str, bpyunits_usystem_items);
+ if (*r_usys < 0) {
+ PyErr_Format(PyExc_ValueError, "Unknown unit system specified: %.200s.", usys_str);
+ return false;
+ }
+
+ *r_ucat = BLI_str_index_in_array(ucat_str, bpyunits_ucategorie_items);
+ if (*r_ucat < 0) {
+ PyErr_Format(PyExc_ValueError, "Unknown unit category specified: %.200s.", ucat_str);
+ return false;
+ }
+
+ if (!bUnit_IsValid(*r_usys, *r_ucat)) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s / %.200s unit system/category combination is not valid.",
+ usys_str,
+ ucat_str);
+ return false;
+ }
+
+ return true;
}
-PyDoc_STRVAR(bpyunits_to_value_doc,
-".. method:: to_value(unit_system, unit_category, str_input, str_ref_unit=None)\n"
-"\n"
-" Convert a given input string into a float value.\n"
-"\n"
-" :arg unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
-" :type unit_system: string\n"
-" :arg unit_category: The category of data we are converting (length, area, rotation, etc.),\n"
-" from :attr:`bpy.utils.units.categories`.\n"
-" :type unit_category: string\n"
-" :arg str_input: The string to convert to a float value.\n"
-" :type str_input: string\n"
-" :arg str_ref_unit: A reference string from which to extract a default unit, if none is found in ``str_input``.\n"
-" :type str_ref_unit: string or None\n"
-" :return: The converted/interpreted value.\n"
-" :rtype: float\n"
-" :raises ValueError: if conversion fails to generate a valid python float value.\n"
-);
+PyDoc_STRVAR(
+ bpyunits_to_value_doc,
+ ".. method:: to_value(unit_system, unit_category, str_input, str_ref_unit=None)\n"
+ "\n"
+ " Convert a given input string into a float value.\n"
+ "\n"
+ " :arg unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
+ " :type unit_system: string\n"
+ " :arg unit_category: The category of data we are converting (length, area, rotation, "
+ "etc.),\n"
+ " from :attr:`bpy.utils.units.categories`.\n"
+ " :type unit_category: string\n"
+ " :arg str_input: The string to convert to a float value.\n"
+ " :type str_input: string\n"
+ " :arg str_ref_unit: A reference string from which to extract a default unit, if none is "
+ "found in ``str_input``.\n"
+ " :type str_ref_unit: string or None\n"
+ " :return: The converted/interpreted value.\n"
+ " :rtype: float\n"
+ " :raises ValueError: if conversion fails to generate a valid python float value.\n");
static PyObject *bpyunits_to_value(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- char *usys_str = NULL, *ucat_str = NULL, *inpt = NULL, *uref = NULL;
- const float scale = 1.0f;
-
- char *str;
- Py_ssize_t str_len;
- double result;
- int usys, ucat;
- PyObject *ret;
-
- static const char *_keywords[] = {
- "unit_system", "unit_category", "str_input", "str_ref_unit", NULL,
- };
- static _PyArg_Parser _parser = {"sss#|z:to_value", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &usys_str, &ucat_str, &inpt, &str_len, &uref))
- {
- return NULL;
- }
-
- if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
- return NULL;
- }
-
- str_len = str_len * 2 + 64;
- str = PyMem_MALLOC(sizeof(*str) * (size_t)str_len);
- BLI_strncpy(str, inpt, (size_t)str_len);
-
- bUnit_ReplaceString(str, (int)str_len, uref, scale, usys, ucat);
-
- if (!PyC_RunString_AsNumber(NULL, str, "<bpy_units_api>", &result)) {
- if (PyErr_Occurred()) {
- PyErr_Print();
- PyErr_Clear();
- }
-
- PyErr_Format(PyExc_ValueError,
- "'%.200s' (converted as '%s') could not be evaluated.",
- inpt, str);
- ret = NULL;
- }
- else {
- ret = PyFloat_FromDouble(result);
- }
-
- PyMem_FREE(str);
- return ret;
+ char *usys_str = NULL, *ucat_str = NULL, *inpt = NULL, *uref = NULL;
+ const float scale = 1.0f;
+
+ char *str;
+ Py_ssize_t str_len;
+ double result;
+ int usys, ucat;
+ PyObject *ret;
+
+ static const char *_keywords[] = {
+ "unit_system",
+ "unit_category",
+ "str_input",
+ "str_ref_unit",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"sss#|z:to_value", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser, &usys_str, &ucat_str, &inpt, &str_len, &uref)) {
+ return NULL;
+ }
+
+ if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
+ return NULL;
+ }
+
+ str_len = str_len * 2 + 64;
+ str = PyMem_MALLOC(sizeof(*str) * (size_t)str_len);
+ BLI_strncpy(str, inpt, (size_t)str_len);
+
+ bUnit_ReplaceString(str, (int)str_len, uref, scale, usys, ucat);
+
+ if (!PyC_RunString_AsNumber(NULL, str, "<bpy_units_api>", &result)) {
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+
+ PyErr_Format(
+ PyExc_ValueError, "'%.200s' (converted as '%s') could not be evaluated.", inpt, str);
+ ret = NULL;
+ }
+ else {
+ ret = PyFloat_FromDouble(result);
+ }
+
+ PyMem_FREE(str);
+ return ret;
}
PyDoc_STRVAR(bpyunits_to_string_doc,
-".. method:: to_string(unit_system, unit_category, value, precision=3, split_unit=False, compatible_unit=False)\n"
-"\n"
-" Convert a given input float value into a string with units.\n"
-"\n"
-" :arg unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
-" :type unit_system: string\n"
-" :arg unit_category: The category of data we are converting (length, area, rotation, etc.),\n"
-" from :attr:`bpy.utils.units.categories`.\n"
-" :type unit_category: string\n"
-" :arg value: The value to convert to a string.\n"
-" :type value: float\n"
-" :arg precision: Number of digits after the comma.\n"
-" :type precision: int\n"
-" :arg split_unit: Whether to use several units if needed (1m1cm), or always only one (1.01m).\n"
-" :type split_unit: bool\n"
-" :arg compatible_unit: Whether to use keyboard-friendly units (1m2) or nicer utf-8 ones (1m²).\n"
-" :type compatible_unit: bool\n"
-" :return: The converted string.\n"
-" :rtype: str\n"
-" :raises ValueError: if conversion fails to generate a valid python string.\n"
-);
+ ".. method:: to_string(unit_system, unit_category, value, precision=3, "
+ "split_unit=False, compatible_unit=False)\n"
+ "\n"
+ " Convert a given input float value into a string with units.\n"
+ "\n"
+ " :arg unit_system: The unit system, from :attr:`bpy.utils.units.systems`.\n"
+ " :type unit_system: string\n"
+ " :arg unit_category: The category of data we are converting (length, area, "
+ "rotation, etc.),\n"
+ " from :attr:`bpy.utils.units.categories`.\n"
+ " :type unit_category: string\n"
+ " :arg value: The value to convert to a string.\n"
+ " :type value: float\n"
+ " :arg precision: Number of digits after the comma.\n"
+ " :type precision: int\n"
+ " :arg split_unit: Whether to use several units if needed (1m1cm), or always only "
+ "one (1.01m).\n"
+ " :type split_unit: bool\n"
+ " :arg compatible_unit: Whether to use keyboard-friendly units (1m2) or nicer "
+ "utf-8 ones (1m²).\n"
+ " :type compatible_unit: bool\n"
+ " :return: The converted string.\n"
+ " :rtype: str\n"
+ " :raises ValueError: if conversion fails to generate a valid python string.\n");
static PyObject *bpyunits_to_string(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- char *usys_str = NULL, *ucat_str = NULL;
- double value = 0.0;
- int precision = 3;
- bool split_unit = false, compatible_unit = false;
-
- int usys, ucat;
-
- static const char *_keywords[] = {
- "unit_system", "unit_category", "value",
- "precision", "split_unit", "compatible_unit", NULL,
- };
- static _PyArg_Parser _parser = {"ssd|iO&O&:to_string", _keywords, 0};
- if (!_PyArg_ParseTupleAndKeywordsFast(
- args, kw, &_parser,
- &usys_str, &ucat_str, &value, &precision,
- PyC_ParseBool, &split_unit,
- PyC_ParseBool, &compatible_unit))
- {
- return NULL;
- }
-
- if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
- return NULL;
- }
-
- {
- /* Maximum expected length of string result:
- * - number itself: precision + decimal dot + up to four 'above dot' digits.
- * - unit: up to ten chars (six currently, let's be conservative, also because we use some utf8 chars).
- * This can be repeated twice (e.g. 1m20cm), and we add ten more spare chars (spaces, trailing '\0'...).
- * So in practice, 64 should be more than enough.
- */
- char buf1[64], buf2[64], *str;
- PyObject *result;
-
- bUnit_AsString(buf1, sizeof(buf1), value, precision, usys, ucat, (bool)split_unit, false);
-
- if (compatible_unit) {
- bUnit_ToUnitAltName(buf2, sizeof(buf2), buf1, usys, ucat);
- str = buf2;
- }
- else {
- str = buf1;
- }
-
- result = PyUnicode_FromString(str);
-
- return result;
- }
+ char *usys_str = NULL, *ucat_str = NULL;
+ double value = 0.0;
+ int precision = 3;
+ bool split_unit = false, compatible_unit = false;
+
+ int usys, ucat;
+
+ static const char *_keywords[] = {
+ "unit_system",
+ "unit_category",
+ "value",
+ "precision",
+ "split_unit",
+ "compatible_unit",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"ssd|iO&O&:to_string", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(args,
+ kw,
+ &_parser,
+ &usys_str,
+ &ucat_str,
+ &value,
+ &precision,
+ PyC_ParseBool,
+ &split_unit,
+ PyC_ParseBool,
+ &compatible_unit)) {
+ return NULL;
+ }
+
+ if (!bpyunits_validate(usys_str, ucat_str, &usys, &ucat)) {
+ return NULL;
+ }
+
+ {
+ /* Maximum expected length of string result:
+ * - number itself: precision + decimal dot + up to four 'above dot' digits.
+ * - unit: up to ten chars (six currently, let's be conservative, also because we use some utf8 chars).
+ * This can be repeated twice (e.g. 1m20cm), and we add ten more spare chars (spaces, trailing '\0'...).
+ * So in practice, 64 should be more than enough.
+ */
+ char buf1[64], buf2[64], *str;
+ PyObject *result;
+
+ bUnit_AsString(buf1, sizeof(buf1), value, precision, usys, ucat, (bool)split_unit, false);
+
+ if (compatible_unit) {
+ bUnit_ToUnitAltName(buf2, sizeof(buf2), buf1, usys, ucat);
+ str = buf2;
+ }
+ else {
+ str = buf1;
+ }
+
+ result = PyUnicode_FromString(str);
+
+ return result;
+ }
}
static PyMethodDef bpyunits_methods[] = {
- {"to_value", (PyCFunction)bpyunits_to_value, METH_VARARGS | METH_KEYWORDS, bpyunits_to_value_doc},
- {"to_string", (PyCFunction)bpyunits_to_string, METH_VARARGS | METH_KEYWORDS, bpyunits_to_string_doc},
- {NULL, NULL, 0, NULL},
+ {"to_value",
+ (PyCFunction)bpyunits_to_value,
+ METH_VARARGS | METH_KEYWORDS,
+ bpyunits_to_value_doc},
+ {"to_string",
+ (PyCFunction)bpyunits_to_string,
+ METH_VARARGS | METH_KEYWORDS,
+ bpyunits_to_string_doc},
+ {NULL, NULL, 0, NULL},
};
-PyDoc_STRVAR(bpyunits_doc,
-"This module contains some data/methods regarding units handling."
-);
+PyDoc_STRVAR(bpyunits_doc, "This module contains some data/methods regarding units handling.");
static struct PyModuleDef bpyunits_module = {
- PyModuleDef_HEAD_INIT,
- "bpy.utils.units",
- bpyunits_doc,
- -1, /* multiple "initialization" just copies the module dict. */
- bpyunits_methods,
- NULL, NULL, NULL, NULL,
+ PyModuleDef_HEAD_INIT,
+ "bpy.utils.units",
+ bpyunits_doc,
+ -1, /* multiple "initialization" just copies the module dict. */
+ bpyunits_methods,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
};
PyObject *BPY_utils_units(void)
{
- PyObject *submodule, *item;
+ PyObject *submodule, *item;
- submodule = PyModule_Create(&bpyunits_module);
- PyDict_SetItemString(PyImport_GetModuleDict(), bpyunits_module.m_name, submodule);
+ submodule = PyModule_Create(&bpyunits_module);
+ PyDict_SetItemString(PyImport_GetModuleDict(), bpyunits_module.m_name, submodule);
- /* Finalize our unit systems and types structseq definitions! */
+ /* Finalize our unit systems and types structseq definitions! */
- /* bpy.utils.units.system */
- item = py_structseq_from_strings(&BPyUnitsSystemsType, &bpyunits_systems_desc, bpyunits_usystem_items);
- PyModule_AddObject(submodule, "systems", item); /* steals ref */
+ /* bpy.utils.units.system */
+ item = py_structseq_from_strings(
+ &BPyUnitsSystemsType, &bpyunits_systems_desc, bpyunits_usystem_items);
+ PyModule_AddObject(submodule, "systems", item); /* steals ref */
- /* bpy.utils.units.categories */
- item = py_structseq_from_strings(&BPyUnitsCategoriesType, &bpyunits_categories_desc, bpyunits_ucategorie_items);
- PyModule_AddObject(submodule, "categories", item); /* steals ref */
+ /* bpy.utils.units.categories */
+ item = py_structseq_from_strings(
+ &BPyUnitsCategoriesType, &bpyunits_categories_desc, bpyunits_ucategorie_items);
+ PyModule_AddObject(submodule, "categories", item); /* steals ref */
- return submodule;
+ return submodule;
}
diff --git a/source/blender/python/intern/bpy_utils_units.h b/source/blender/python/intern/bpy_utils_units.h
index 55b79da6a93..5a30c1c3dae 100644
--- a/source/blender/python/intern/bpy_utils_units.h
+++ b/source/blender/python/intern/bpy_utils_units.h
@@ -23,4 +23,4 @@
PyObject *BPY_utils_units(void);
-#endif /* __BPY_UTILS_UNITS_H__ */
+#endif /* __BPY_UTILS_UNITS_H__ */
diff --git a/source/blender/python/intern/stubs.c b/source/blender/python/intern/stubs.c
index b6c30828f74..bf068f99722 100644
--- a/source/blender/python/intern/stubs.c
+++ b/source/blender/python/intern/stubs.c
@@ -34,7 +34,18 @@
//void BPY_script_exec(void) {}
//void BPY_python_start(void) {}
//void BPY_text_free_code(void) {}
-void BPY_pyconstraint_exec(struct bPythonConstraint *con, struct bConstraintOb *cob, struct ListBase *targets) {}
-void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct) {}
-int BPY_is_pyconstraint(struct Text *text) { return 0;}
-void BPY_pyconstraint_update(struct Object *owner, struct bConstraint *con) {}
+void BPY_pyconstraint_exec(struct bPythonConstraint *con,
+ struct bConstraintOb *cob,
+ struct ListBase *targets)
+{
+}
+void BPY_pyconstraint_target(struct bPythonConstraint *con, struct bConstraintTarget *ct)
+{
+}
+int BPY_is_pyconstraint(struct Text *text)
+{
+ return 0;
+}
+void BPY_pyconstraint_update(struct Object *owner, struct bConstraint *con)
+{
+}
diff --git a/source/blender/python/mathutils/CMakeLists.txt b/source/blender/python/mathutils/CMakeLists.txt
index 7b0c042d50a..a58260a84f6 100644
--- a/source/blender/python/mathutils/CMakeLists.txt
+++ b/source/blender/python/mathutils/CMakeLists.txt
@@ -16,48 +16,48 @@
# ***** END GPL LICENSE BLOCK *****
set(INC
- .
- ../../blenlib
- ../../blenkernel
- ../../bmesh
- ../../depsgraph
- ../../makesdna
- ../../../../intern/guardedalloc
+ .
+ ../../blenlib
+ ../../blenkernel
+ ../../bmesh
+ ../../depsgraph
+ ../../makesdna
+ ../../../../intern/guardedalloc
)
set(INC_SYS
- ${PYTHON_INCLUDE_DIRS}
+ ${PYTHON_INCLUDE_DIRS}
)
set(SRC
- mathutils.c
- mathutils_Color.c
- mathutils_Euler.c
- mathutils_Matrix.c
- mathutils_Quaternion.c
- mathutils_Vector.c
- mathutils_bvhtree.c
- mathutils_geometry.c
- mathutils_interpolate.c
- mathutils_kdtree.c
- mathutils_noise.c
+ mathutils.c
+ mathutils_Color.c
+ mathutils_Euler.c
+ mathutils_Matrix.c
+ mathutils_Quaternion.c
+ mathutils_Vector.c
+ mathutils_bvhtree.c
+ mathutils_geometry.c
+ mathutils_interpolate.c
+ mathutils_kdtree.c
+ mathutils_noise.c
- mathutils.h
- mathutils_Color.h
- mathutils_Euler.h
- mathutils_Matrix.h
- mathutils_Quaternion.h
- mathutils_Vector.h
- mathutils_bvhtree.h
- mathutils_geometry.h
- mathutils_interpolate.h
- mathutils_kdtree.h
- mathutils_noise.h
+ mathutils.h
+ mathutils_Color.h
+ mathutils_Euler.h
+ mathutils_Matrix.h
+ mathutils_Quaternion.h
+ mathutils_Vector.h
+ mathutils_bvhtree.h
+ mathutils_geometry.h
+ mathutils_interpolate.h
+ mathutils_kdtree.h
+ mathutils_noise.h
)
set(LIB
- bf_blenlib
- bf_python_ext
+ bf_blenlib
+ bf_python_ext
)
diff --git a/source/blender/python/mathutils/mathutils.c b/source/blender/python/mathutils/mathutils.c
index 41738ced41a..32ffa4ad2da 100644
--- a/source/blender/python/mathutils/mathutils.c
+++ b/source/blender/python/mathutils/mathutils.c
@@ -31,59 +31,60 @@
# include "BLI_dynstr.h"
#endif
-PyDoc_STRVAR(M_Mathutils_doc,
-"This module provides access to math operations.\n"
-"\n"
-".. note::\n"
-"\n"
-" Classes, methods and attributes that accept vectors also accept other numeric sequences,\n"
-" such as tuples, lists."
-"\n\n"
-"Submodules:\n"
-"\n"
-".. toctree::\n"
-" :maxdepth: 1\n"
-"\n"
-" mathutils.geometry.rst\n"
-" mathutils.bvhtree.rst\n"
-" mathutils.kdtree.rst\n"
-" mathutils.interpolate.rst\n"
-" mathutils.noise.rst\n"
-"\n"
-"The :mod:`mathutils` module provides the following classes:\n"
-"\n"
-"- :class:`Color`,\n"
-"- :class:`Euler`,\n"
-"- :class:`Matrix`,\n"
-"- :class:`Quaternion`,\n"
-"- :class:`Vector`,\n"
-);
+PyDoc_STRVAR(
+ M_Mathutils_doc,
+ "This module provides access to math operations.\n"
+ "\n"
+ ".. note::\n"
+ "\n"
+ " Classes, methods and attributes that accept vectors also accept other numeric sequences,\n"
+ " such as tuples, lists."
+ "\n\n"
+ "Submodules:\n"
+ "\n"
+ ".. toctree::\n"
+ " :maxdepth: 1\n"
+ "\n"
+ " mathutils.geometry.rst\n"
+ " mathutils.bvhtree.rst\n"
+ " mathutils.kdtree.rst\n"
+ " mathutils.interpolate.rst\n"
+ " mathutils.noise.rst\n"
+ "\n"
+ "The :mod:`mathutils` module provides the following classes:\n"
+ "\n"
+ "- :class:`Color`,\n"
+ "- :class:`Euler`,\n"
+ "- :class:`Matrix`,\n"
+ "- :class:`Quaternion`,\n"
+ "- :class:`Vector`,\n");
static int mathutils_array_parse_fast(float *array,
int size,
PyObject *value_fast,
const char *error_prefix)
{
- PyObject *item;
- PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
-
- int i;
-
- i = size;
- do {
- i--;
- if (((array[i] = PyFloat_AsDouble((item = value_fast_items[i]))) == -1.0f) &&
- PyErr_Occurred())
- {
- PyErr_Format(PyExc_TypeError,
- "%.200s: sequence index %d expected a number, "
- "found '%.200s' type, ",
- error_prefix, i, Py_TYPE(item)->tp_name);
- size = -1;
- break;
- }
- } while (i);
-
- return size;
+ PyObject *item;
+ PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
+
+ int i;
+
+ i = size;
+ do {
+ i--;
+ if (((array[i] = PyFloat_AsDouble((item = value_fast_items[i]))) == -1.0f) &&
+ PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: sequence index %d expected a number, "
+ "found '%.200s' type, ",
+ error_prefix,
+ i,
+ Py_TYPE(item)->tp_name);
+ size = -1;
+ break;
+ }
+ } while (i);
+
+ return size;
}
/**
@@ -93,271 +94,289 @@ static int mathutils_array_parse_fast(float *array,
*/
Py_hash_t mathutils_array_hash(const float *array, size_t array_len)
{
- int i;
- Py_uhash_t x; /* Unsigned for defined overflow behavior. */
- Py_hash_t y;
- Py_uhash_t mult;
- Py_ssize_t len;
-
- mult = _PyHASH_MULTIPLIER;
- len = array_len;
- x = 0x345678UL;
- i = 0;
- while (--len >= 0) {
- y = _Py_HashDouble((double)(array[i++]));
- if (y == -1) {
- return -1;
- }
- x = (x ^ y) * mult;
- /* the cast might truncate len; that doesn't change hash stability */
- mult += (Py_hash_t)(82520UL + len + len);
- }
- x += 97531UL;
- if (x == (Py_uhash_t)-1) {
- x = -2;
- }
- return x;
+ int i;
+ Py_uhash_t x; /* Unsigned for defined overflow behavior. */
+ Py_hash_t y;
+ Py_uhash_t mult;
+ Py_ssize_t len;
+
+ mult = _PyHASH_MULTIPLIER;
+ len = array_len;
+ x = 0x345678UL;
+ i = 0;
+ while (--len >= 0) {
+ y = _Py_HashDouble((double)(array[i++]));
+ if (y == -1) {
+ return -1;
+ }
+ x = (x ^ y) * mult;
+ /* the cast might truncate len; that doesn't change hash stability */
+ mult += (Py_hash_t)(82520UL + len + len);
+ }
+ x += 97531UL;
+ if (x == (Py_uhash_t)-1) {
+ x = -2;
+ }
+ return x;
}
/* helper function 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)
+int mathutils_array_parse(
+ float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
{
- const unsigned int flag = array_max;
- int size;
+ const unsigned int flag = array_max;
+ int size;
- array_max &= ~MU_ARRAY_FLAGS;
+ array_max &= ~MU_ARRAY_FLAGS;
#if 1 /* approx 6x speedup for mathutils types */
- if ((size = VectorObject_Check(value) ? ((VectorObject *)value)->size : 0) ||
- (size = EulerObject_Check(value) ? 3 : 0) ||
- (size = QuaternionObject_Check(value) ? 4 : 0) ||
- (size = ColorObject_Check(value) ? 3 : 0))
- {
- if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
- return -1;
- }
-
- if (flag & MU_ARRAY_SPILL) {
- CLAMP_MAX(size, array_max);
- }
-
- 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);
- }
- return -1;
- }
-
- memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
- }
- else
+ if ((size = VectorObject_Check(value) ? ((VectorObject *)value)->size : 0) ||
+ (size = EulerObject_Check(value) ? 3 : 0) ||
+ (size = QuaternionObject_Check(value) ? 4 : 0) ||
+ (size = ColorObject_Check(value) ? 3 : 0)) {
+ if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
+ return -1;
+ }
+
+ if (flag & MU_ARRAY_SPILL) {
+ CLAMP_MAX(size, array_max);
+ }
+
+ 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);
+ }
+ return -1;
+ }
+
+ memcpy(array, ((BaseMathObject *)value)->data, size * sizeof(float));
+ }
+ else
#endif
- {
- PyObject *value_fast = NULL;
-
- /* 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 (flag & MU_ARRAY_SPILL) {
- CLAMP_MAX(size, array_max);
- }
-
- 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;
- }
-
- size = mathutils_array_parse_fast(array, size, value_fast, error_prefix);
- Py_DECREF(value_fast);
- }
-
- if (size != -1) {
- if (flag & MU_ARRAY_ZERO) {
- int size_left = array_max - size;
- if (size_left) {
- memset(&array[size], 0, sizeof(float) * size_left);
- }
- }
- }
-
- return size;
+ {
+ PyObject *value_fast = NULL;
+
+ /* 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 (flag & MU_ARRAY_SPILL) {
+ CLAMP_MAX(size, array_max);
+ }
+
+ 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;
+ }
+
+ size = mathutils_array_parse_fast(array, size, value_fast, error_prefix);
+ Py_DECREF(value_fast);
+ }
+
+ if (size != -1) {
+ if (flag & MU_ARRAY_ZERO) {
+ int size_left = array_max - size;
+ if (size_left) {
+ memset(&array[size], 0, sizeof(float) * size_left);
+ }
+ }
+ }
+
+ return size;
}
/* on error, -1 is returned and no allocation is made */
-int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix)
+int mathutils_array_parse_alloc(float **array,
+ int array_min,
+ PyObject *value,
+ const char *error_prefix)
{
- int size;
+ int size;
#if 1 /* approx 6x speedup for mathutils types */
- if ((size = VectorObject_Check(value) ? ((VectorObject *)value)->size : 0) ||
- (size = EulerObject_Check(value) ? 3 : 0) ||
- (size = QuaternionObject_Check(value) ? 4 : 0) ||
- (size = ColorObject_Check(value) ? 3 : 0))
- {
- if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
- return -1;
- }
-
- if (size < array_min) {
- PyErr_Format(PyExc_ValueError,
- "%.200s: sequence size is %d, expected > %d",
- error_prefix, size, array_min);
- return -1;
- }
-
- *array = PyMem_Malloc(size * sizeof(float));
- memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
- return size;
- }
- else
+ if ((size = VectorObject_Check(value) ? ((VectorObject *)value)->size : 0) ||
+ (size = EulerObject_Check(value) ? 3 : 0) ||
+ (size = QuaternionObject_Check(value) ? 4 : 0) ||
+ (size = ColorObject_Check(value) ? 3 : 0)) {
+ if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
+ return -1;
+ }
+
+ if (size < array_min) {
+ PyErr_Format(PyExc_ValueError,
+ "%.200s: sequence size is %d, expected > %d",
+ error_prefix,
+ size,
+ array_min);
+ return -1;
+ }
+
+ *array = PyMem_Malloc(size * sizeof(float));
+ memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
+ return size;
+ }
+ else
#endif
- {
- PyObject *value_fast = NULL;
- // *array = NULL;
- int ret;
-
- /* 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_min) {
- Py_DECREF(value_fast);
- PyErr_Format(PyExc_ValueError,
- "%.200s: sequence size is %d, expected > %d",
- error_prefix, size, array_min);
- return -1;
- }
-
- *array = PyMem_Malloc(size * sizeof(float));
-
- ret = mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
- Py_DECREF(value_fast);
-
- if (ret == -1) {
- PyMem_Free(*array);
- }
-
- return ret;
- }
+ {
+ PyObject *value_fast = NULL;
+ // *array = NULL;
+ int ret;
+
+ /* 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_min) {
+ Py_DECREF(value_fast);
+ PyErr_Format(PyExc_ValueError,
+ "%.200s: sequence size is %d, expected > %d",
+ error_prefix,
+ size,
+ array_min);
+ return -1;
+ }
+
+ *array = PyMem_Malloc(size * sizeof(float));
+
+ ret = mathutils_array_parse_fast(*array, size, value_fast, error_prefix);
+ Py_DECREF(value_fast);
+
+ if (ret == -1) {
+ PyMem_Free(*array);
+ }
+
+ return ret;
+ }
}
/* parse an array of vectors */
-int mathutils_array_parse_alloc_v(float **array, int array_dim, PyObject *value, const char *error_prefix)
+int mathutils_array_parse_alloc_v(float **array,
+ int array_dim,
+ PyObject *value,
+ const char *error_prefix)
{
- PyObject *value_fast;
- const int array_dim_flag = array_dim;
- int i, size;
+ PyObject *value_fast;
+ const int array_dim_flag = array_dim;
+ int i, size;
- /* non list/tuple cases */
- if (!(value_fast = PySequence_Fast(value, error_prefix))) {
- /* PySequence_Fast sets the error */
- return -1;
- }
+ /* 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);
+ size = PySequence_Fast_GET_SIZE(value_fast);
- if (size != 0) {
- PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
- float *fp;
+ if (size != 0) {
+ PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
+ float *fp;
- array_dim &= ~MU_ARRAY_FLAGS;
+ array_dim &= ~MU_ARRAY_FLAGS;
- fp = *array = PyMem_Malloc(size * array_dim * sizeof(float));
+ fp = *array = PyMem_Malloc(size * array_dim * sizeof(float));
- for (i = 0; i < size; i++, fp += array_dim) {
- PyObject *item = value_fast_items[i];
+ for (i = 0; i < size; i++, fp += array_dim) {
+ PyObject *item = value_fast_items[i];
- if (mathutils_array_parse(fp, array_dim, array_dim_flag, item, error_prefix) == -1) {
- PyMem_Free(*array);
- *array = NULL;
- size = -1;
- break;
- }
- }
- }
+ if (mathutils_array_parse(fp, array_dim, array_dim_flag, item, error_prefix) == -1) {
+ PyMem_Free(*array);
+ *array = NULL;
+ size = -1;
+ break;
+ }
+ }
+ }
- Py_DECREF(value_fast);
- return size;
+ Py_DECREF(value_fast);
+ return size;
}
int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
{
- if (EulerObject_Check(value)) {
- if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
- return -1;
- }
- else {
- eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
- return 0;
- }
- }
- else if (QuaternionObject_Check(value)) {
- if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
- return -1;
- }
- else {
- float tquat[4];
- normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
- quat_to_mat3(rmat, tquat);
- return 0;
- }
- }
- else if (MatrixObject_Check(value)) {
- if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
- return -1;
- }
- else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
- PyErr_Format(PyExc_ValueError,
- "%.200s: matrix must have minimum 3x3 dimensions",
- error_prefix);
- return -1;
- }
- else {
- matrix_as_3x3(rmat, (MatrixObject *)value);
- normalize_m3(rmat);
- return 0;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "%.200s: expected a Euler, Quaternion or Matrix type, "
- "found %.200s", error_prefix, Py_TYPE(value)->tp_name);
- return -1;
- }
+ if (EulerObject_Check(value)) {
+ if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
+ return -1;
+ }
+ else {
+ eulO_to_mat3(rmat, ((EulerObject *)value)->eul, ((EulerObject *)value)->order);
+ return 0;
+ }
+ }
+ else if (QuaternionObject_Check(value)) {
+ if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
+ return -1;
+ }
+ else {
+ float tquat[4];
+ normalize_qt_qt(tquat, ((QuaternionObject *)value)->quat);
+ quat_to_mat3(rmat, tquat);
+ return 0;
+ }
+ }
+ else if (MatrixObject_Check(value)) {
+ if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
+ return -1;
+ }
+ else if (((MatrixObject *)value)->num_row < 3 || ((MatrixObject *)value)->num_col < 3) {
+ PyErr_Format(
+ PyExc_ValueError, "%.200s: matrix must have minimum 3x3 dimensions", error_prefix);
+ return -1;
+ }
+ else {
+ matrix_as_3x3(rmat, (MatrixObject *)value);
+ normalize_m3(rmat);
+ return 0;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s: expected a Euler, Quaternion or Matrix type, "
+ "found %.200s",
+ error_prefix,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
}
-
/* ----------------------------------MATRIX FUNCTIONS-------------------- */
-
/* Utility functions */
/* LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon */
@@ -374,45 +393,45 @@ int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error
int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
{
- /* solid, fast routine across all platforms
- * with constant time behavior */
- int ai = *(int *)(&af);
- int bi = *(int *)(&bf);
- int test = SIGNMASK(ai ^ bi);
- int diff, v1, v2;
-
- assert((0 == test) || (0xFFFFFFFF == test));
- diff = (ai ^ (test & 0x7fffffff)) - bi;
- v1 = maxDiff + diff;
- v2 = maxDiff - diff;
- return (v1 | v2) >= 0;
+ /* solid, fast routine across all platforms
+ * with constant time behavior */
+ int ai = *(int *)(&af);
+ int bi = *(int *)(&bf);
+ int test = SIGNMASK(ai ^ bi);
+ int diff, v1, v2;
+
+ assert((0 == test) || (0xFFFFFFFF == test));
+ diff = (ai ^ (test & 0x7fffffff)) - bi;
+ v1 = maxDiff + diff;
+ v2 = maxDiff - diff;
+ return (v1 | v2) >= 0;
}
/*---------------------- EXPP_VectorsAreEqual -------------------------
* Builds on EXPP_FloatsAreEqual to test vectors */
int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int floatSteps)
{
- int x;
- for (x = 0; x < size; x++) {
- if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0) {
- return 0;
- }
- }
- return 1;
+ int x;
+ for (x = 0; x < size; x++) {
+ if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0) {
+ return 0;
+ }
+ }
+ return 1;
}
#ifndef MATH_STANDALONE
/* dynstr as python string utility functions, frees 'ds'! */
PyObject *mathutils_dynstr_to_py(struct DynStr *ds)
{
- const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
- char *ds_buf = PyMem_Malloc(ds_len + 1);
- PyObject *ret;
- BLI_dynstr_get_cstring_ex(ds, ds_buf);
- BLI_dynstr_free(ds);
- ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
- PyMem_Free(ds_buf);
- return ret;
+ const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
+ char *ds_buf = PyMem_Malloc(ds_len + 1);
+ PyObject *ret;
+ BLI_dynstr_get_cstring_ex(ds, ds_buf);
+ BLI_dynstr_free(ds);
+ ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
+ PyMem_Free(ds_buf);
+ return ret;
}
#endif
@@ -424,183 +443,174 @@ static Mathutils_Callback *mathutils_callbacks[MATHUTILS_TOT_CB] = {NULL};
unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb)
{
- unsigned char i;
+ unsigned char i;
- /* find the first free slot */
- for (i = 0; mathutils_callbacks[i]; i++) {
- if (mathutils_callbacks[i] == cb) {
- /* already registered? */
- return i;
- }
- }
+ /* find the first free slot */
+ for (i = 0; mathutils_callbacks[i]; i++) {
+ if (mathutils_callbacks[i] == cb) {
+ /* already registered? */
+ return i;
+ }
+ }
- BLI_assert(i + 1 < MATHUTILS_TOT_CB);
+ BLI_assert(i + 1 < MATHUTILS_TOT_CB);
- mathutils_callbacks[i] = cb;
- return i;
+ mathutils_callbacks[i] = cb;
+ return i;
}
/* use macros to check for NULL */
int _BaseMathObject_ReadCallback(BaseMathObject *self)
{
- Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
- if (LIKELY(cb->get(self, self->cb_subtype) != -1)) {
- return 0;
- }
-
- if (!PyErr_Occurred()) {
- PyErr_Format(PyExc_RuntimeError,
- "%s read, user has become invalid",
- Py_TYPE(self)->tp_name);
- }
- return -1;
+ Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
+ if (LIKELY(cb->get(self, self->cb_subtype) != -1)) {
+ return 0;
+ }
+
+ if (!PyErr_Occurred()) {
+ PyErr_Format(PyExc_RuntimeError, "%s read, user has become invalid", Py_TYPE(self)->tp_name);
+ }
+ return -1;
}
int _BaseMathObject_WriteCallback(BaseMathObject *self)
{
- Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
- if (LIKELY(cb->set(self, self->cb_subtype) != -1)) {
- return 0;
- }
-
- if (!PyErr_Occurred()) {
- PyErr_Format(PyExc_RuntimeError,
- "%s write, user has become invalid",
- Py_TYPE(self)->tp_name);
- }
- return -1;
+ Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
+ if (LIKELY(cb->set(self, self->cb_subtype) != -1)) {
+ return 0;
+ }
+
+ if (!PyErr_Occurred()) {
+ PyErr_Format(PyExc_RuntimeError, "%s write, user has become invalid", Py_TYPE(self)->tp_name);
+ }
+ return -1;
}
int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
{
- Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
- if (LIKELY(cb->get_index(self, self->cb_subtype, index) != -1)) {
- return 0;
- }
-
- if (!PyErr_Occurred()) {
- PyErr_Format(PyExc_RuntimeError,
- "%s read index, user has become invalid",
- Py_TYPE(self)->tp_name);
- }
- return -1;
+ Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
+ if (LIKELY(cb->get_index(self, self->cb_subtype, index) != -1)) {
+ return 0;
+ }
+
+ if (!PyErr_Occurred()) {
+ PyErr_Format(
+ PyExc_RuntimeError, "%s read index, user has become invalid", Py_TYPE(self)->tp_name);
+ }
+ return -1;
}
int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
{
- Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
- if (LIKELY(cb->set_index(self, self->cb_subtype, index) != -1)) {
- return 0;
- }
-
- if (!PyErr_Occurred()) {
- PyErr_Format(PyExc_RuntimeError,
- "%s write index, user has become invalid",
- Py_TYPE(self)->tp_name);
- }
- return -1;
+ Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
+ if (LIKELY(cb->set_index(self, self->cb_subtype, index) != -1)) {
+ return 0;
+ }
+
+ if (!PyErr_Occurred()) {
+ PyErr_Format(
+ PyExc_RuntimeError, "%s write index, user has become invalid", Py_TYPE(self)->tp_name);
+ }
+ return -1;
}
void _BaseMathObject_RaiseFrozenExc(const BaseMathObject *self)
{
- PyErr_Format(PyExc_TypeError,
- "%s is frozen (immutable)",
- Py_TYPE(self)->tp_name);
+ PyErr_Format(PyExc_TypeError, "%s is frozen (immutable)", Py_TYPE(self)->tp_name);
}
void _BaseMathObject_RaiseNotFrozenExc(const BaseMathObject *self)
{
- PyErr_Format(PyExc_TypeError,
- "%s is not frozen (mutable), call freeze first",
- Py_TYPE(self)->tp_name);
+ PyErr_Format(
+ PyExc_TypeError, "%s is not frozen (mutable), call freeze first", Py_TYPE(self)->tp_name);
}
/* BaseMathObject generic functions for all mathutils types */
char BaseMathObject_owner_doc[] = "The item this is wrapping or None (read-only).";
PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *UNUSED(closure))
{
- PyObject *ret = self->cb_user ? self->cb_user : Py_None;
- return Py_INCREF_RET(ret);
+ PyObject *ret = self->cb_user ? self->cb_user : Py_None;
+ return Py_INCREF_RET(ret);
}
-char BaseMathObject_is_wrapped_doc[] = "True when this object wraps external data (read-only).\n\n:type: boolean";
+char BaseMathObject_is_wrapped_doc[] =
+ "True when this object wraps external data (read-only).\n\n:type: boolean";
PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *UNUSED(closure))
{
- return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_WRAP) != 0);
+ return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_WRAP) != 0);
}
-char BaseMathObject_is_frozen_doc[] = "True when this object has been frozen (read-only).\n\n:type: boolean";
+char BaseMathObject_is_frozen_doc[] =
+ "True when this object has been frozen (read-only).\n\n:type: boolean";
PyObject *BaseMathObject_is_frozen_get(BaseMathObject *self, void *UNUSED(closure))
{
- return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_FROZEN) != 0);
+ return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_FROZEN) != 0);
}
char BaseMathObject_freeze_doc[] =
-".. function:: freeze()\n"
-"\n"
-" Make this object immutable.\n"
-"\n"
-" After this the object can be hashed, used in dictionaries & sets.\n"
-"\n"
-" :return: An instance of this object.\n"
-;
+ ".. function:: freeze()\n"
+ "\n"
+ " Make this object immutable.\n"
+ "\n"
+ " After this the object can be hashed, used in dictionaries & sets.\n"
+ "\n"
+ " :return: An instance of this object.\n";
PyObject *BaseMathObject_freeze(BaseMathObject *self)
{
- if ((self->flag & BASE_MATH_FLAG_IS_WRAP) || (self->cb_user != NULL)) {
- PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped/owned data");
- return NULL;
- }
+ if ((self->flag & BASE_MATH_FLAG_IS_WRAP) || (self->cb_user != NULL)) {
+ PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped/owned data");
+ return NULL;
+ }
- self->flag |= BASE_MATH_FLAG_IS_FROZEN;
+ self->flag |= BASE_MATH_FLAG_IS_FROZEN;
- return Py_INCREF_RET((PyObject *)self);
+ return Py_INCREF_RET((PyObject *)self);
}
int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->cb_user);
- return 0;
+ Py_VISIT(self->cb_user);
+ return 0;
}
int BaseMathObject_clear(BaseMathObject *self)
{
- Py_CLEAR(self->cb_user);
- return 0;
+ Py_CLEAR(self->cb_user);
+ return 0;
}
void BaseMathObject_dealloc(BaseMathObject *self)
{
- /* only free non wrapped */
- if ((self->flag & BASE_MATH_FLAG_IS_WRAP) == 0) {
- PyMem_Free(self->data);
- }
+ /* only free non wrapped */
+ if ((self->flag & BASE_MATH_FLAG_IS_WRAP) == 0) {
+ PyMem_Free(self->data);
+ }
- if (self->cb_user) {
- PyObject_GC_UnTrack(self);
- BaseMathObject_clear(self);
- }
+ if (self->cb_user) {
+ PyObject_GC_UnTrack(self);
+ BaseMathObject_clear(self);
+ }
- Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
+ Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
}
/*----------------------------MODULE INIT-------------------------*/
static struct PyMethodDef M_Mathutils_methods[] = {
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_Mathutils_module_def = {
- PyModuleDef_HEAD_INIT,
- "mathutils", /* m_name */
- M_Mathutils_doc, /* m_doc */
- 0, /* m_size */
- M_Mathutils_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils", /* m_name */
+ M_Mathutils_doc, /* m_doc */
+ 0, /* m_size */
+ M_Mathutils_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
-
/* submodules only */
#include "mathutils_geometry.h"
#include "mathutils_interpolate.h"
@@ -612,68 +622,69 @@ static struct PyModuleDef M_Mathutils_module_def = {
PyMODINIT_FUNC PyInit_mathutils(void)
{
- PyObject *mod;
- PyObject *submodule;
- PyObject *sys_modules = PyImport_GetModuleDict();
-
- if (PyType_Ready(&vector_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&matrix_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&matrix_access_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&euler_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&quaternion_Type) < 0) {
- return NULL;
- }
- if (PyType_Ready(&color_Type) < 0) {
- return NULL;
- }
-
- mod = PyModule_Create(&M_Mathutils_module_def);
-
- /* each type has its own new() function */
- PyModule_AddObject(mod, vector_Type.tp_name, (PyObject *)&vector_Type);
- PyModule_AddObject(mod, matrix_Type.tp_name, (PyObject *)&matrix_Type);
- PyModule_AddObject(mod, euler_Type.tp_name, (PyObject *)&euler_Type);
- PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
- PyModule_AddObject(mod, color_Type.tp_name, (PyObject *)&color_Type);
-
- /* submodule */
- PyModule_AddObject(mod, "geometry", (submodule = PyInit_mathutils_geometry()));
- /* XXX, python doesn't do imports with this usefully yet
- * 'from mathutils.geometry import PolyFill'
- * ...fails without this. */
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
-
- PyModule_AddObject(mod, "interpolate", (submodule = PyInit_mathutils_interpolate()));
- /* XXX, python doesnt do imports with this usefully yet
- * 'from mathutils.geometry import PolyFill'
- * ...fails without this. */
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ PyObject *mod;
+ PyObject *submodule;
+ PyObject *sys_modules = PyImport_GetModuleDict();
+
+ if (PyType_Ready(&vector_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&matrix_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&matrix_access_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&euler_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&quaternion_Type) < 0) {
+ return NULL;
+ }
+ if (PyType_Ready(&color_Type) < 0) {
+ return NULL;
+ }
+
+ mod = PyModule_Create(&M_Mathutils_module_def);
+
+ /* each type has its own new() function */
+ PyModule_AddObject(mod, vector_Type.tp_name, (PyObject *)&vector_Type);
+ PyModule_AddObject(mod, matrix_Type.tp_name, (PyObject *)&matrix_Type);
+ PyModule_AddObject(mod, euler_Type.tp_name, (PyObject *)&euler_Type);
+ PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
+ PyModule_AddObject(mod, color_Type.tp_name, (PyObject *)&color_Type);
+
+ /* submodule */
+ PyModule_AddObject(mod, "geometry", (submodule = PyInit_mathutils_geometry()));
+ /* XXX, python doesn't do imports with this usefully yet
+ * 'from mathutils.geometry import PolyFill'
+ * ...fails without this. */
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+
+ PyModule_AddObject(mod, "interpolate", (submodule = PyInit_mathutils_interpolate()));
+ /* XXX, python doesnt do imports with this usefully yet
+ * 'from mathutils.geometry import PolyFill'
+ * ...fails without this. */
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
#ifndef MATH_STANDALONE
- /* Noise submodule */
- PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ /* Noise submodule */
+ PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- /* BVHTree submodule */
- PyModule_AddObject(mod, "bvhtree", (submodule = PyInit_mathutils_bvhtree()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ /* BVHTree submodule */
+ PyModule_AddObject(mod, "bvhtree", (submodule = PyInit_mathutils_bvhtree()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
- /* KDTree_3d submodule */
- PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree()));
- PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
+ /* KDTree_3d submodule */
+ PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree()));
+ PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule);
#endif
- mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
- mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
- mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_translation_cb);
+ mathutils_matrix_row_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_row_cb);
+ mathutils_matrix_col_cb_index = Mathutils_RegisterCallback(&mathutils_matrix_col_cb);
+ mathutils_matrix_translation_cb_index = Mathutils_RegisterCallback(
+ &mathutils_matrix_translation_cb);
- return mod;
+ return mod;
}
diff --git a/source/blender/python/mathutils/mathutils.h b/source/blender/python/mathutils/mathutils.h
index bc5490a3acd..4ec2c869499 100644
--- a/source/blender/python/mathutils/mathutils.h
+++ b/source/blender/python/mathutils/mathutils.h
@@ -32,37 +32,39 @@ extern char BaseMathObject_is_frozen_doc[];
extern char BaseMathObject_owner_doc[];
#define BASE_MATH_NEW(struct_name, root_type, base_type) \
- (struct_name *)((base_type ? (base_type)->tp_alloc(base_type, 0) : _PyObject_GC_New(&(root_type))));
-
+ (struct_name *)((base_type ? (base_type)->tp_alloc(base_type, 0) : \
+ _PyObject_GC_New(&(root_type))));
/** BaseMathObject.flag */
enum {
- /**
- * Do not own the memory used in this vector,
- * \note This is error prone if the memory may be freed while this vector is in use.
- * Prefer using callbacks where possible, see: #Mathutils_RegisterCallback
- */
- BASE_MATH_FLAG_IS_WRAP = (1 << 0),
- /**
- * Prevent changes to the vector so it can be used as a set or dictionary key for example.
- * (typical use cases for tuple).
- */
- BASE_MATH_FLAG_IS_FROZEN = (1 << 1),
+ /**
+ * Do not own the memory used in this vector,
+ * \note This is error prone if the memory may be freed while this vector is in use.
+ * Prefer using callbacks where possible, see: #Mathutils_RegisterCallback
+ */
+ BASE_MATH_FLAG_IS_WRAP = (1 << 0),
+ /**
+ * Prevent changes to the vector so it can be used as a set or dictionary key for example.
+ * (typical use cases for tuple).
+ */
+ BASE_MATH_FLAG_IS_FROZEN = (1 << 1),
};
#define BASE_MATH_FLAG_DEFAULT 0
-#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, etc */ \
- unsigned char cb_subtype; /* subtype: location, rotation... \
- * to avoid defining many new functions for every attribute of the same type */ \
- unsigned char flag /* wrapped data type? */ \
+#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, etc */ \
+ unsigned char \
+ cb_subtype; /* subtype: location, rotation... \
+ * to avoid defining many new functions for every attribute of the same type */ \
+ unsigned char flag /* wrapped data type? */
typedef struct {
- BASE_MATH_MEMBERS(data);
+ BASE_MATH_MEMBERS(data);
} BaseMathObject;
/* types */
@@ -73,8 +75,7 @@ typedef struct {
#include "mathutils_Color.h"
/* avoid checking all types */
-#define BaseMathObject_CheckExact(v) \
- (Py_TYPE(v)->tp_dealloc == (destructor)BaseMathObject_dealloc)
+#define BaseMathObject_CheckExact(v) (Py_TYPE(v)->tp_dealloc == (destructor)BaseMathObject_dealloc)
PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *);
PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *);
@@ -94,18 +95,23 @@ int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int flo
typedef struct Mathutils_Callback Mathutils_Callback;
-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 its 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 */
+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 its 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 {
- BaseMathCheckFunc check;
- BaseMathGetFunc get;
- BaseMathSetFunc set;
- BaseMathGetIndexFunc get_index;
- BaseMathSetIndexFunc set_index;
+ BaseMathCheckFunc check;
+ BaseMathGetFunc get;
+ BaseMathSetFunc set;
+ BaseMathGetIndexFunc get_index;
+ BaseMathSetIndexFunc set_index;
};
unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb);
@@ -120,44 +126,55 @@ void _BaseMathObject_RaiseNotFrozenExc(const BaseMathObject *self);
/* since this is called so often avoid where possible */
#define BaseMath_ReadCallback(_self) \
- (((_self)->cb_user ? _BaseMathObject_ReadCallback((BaseMathObject *)_self) : 0))
+ (((_self)->cb_user ? _BaseMathObject_ReadCallback((BaseMathObject *)_self) : 0))
#define BaseMath_WriteCallback(_self) \
- (((_self)->cb_user ?_BaseMathObject_WriteCallback((BaseMathObject *)_self) : 0))
+ (((_self)->cb_user ? _BaseMathObject_WriteCallback((BaseMathObject *)_self) : 0))
#define BaseMath_ReadIndexCallback(_self, _index) \
- (((_self)->cb_user ? _BaseMathObject_ReadIndexCallback((BaseMathObject *)_self, _index) : 0))
+ (((_self)->cb_user ? _BaseMathObject_ReadIndexCallback((BaseMathObject *)_self, _index) : 0))
#define BaseMath_WriteIndexCallback(_self, _index) \
- (((_self)->cb_user ? _BaseMathObject_WriteIndexCallback((BaseMathObject *)_self, _index) : 0))
+ (((_self)->cb_user ? _BaseMathObject_WriteIndexCallback((BaseMathObject *)_self, _index) : 0))
/* support BASE_MATH_FLAG_IS_FROZEN */
#define BaseMath_ReadCallback_ForWrite(_self) \
- (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
- (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : (BaseMath_ReadCallback(_self)))
+ (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
+ (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : \
+ (BaseMath_ReadCallback(_self)))
#define BaseMath_ReadIndexCallback_ForWrite(_self, _index) \
- (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
- (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : (BaseMath_ReadIndexCallback(_self, _index)))
+ (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
+ (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : \
+ (BaseMath_ReadIndexCallback(_self, _index)))
#define BaseMath_Prepare_ForWrite(_self) \
- (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
- (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : 0)
+ (UNLIKELY((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) ? \
+ (_BaseMathObject_RaiseFrozenExc((BaseMathObject *)_self), -1) : \
+ 0)
#define BaseMathObject_Prepare_ForHash(_self) \
- (UNLIKELY(((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) == 0) ? \
- (_BaseMathObject_RaiseNotFrozenExc((BaseMathObject *)_self), -1) : 0)
+ (UNLIKELY(((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) == 0) ? \
+ (_BaseMathObject_RaiseNotFrozenExc((BaseMathObject *)_self), -1) : \
+ 0)
/* utility func */
-int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix);
-int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, const char *error_prefix);
-int mathutils_array_parse_alloc_v(float **array, int array_dim, PyObject *value, const char *error_prefix);
+int mathutils_array_parse(
+ float *array, int array_min, int array_max, PyObject *value, const char *error_prefix);
+int mathutils_array_parse_alloc(float **array,
+ int array_min,
+ PyObject *value,
+ const char *error_prefix);
+int mathutils_array_parse_alloc_v(float **array,
+ int array_dim,
+ PyObject *value,
+ const char *error_prefix);
int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix);
Py_hash_t mathutils_array_hash(const float *float_array, size_t array_len);
/* zero remaining unused elements of the array */
-#define MU_ARRAY_ZERO (1u << 30)
+#define MU_ARRAY_ZERO (1u << 30)
/* ignore larger py sequences than requested (just use first elements),
* handy when using 3d vectors as 2d */
-#define MU_ARRAY_SPILL (1u << 31)
+#define MU_ARRAY_SPILL (1u << 31)
#define MU_ARRAY_FLAGS (MU_ARRAY_ZERO | MU_ARRAY_SPILL)
diff --git a/source/blender/python/mathutils/mathutils_Color.c b/source/blender/python/mathutils/mathutils_Color.c
index 98e85782989..4e21a8e0389 100644
--- a/source/blender/python/mathutils/mathutils_Color.c
+++ b/source/blender/python/mathutils/mathutils_Color.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -39,30 +38,32 @@
/* makes a new color for you to play with */
static PyObject *Color_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- float col[3] = {0.0f, 0.0f, 0.0f};
-
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "mathutils.Color(): "
- "takes no keyword args");
- return NULL;
- }
-
- 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 than a single arg given");
- return NULL;
- }
- return Color_CreatePyObject(col, type);
+ float col[3] = {0.0f, 0.0f, 0.0f};
+
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError,
+ "mathutils.Color(): "
+ "takes no keyword args");
+ return NULL;
+ }
+
+ 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 than a single arg given");
+ return NULL;
+ }
+ return Color_CreatePyObject(col, type);
}
/* -----------------------------METHODS---------------------------- */
@@ -70,50 +71,49 @@ static PyObject *Color_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
/* 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;
+ 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;
}
PyDoc_STRVAR(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\n"
-" no reference to the original data.\n"
-);
+ ".. 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\n"
+ " no reference to the original data.\n");
static PyObject *Color_copy(ColorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Color_CreatePyObject(self->col, Py_TYPE(self));
+ return Color_CreatePyObject(self->col, Py_TYPE(self));
}
static PyObject *Color_deepcopy(ColorObject *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return Color_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return Color_copy(self);
}
/* ----------------------------print object (internal)-------------- */
@@ -121,35 +121,35 @@ static PyObject *Color_deepcopy(ColorObject *self, PyObject *args)
static PyObject *Color_repr(ColorObject *self)
{
- PyObject *ret, *tuple;
+ PyObject *ret, *tuple;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- tuple = Color_ToTupleExt(self, -1);
+ tuple = Color_ToTupleExt(self, -1);
- ret = PyUnicode_FromFormat("Color(%R)", tuple);
+ ret = PyUnicode_FromFormat("Color(%R)", tuple);
- Py_DECREF(tuple);
- return ret;
+ Py_DECREF(tuple);
+ return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Color_str(ColorObject *self)
{
- DynStr *ds;
+ DynStr *ds;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- ds = BLI_dynstr_new();
+ ds = BLI_dynstr_new();
- BLI_dynstr_appendf(ds, "<Color (r=%.4f, g=%.4f, b=%.4f)>",
- self->col[0], self->col[1], self->col[2]);
+ BLI_dynstr_appendf(
+ ds, "<Color (r=%.4f, g=%.4f, b=%.4f)>", self->col[0], self->col[1], self->col[2]);
- return mathutils_dynstr_to_py(ds); /* frees ds */
+ return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
@@ -157,53 +157,53 @@ static PyObject *Color_str(ColorObject *self)
/* returns -1 exception, 0 false, 1 true */
static PyObject *Color_richcmpr(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
-
- if (ColorObject_Check(a) && ColorObject_Check(b)) {
- ColorObject *colA = (ColorObject *)a;
- ColorObject *colB = (ColorObject *)b;
-
- if (BaseMath_ReadCallback(colA) == -1 || BaseMath_ReadCallback(colB) == -1) {
- return NULL;
- }
-
- ok = EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1) ? 0 : -1;
- }
-
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
-
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- return Py_INCREF_RET(res);
+ PyObject *res;
+ int ok = -1; /* zero is true */
+
+ if (ColorObject_Check(a) && ColorObject_Check(b)) {
+ ColorObject *colA = (ColorObject *)a;
+ ColorObject *colB = (ColorObject *)b;
+
+ if (BaseMath_ReadCallback(colA) == -1 || BaseMath_ReadCallback(colB) == -1) {
+ return NULL;
+ }
+
+ ok = EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1) ? 0 : -1;
+ }
+
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
+
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ return Py_INCREF_RET(res);
}
static Py_hash_t Color_hash(ColorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- if (BaseMathObject_Prepare_ForHash(self) == -1) {
- return -1;
- }
+ if (BaseMathObject_Prepare_ForHash(self) == -1) {
+ return -1;
+ }
- return mathutils_array_hash(self->col, COLOR_SIZE);
+ return mathutils_array_hash(self->col, COLOR_SIZE);
}
/* ---------------------SEQUENCE PROTOCOLS------------------------ */
@@ -211,525 +211,523 @@ static Py_hash_t Color_hash(ColorObject *self)
/* sequence length */
static int Color_len(ColorObject *UNUSED(self))
{
- return COLOR_SIZE;
+ 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[item]: "
- "array index out of range");
- return NULL;
- }
-
- if (BaseMath_ReadIndexCallback(self, i) == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(self->col[i]);
-
+ if (i < 0) {
+ i = COLOR_SIZE - i;
+ }
+
+ if (i < 0 || i >= COLOR_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "color[item]: "
+ "array index out of range");
+ return NULL;
+ }
+
+ if (BaseMath_ReadIndexCallback(self, i) == -1) {
+ 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;
-
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
-
- f = PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError,
- "color[item] = x: "
- "assigned value not a number");
- return -1;
- }
-
- if (i < 0) {
- i = COLOR_SIZE - i;
- }
-
- if (i < 0 || i >= COLOR_SIZE) {
- PyErr_SetString(PyExc_IndexError, "color[item] = x: "
- "array assignment index out of range");
- return -1;
- }
-
- self->col[i] = f;
-
- if (BaseMath_WriteIndexCallback(self, i) == -1) {
- return -1;
- }
-
- return 0;
+ float f;
+
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ f = PyFloat_AsDouble(value);
+ if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError,
+ "color[item] = x: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ if (i < 0) {
+ i = COLOR_SIZE - i;
+ }
+
+ if (i < 0 || i >= COLOR_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "color[item] = x: "
+ "array assignment index out of range");
+ return -1;
+ }
+
+ self->col[i] = f;
+
+ if (BaseMath_WriteIndexCallback(self, i) == -1) {
+ return -1;
+ }
+
+ return 0;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (get) */
static PyObject *Color_slice(ColorObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- CLAMP(begin, 0, COLOR_SIZE);
- if (end < 0) {
- end = (COLOR_SIZE + 1) + end;
- }
- CLAMP(end, 0, COLOR_SIZE);
- begin = MIN2(begin, end);
-
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->col[count]));
- }
-
- return tuple;
+ PyObject *tuple;
+ int count;
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ CLAMP(begin, 0, COLOR_SIZE);
+ if (end < 0) {
+ end = (COLOR_SIZE + 1) + end;
+ }
+ CLAMP(end, 0, COLOR_SIZE);
+ begin = MIN2(begin, end);
+
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->col[count]));
+ }
+
+ return tuple;
}
/* ----------------------------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_ForWrite(self) == -1) {
- 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_ValueError,
- "color[begin:end] = []: "
- "size mismatch in slice assignment");
- return -1;
- }
-
- for (i = 0; i < COLOR_SIZE; i++) {
- self->col[begin + i] = col[i];
- }
-
- (void)BaseMath_WriteCallback(self);
- return 0;
+ int i, size;
+ float col[COLOR_SIZE];
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ 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_ValueError,
+ "color[begin:end] = []: "
+ "size mismatch in slice assignment");
+ return -1;
+ }
+
+ for (i = 0; i < COLOR_SIZE; i++) {
+ self->col[begin + i] = col[i];
+ }
+
+ (void)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(item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Color_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with color");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "color indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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(item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Color_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with color");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "color indices must be integers, not %.200s", Py_TYPE(item)->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(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_IndexError,
- "slice steps not supported with color");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "color indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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(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_IndexError, "slice steps not supported with color");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "color indices must be integers, not %.200s", Py_TYPE(item)->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 */
- NULL, /* sq_slice, deprecated */
- (ssizeobjargproc) Color_ass_item, /* sq_ass_item */
- NULL, /* sq_ass_slice, deprecated */
- (objobjproc) NULL, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)Color_len, /* sq_length */
+ (binaryfunc)NULL, /* sq_concat */
+ (ssizeargfunc)NULL, /* sq_repeat */
+ (ssizeargfunc)Color_item, /* sq_item */
+ NULL, /* sq_slice, deprecated */
+ (ssizeobjargproc)Color_ass_item, /* sq_ass_item */
+ 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,
+ (lenfunc)Color_len,
+ (binaryfunc)Color_subscript,
+ (objobjargproc)Color_ass_subscript,
};
/* numeric */
-
/* addition: obj + obj */
static PyObject *Color_add(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL, *color2 = NULL;
- float col[COLOR_SIZE];
-
- if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
- PyErr_Format(PyExc_TypeError,
- "Color addition: (%s + %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- color1 = (ColorObject *)v1;
- color2 = (ColorObject *)v2;
-
- if (BaseMath_ReadCallback(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
- return NULL;
- }
-
- add_vn_vnvn(col, color1->col, color2->col, COLOR_SIZE);
-
- return Color_CreatePyObject(col, Py_TYPE(v1));
+ ColorObject *color1 = NULL, *color2 = NULL;
+ float col[COLOR_SIZE];
+
+ if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Color addition: (%s + %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ color1 = (ColorObject *)v1;
+ color2 = (ColorObject *)v2;
+
+ if (BaseMath_ReadCallback(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
+ return NULL;
+ }
+
+ add_vn_vnvn(col, color1->col, color2->col, COLOR_SIZE);
+
+ return Color_CreatePyObject(col, Py_TYPE(v1));
}
/* addition in-place: obj += obj */
static PyObject *Color_iadd(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL, *color2 = NULL;
-
- if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
- PyErr_Format(PyExc_TypeError,
- "Color addition: (%s += %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- color1 = (ColorObject *)v1;
- color2 = (ColorObject *)v2;
-
- if (BaseMath_ReadCallback_ForWrite(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
- return NULL;
- }
-
- add_vn_vn(color1->col, color2->col, COLOR_SIZE);
-
- (void)BaseMath_WriteCallback(color1);
- Py_INCREF(v1);
- return v1;
+ ColorObject *color1 = NULL, *color2 = NULL;
+
+ if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Color addition: (%s += %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ color1 = (ColorObject *)v1;
+ color2 = (ColorObject *)v2;
+
+ if (BaseMath_ReadCallback_ForWrite(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
+ return NULL;
+ }
+
+ add_vn_vn(color1->col, color2->col, COLOR_SIZE);
+
+ (void)BaseMath_WriteCallback(color1);
+ Py_INCREF(v1);
+ return v1;
}
/* subtraction: obj - obj */
static PyObject *Color_sub(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL, *color2 = NULL;
- float col[COLOR_SIZE];
-
- if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
- PyErr_Format(PyExc_TypeError,
- "Color subtraction: (%s - %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- color1 = (ColorObject *)v1;
- color2 = (ColorObject *)v2;
-
- if (BaseMath_ReadCallback(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
- return NULL;
- }
-
- sub_vn_vnvn(col, color1->col, color2->col, COLOR_SIZE);
-
- return Color_CreatePyObject(col, Py_TYPE(v1));
+ ColorObject *color1 = NULL, *color2 = NULL;
+ float col[COLOR_SIZE];
+
+ if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Color subtraction: (%s - %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ color1 = (ColorObject *)v1;
+ color2 = (ColorObject *)v2;
+
+ if (BaseMath_ReadCallback(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
+ return NULL;
+ }
+
+ sub_vn_vnvn(col, color1->col, color2->col, COLOR_SIZE);
+
+ return Color_CreatePyObject(col, Py_TYPE(v1));
}
/* subtraction in-place: obj -= obj */
static PyObject *Color_isub(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL, *color2 = NULL;
-
- if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
- PyErr_Format(PyExc_TypeError,
- "Color subtraction: (%s -= %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- color1 = (ColorObject *)v1;
- color2 = (ColorObject *)v2;
-
- if (BaseMath_ReadCallback_ForWrite(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
- return NULL;
- }
-
- sub_vn_vn(color1->col, color2->col, COLOR_SIZE);
-
- (void)BaseMath_WriteCallback(color1);
- Py_INCREF(v1);
- return v1;
+ ColorObject *color1 = NULL, *color2 = NULL;
+
+ if (!ColorObject_Check(v1) || !ColorObject_Check(v2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Color subtraction: (%s -= %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ color1 = (ColorObject *)v1;
+ color2 = (ColorObject *)v2;
+
+ if (BaseMath_ReadCallback_ForWrite(color1) == -1 || BaseMath_ReadCallback(color2) == -1) {
+ return NULL;
+ }
+
+ sub_vn_vn(color1->col, color2->col, COLOR_SIZE);
+
+ (void)BaseMath_WriteCallback(color1);
+ Py_INCREF(v1);
+ return v1;
}
static PyObject *color_mul_float(ColorObject *color, const float scalar)
{
- float tcol[COLOR_SIZE];
- mul_vn_vn_fl(tcol, color->col, COLOR_SIZE, scalar);
- return Color_CreatePyObject(tcol, Py_TYPE(color));
+ float tcol[COLOR_SIZE];
+ mul_vn_vn_fl(tcol, color->col, COLOR_SIZE, scalar);
+ return Color_CreatePyObject(tcol, Py_TYPE(color));
}
-
static PyObject *Color_mul(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL, *color2 = NULL;
- float scalar;
-
- if (ColorObject_Check(v1)) {
- color1 = (ColorObject *)v1;
- if (BaseMath_ReadCallback(color1) == -1) {
- return NULL;
- }
- }
- if (ColorObject_Check(v2)) {
- color2 = (ColorObject *)v2;
- if (BaseMath_ReadCallback(color2) == -1) {
- return NULL;
- }
- }
-
-
- /* make sure v1 is always the vector */
- if (color1 && color2) {
- /* col * col, don't support yet! */
- }
- else if (color1) {
- if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR * FLOAT */
- return color_mul_float(color1, scalar);
- }
- }
- else if (color2) {
- if (((scalar = PyFloat_AsDouble(v1)) == -1.0f && PyErr_Occurred()) == 0) { /* FLOAT * COLOR */
- return color_mul_float(color2, scalar);
- }
- }
- else {
- BLI_assert(!"internal error");
- }
-
- PyErr_Format(PyExc_TypeError,
- "Color multiplication: not supported between "
- "'%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ ColorObject *color1 = NULL, *color2 = NULL;
+ float scalar;
+
+ if (ColorObject_Check(v1)) {
+ color1 = (ColorObject *)v1;
+ if (BaseMath_ReadCallback(color1) == -1) {
+ return NULL;
+ }
+ }
+ if (ColorObject_Check(v2)) {
+ color2 = (ColorObject *)v2;
+ if (BaseMath_ReadCallback(color2) == -1) {
+ return NULL;
+ }
+ }
+
+ /* make sure v1 is always the vector */
+ if (color1 && color2) {
+ /* col * col, don't support yet! */
+ }
+ else if (color1) {
+ if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR * FLOAT */
+ return color_mul_float(color1, scalar);
+ }
+ }
+ else if (color2) {
+ if (((scalar = PyFloat_AsDouble(v1)) == -1.0f && PyErr_Occurred()) == 0) { /* FLOAT * COLOR */
+ return color_mul_float(color2, scalar);
+ }
+ }
+ else {
+ BLI_assert(!"internal error");
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Color multiplication: not supported between "
+ "'%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
}
static PyObject *Color_div(PyObject *v1, PyObject *v2)
{
- ColorObject *color1 = NULL;
- float scalar;
-
- if (ColorObject_Check(v1)) {
- color1 = (ColorObject *)v1;
- if (BaseMath_ReadCallback(color1) == -1) {
- return NULL;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Color division not supported in this order");
- return NULL;
- }
-
- /* make sure v1 is always the vector */
- if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR * FLOAT */
- if (scalar == 0.0f) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "Color division: divide by zero error");
- return NULL;
- }
- return color_mul_float(color1, 1.0f / scalar);
- }
-
- PyErr_Format(PyExc_TypeError,
- "Color multiplication: not supported between "
- "'%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ ColorObject *color1 = NULL;
+ float scalar;
+
+ if (ColorObject_Check(v1)) {
+ color1 = (ColorObject *)v1;
+ if (BaseMath_ReadCallback(color1) == -1) {
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "Color division not supported in this order");
+ return NULL;
+ }
+
+ /* make sure v1 is always the vector */
+ if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR * FLOAT */
+ if (scalar == 0.0f) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "Color division: divide by zero error");
+ return NULL;
+ }
+ return color_mul_float(color1, 1.0f / scalar);
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Color multiplication: not supported between "
+ "'%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
}
/* multiplication in-place: obj *= obj */
static PyObject *Color_imul(PyObject *v1, PyObject *v2)
{
- ColorObject *color = (ColorObject *)v1;
- float scalar;
-
- if (BaseMath_ReadCallback_ForWrite(color) == -1) {
- return NULL;
- }
-
- /* only support color *= float */
- if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR *= FLOAT */
- mul_vn_fl(color->col, COLOR_SIZE, scalar);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Color multiplication: (%s *= %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(color);
- Py_INCREF(v1);
- return v1;
+ ColorObject *color = (ColorObject *)v1;
+ float scalar;
+
+ if (BaseMath_ReadCallback_ForWrite(color) == -1) {
+ return NULL;
+ }
+
+ /* only support color *= float */
+ if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR *= FLOAT */
+ mul_vn_fl(color->col, COLOR_SIZE, scalar);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Color multiplication: (%s *= %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(color);
+ Py_INCREF(v1);
+ return v1;
}
/* multiplication in-place: obj *= obj */
static PyObject *Color_idiv(PyObject *v1, PyObject *v2)
{
- ColorObject *color = (ColorObject *)v1;
- float scalar;
-
- if (BaseMath_ReadCallback_ForWrite(color) == -1) {
- return NULL;
- }
-
- /* only support color /= float */
- if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR /= FLOAT */
- if (scalar == 0.0f) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "Color division: divide by zero error");
- return NULL;
- }
-
- mul_vn_fl(color->col, COLOR_SIZE, 1.0f / scalar);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Color division: (%s /= %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(color);
- Py_INCREF(v1);
- return v1;
+ ColorObject *color = (ColorObject *)v1;
+ float scalar;
+
+ if (BaseMath_ReadCallback_ForWrite(color) == -1) {
+ return NULL;
+ }
+
+ /* only support color /= float */
+ if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* COLOR /= FLOAT */
+ if (scalar == 0.0f) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "Color division: divide by zero error");
+ return NULL;
+ }
+
+ mul_vn_fl(color->col, COLOR_SIZE, 1.0f / scalar);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Color division: (%s /= %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(color);
+ Py_INCREF(v1);
+ return v1;
}
/* -obj
* returns the negative of this object */
static PyObject *Color_neg(ColorObject *self)
{
- float tcol[COLOR_SIZE];
+ float tcol[COLOR_SIZE];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- negate_vn_vn(tcol, self->col, COLOR_SIZE);
- return Color_CreatePyObject(tcol, Py_TYPE(self));
+ negate_vn_vn(tcol, self->col, COLOR_SIZE);
+ return Color_CreatePyObject(tcol, Py_TYPE(self));
}
-
static PyNumberMethods Color_NumMethods = {
- (binaryfunc) Color_add, /*nb_add*/
- (binaryfunc) Color_sub, /*nb_subtract*/
- (binaryfunc) Color_mul, /*nb_multiply*/
- NULL, /*nb_remainder*/
- NULL, /*nb_divmod*/
- NULL, /*nb_power*/
- (unaryfunc) Color_neg, /*nb_negative*/
- (unaryfunc) Color_copy, /*tp_positive*/
- (unaryfunc) NULL, /*tp_absolute*/
- (inquiry) NULL, /*tp_bool*/
- (unaryfunc) NULL, /*nb_invert*/
- NULL, /*nb_lshift*/
- (binaryfunc)NULL, /*nb_rshift*/
- NULL, /*nb_and*/
- NULL, /*nb_xor*/
- NULL, /*nb_or*/
- NULL, /*nb_int*/
- NULL, /*nb_reserved*/
- NULL, /*nb_float*/
- Color_iadd, /* nb_inplace_add */
- Color_isub, /* nb_inplace_subtract */
- Color_imul, /* nb_inplace_multiply */
- NULL, /* nb_inplace_remainder */
- NULL, /* nb_inplace_power */
- NULL, /* nb_inplace_lshift */
- NULL, /* nb_inplace_rshift */
- NULL, /* nb_inplace_and */
- NULL, /* nb_inplace_xor */
- NULL, /* nb_inplace_or */
- NULL, /* nb_floor_divide */
- Color_div, /* nb_true_divide */
- NULL, /* nb_inplace_floor_divide */
- Color_idiv, /* nb_inplace_true_divide */
- NULL, /* nb_index */
+ (binaryfunc)Color_add, /*nb_add*/
+ (binaryfunc)Color_sub, /*nb_subtract*/
+ (binaryfunc)Color_mul, /*nb_multiply*/
+ NULL, /*nb_remainder*/
+ NULL, /*nb_divmod*/
+ NULL, /*nb_power*/
+ (unaryfunc)Color_neg, /*nb_negative*/
+ (unaryfunc)Color_copy, /*tp_positive*/
+ (unaryfunc)NULL, /*tp_absolute*/
+ (inquiry)NULL, /*tp_bool*/
+ (unaryfunc)NULL, /*nb_invert*/
+ NULL, /*nb_lshift*/
+ (binaryfunc)NULL, /*nb_rshift*/
+ NULL, /*nb_and*/
+ NULL, /*nb_xor*/
+ NULL, /*nb_or*/
+ NULL, /*nb_int*/
+ NULL, /*nb_reserved*/
+ NULL, /*nb_float*/
+ Color_iadd, /* nb_inplace_add */
+ Color_isub, /* nb_inplace_subtract */
+ Color_imul, /* nb_inplace_multiply */
+ NULL, /* nb_inplace_remainder */
+ NULL, /* nb_inplace_power */
+ NULL, /* nb_inplace_lshift */
+ NULL, /* nb_inplace_rshift */
+ NULL, /* nb_inplace_and */
+ NULL, /* nb_inplace_xor */
+ NULL, /* nb_inplace_or */
+ NULL, /* nb_floor_divide */
+ Color_div, /* nb_true_divide */
+ NULL, /* nb_inplace_floor_divide */
+ Color_idiv, /* nb_inplace_true_divide */
+ NULL, /* nb_index */
};
/* color channel, vector.r/g/b */
@@ -739,12 +737,12 @@ PyDoc_STRVAR(Color_channel_b_doc, "Blue color channel.\n\n:type: float");
static PyObject *Color_channel_get(ColorObject *self, void *type)
{
- return Color_item(self, POINTER_AS_INT(type));
+ return Color_item(self, POINTER_AS_INT(type));
}
static int Color_channel_set(ColorObject *self, PyObject *value, void *type)
{
- return Color_ass_item(self, POINTER_AS_INT(type), value);
+ return Color_ass_item(self, POINTER_AS_INT(type), value);
}
/* color channel (HSV), color.h/s/v */
@@ -754,258 +752,290 @@ PyDoc_STRVAR(Color_channel_hsv_v_doc, "HSV Value component in [0, 1].\n\n:type:
static PyObject *Color_channel_hsv_get(ColorObject *self, void *type)
{
- float hsv[3];
- int i = POINTER_AS_INT(type);
+ float hsv[3];
+ int i = POINTER_AS_INT(type);
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
+ rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
- return PyFloat_FromDouble(hsv[i]);
+ return PyFloat_FromDouble(hsv[i]);
}
static int Color_channel_hsv_set(ColorObject *self, PyObject *value, void *type)
{
- float hsv[3];
- int i = POINTER_AS_INT(type);
- float f = PyFloat_AsDouble(value);
-
- if (f == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "color.h/s/v = value: "
- "assigned value not a number");
- return -1;
- }
-
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
-
- rgb_to_hsv_v(self->col, hsv);
- CLAMP(f, 0.0f, 1.0f);
- hsv[i] = f;
- hsv_to_rgb_v(hsv, self->col);
-
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
-
- return 0;
+ float hsv[3];
+ int i = POINTER_AS_INT(type);
+ float f = PyFloat_AsDouble(value);
+
+ if (f == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "color.h/s/v = value: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ rgb_to_hsv_v(self->col, hsv);
+ CLAMP(f, 0.0f, 1.0f);
+ hsv[i] = f;
+ hsv_to_rgb_v(hsv, self->col);
+
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
+
+ return 0;
}
/* color channel (HSV), color.h/s/v */
PyDoc_STRVAR(Color_hsv_doc, "HSV Values in [0, 1].\n\n:type: float triplet");
static PyObject *Color_hsv_get(ColorObject *self, void *UNUSED(closure))
{
- float hsv[3];
- PyObject *ret;
+ float hsv[3];
+ PyObject *ret;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
+ rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
- ret = PyTuple_New(3);
- PyTuple_SET_ITEMS(ret,
- PyFloat_FromDouble(hsv[0]),
- PyFloat_FromDouble(hsv[1]),
- PyFloat_FromDouble(hsv[2]));
- return ret;
+ ret = PyTuple_New(3);
+ PyTuple_SET_ITEMS(
+ ret, PyFloat_FromDouble(hsv[0]), PyFloat_FromDouble(hsv[1]), PyFloat_FromDouble(hsv[2]));
+ return ret;
}
static int Color_hsv_set(ColorObject *self, PyObject *value, void *UNUSED(closure))
{
- float hsv[3];
+ float hsv[3];
- if (mathutils_array_parse(hsv, 3, 3, value, "mathutils.Color.hsv = value") == -1) {
- return -1;
- }
+ if (mathutils_array_parse(hsv, 3, 3, value, "mathutils.Color.hsv = value") == -1) {
+ return -1;
+ }
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
- CLAMP(hsv[0], 0.0f, 1.0f);
- CLAMP(hsv[1], 0.0f, 1.0f);
- CLAMP(hsv[2], 0.0f, 1.0f);
+ CLAMP(hsv[0], 0.0f, 1.0f);
+ CLAMP(hsv[1], 0.0f, 1.0f);
+ CLAMP(hsv[2], 0.0f, 1.0f);
- hsv_to_rgb_v(hsv, self->col);
+ hsv_to_rgb_v(hsv, self->col);
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
- return 0;
+ return 0;
}
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Color_getseters[] = {
- {(char *)"r", (getter)Color_channel_get, (setter)Color_channel_set, Color_channel_r_doc, (void *)0},
- {(char *)"g", (getter)Color_channel_get, (setter)Color_channel_set, Color_channel_g_doc, (void *)1},
- {(char *)"b", (getter)Color_channel_get, (setter)Color_channel_set, Color_channel_b_doc, (void *)2},
-
- {(char *)"h", (getter)Color_channel_hsv_get, (setter)Color_channel_hsv_set, (char *)Color_channel_hsv_h_doc, (void *)0},
- {(char *)"s", (getter)Color_channel_hsv_get, (setter)Color_channel_hsv_set, (char *)Color_channel_hsv_s_doc, (void *)1},
- {(char *)"v", (getter)Color_channel_hsv_get, (setter)Color_channel_hsv_set, (char *)Color_channel_hsv_v_doc, (void *)2},
-
- {(char *)"hsv", (getter)Color_hsv_get, (setter)Color_hsv_set, (char *)Color_hsv_doc, (void *)0},
-
- {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
- {(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
- {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"r",
+ (getter)Color_channel_get,
+ (setter)Color_channel_set,
+ Color_channel_r_doc,
+ (void *)0},
+ {(char *)"g",
+ (getter)Color_channel_get,
+ (setter)Color_channel_set,
+ Color_channel_g_doc,
+ (void *)1},
+ {(char *)"b",
+ (getter)Color_channel_get,
+ (setter)Color_channel_set,
+ Color_channel_b_doc,
+ (void *)2},
+
+ {(char *)"h",
+ (getter)Color_channel_hsv_get,
+ (setter)Color_channel_hsv_set,
+ (char *)Color_channel_hsv_h_doc,
+ (void *)0},
+ {(char *)"s",
+ (getter)Color_channel_hsv_get,
+ (setter)Color_channel_hsv_set,
+ (char *)Color_channel_hsv_s_doc,
+ (void *)1},
+ {(char *)"v",
+ (getter)Color_channel_hsv_get,
+ (setter)Color_channel_hsv_set,
+ (char *)Color_channel_hsv_v_doc,
+ (void *)2},
+
+ {(char *)"hsv",
+ (getter)Color_hsv_get,
+ (setter)Color_hsv_set,
+ (char *)Color_hsv_doc,
+ (void *)0},
+
+ {(char *)"is_wrapped",
+ (getter)BaseMathObject_is_wrapped_get,
+ (setter)NULL,
+ BaseMathObject_is_wrapped_doc,
+ NULL},
+ {(char *)"is_frozen",
+ (getter)BaseMathObject_is_frozen_get,
+ (setter)NULL,
+ BaseMathObject_is_frozen_doc,
+ NULL},
+ {(char *)"owner",
+ (getter)BaseMathObject_owner_get,
+ (setter)NULL,
+ BaseMathObject_owner_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Color_methods[] = {
- {"copy", (PyCFunction) Color_copy, METH_NOARGS, Color_copy_doc},
- {"__copy__", (PyCFunction) Color_copy, METH_NOARGS, Color_copy_doc},
- {"__deepcopy__", (PyCFunction) Color_deepcopy, METH_VARARGS, Color_copy_doc},
+ {"copy", (PyCFunction)Color_copy, METH_NOARGS, Color_copy_doc},
+ {"__copy__", (PyCFunction)Color_copy, METH_NOARGS, Color_copy_doc},
+ {"__deepcopy__", (PyCFunction)Color_deepcopy, METH_VARARGS, Color_copy_doc},
- /* base-math methods */
- {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
- {NULL, NULL, 0, NULL},
+ /* base-math methods */
+ {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
+ {NULL, NULL, 0, NULL},
};
/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(color_doc,
-".. class:: Color(rgb)\n"
-"\n"
-" This object gives access to Colors in Blender.\n"
-"\n"
-" :param rgb: (r, g, b) color values\n"
-" :type rgb: 3d vector\n"
-);
+ ".. class:: Color(rgb)\n"
+ "\n"
+ " This object gives access to Colors in Blender.\n"
+ "\n"
+ " :param rgb: (r, g, b) color values\n"
+ " :type rgb: 3d vector\n");
PyTypeObject color_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Color", /* tp_name */
- sizeof(ColorObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)BaseMathObject_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- (reprfunc) Color_repr, /* tp_repr */
- &Color_NumMethods, /* tp_as_number */
- &Color_SeqMethods, /* tp_as_sequence */
- &Color_AsMapping, /* tp_as_mapping */
- (hashfunc)Color_hash, /* tp_hash */
- NULL, /* tp_call */
+ PyVarObject_HEAD_INIT(NULL, 0) "Color", /* tp_name */
+ sizeof(ColorObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc)Color_repr, /* tp_repr */
+ &Color_NumMethods, /* tp_as_number */
+ &Color_SeqMethods, /* tp_as_sequence */
+ &Color_AsMapping, /* tp_as_mapping */
+ (hashfunc)Color_hash, /* tp_hash */
+ NULL, /* tp_call */
#ifndef MATH_STANDALONE
- (reprfunc) Color_str, /* tp_str */
+ (reprfunc)Color_str, /* tp_str */
#else
- NULL, /* tp_str */
+ NULL, /* tp_str */
#endif
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- color_doc, /* tp_doc */
- (traverseproc)BaseMathObject_traverse, /* tp_traverse */
- (inquiry)BaseMathObject_clear, /* tp_clear */
- (richcmpfunc)Color_richcmpr, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- Color_methods, /* tp_methods */
- NULL, /* tp_members */
- Color_getseters, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- NULL, /* tp_init */
- NULL, /* tp_alloc */
- Color_new, /* tp_new */
- NULL, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- NULL, /* tp_del */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ color_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Color_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Color_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Color_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Color_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL, /* tp_del */
};
-PyObject *Color_CreatePyObject(
- const float col[3],
- PyTypeObject *base_type)
+PyObject *Color_CreatePyObject(const float col[3], PyTypeObject *base_type)
{
- ColorObject *self;
- float *col_alloc;
-
- col_alloc = PyMem_Malloc(COLOR_SIZE * sizeof(float));
- if (UNLIKELY(col_alloc == NULL)) {
- PyErr_SetString(PyExc_MemoryError,
- "Color(): "
- "problem allocating data");
- return NULL;
- }
-
- self = BASE_MATH_NEW(ColorObject, color_Type, base_type);
- if (self) {
- self->col = col_alloc;
-
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- /* NEW */
- if (col) {
- copy_v3_v3(self->col, col);
- }
- else {
- zero_v3(self->col);
- }
-
- self->flag = BASE_MATH_FLAG_DEFAULT;
- }
- else {
- PyMem_Free(col_alloc);
- }
-
- return (PyObject *)self;
+ ColorObject *self;
+ float *col_alloc;
+
+ col_alloc = PyMem_Malloc(COLOR_SIZE * sizeof(float));
+ if (UNLIKELY(col_alloc == NULL)) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Color(): "
+ "problem allocating data");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(ColorObject, color_Type, base_type);
+ if (self) {
+ self->col = col_alloc;
+
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ /* NEW */
+ if (col) {
+ copy_v3_v3(self->col, col);
+ }
+ else {
+ zero_v3(self->col);
+ }
+
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ }
+ else {
+ PyMem_Free(col_alloc);
+ }
+
+ return (PyObject *)self;
}
-PyObject *Color_CreatePyObject_wrap(
- float col[3],
- PyTypeObject *base_type)
+PyObject *Color_CreatePyObject_wrap(float col[3], PyTypeObject *base_type)
{
- ColorObject *self;
+ ColorObject *self;
- self = BASE_MATH_NEW(ColorObject, color_Type, base_type);
- if (self) {
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
+ self = BASE_MATH_NEW(ColorObject, color_Type, base_type);
+ if (self) {
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
- /* WRAP */
- self->col = col;
- self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
- }
+ /* WRAP */
+ self->col = col;
+ self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
PyObject *Color_CreatePyObject_cb(PyObject *cb_user,
- unsigned char cb_type, unsigned char cb_subtype)
-{
- ColorObject *self = (ColorObject *)Color_CreatePyObject(NULL, NULL);
- if (self) {
- Py_INCREF(cb_user);
- self->cb_user = cb_user;
- self->cb_type = cb_type;
- self->cb_subtype = cb_subtype;
- PyObject_GC_Track(self);
- }
-
- return (PyObject *)self;
+ unsigned char cb_type,
+ unsigned char cb_subtype)
+{
+ ColorObject *self = (ColorObject *)Color_CreatePyObject(NULL, NULL);
+ if (self) {
+ Py_INCREF(cb_user);
+ self->cb_user = cb_user;
+ self->cb_type = cb_type;
+ self->cb_subtype = cb_subtype;
+ PyObject_GC_Track(self);
+ }
+
+ return (PyObject *)self;
}
diff --git a/source/blender/python/mathutils/mathutils_Color.h b/source/blender/python/mathutils/mathutils_Color.h
index 6dc56f8aacb..51e1746ae74 100644
--- a/source/blender/python/mathutils/mathutils_Color.h
+++ b/source/blender/python/mathutils/mathutils_Color.h
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#ifndef __MATHUTILS_COLOR_H__
#define __MATHUTILS_COLOR_H__
@@ -27,7 +26,7 @@ extern PyTypeObject color_Type;
#define ColorObject_CheckExact(v) (Py_TYPE(v) == &color_Type)
typedef struct {
- BASE_MATH_MEMBERS(col);
+ BASE_MATH_MEMBERS(col);
} ColorObject;
/* struct data contains a pointer to the actual data that the
@@ -36,17 +35,12 @@ typedef struct {
* blender (stored in blend_data). This is an either/or struct not both*/
/* prototypes */
-PyObject *Color_CreatePyObject(
- const float col[3],
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Color_CreatePyObject_wrap(
- float col[3],
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-PyObject *Color_CreatePyObject_cb(
- PyObject *cb_user,
- unsigned char cb_type, unsigned char cb_subtype
- ) ATTR_WARN_UNUSED_RESULT;
+PyObject *Color_CreatePyObject(const float col[3],
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT;
+PyObject *Color_CreatePyObject_wrap(float col[3], PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+PyObject *Color_CreatePyObject_cb(PyObject *cb_user,
+ unsigned char cb_type,
+ unsigned char cb_subtype) ATTR_WARN_UNUSED_RESULT;
#endif /* __MATHUTILS_COLOR_H__ */
diff --git a/source/blender/python/mathutils/mathutils_Euler.c b/source/blender/python/mathutils/mathutils_Euler.c
index 4177fc489bb..56662465b52 100644
--- a/source/blender/python/mathutils/mathutils_Euler.c
+++ b/source/blender/python/mathutils/mathutils_Euler.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -38,291 +37,289 @@
/* makes a new euler for you to play with */
static PyObject *Euler_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq = NULL;
- const char *order_str = NULL;
-
- float eul[EULER_SIZE] = {0.0f, 0.0f, 0.0f};
- short order = EULER_ORDER_XYZ;
-
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "mathutils.Euler(): "
- "takes no keyword args");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "|Os:mathutils.Euler", &seq, &order_str)) {
- return NULL;
- }
-
- switch (PyTuple_GET_SIZE(args)) {
- case 0:
- break;
- case 2:
- if ((order = euler_order_from_string(order_str, "mathutils.Euler()")) == -1) {
- return NULL;
- }
- ATTR_FALLTHROUGH;
- case 1:
- if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1) {
- return NULL;
- }
- break;
- }
- return Euler_CreatePyObject(eul, order, type);
+ PyObject *seq = NULL;
+ const char *order_str = NULL;
+
+ float eul[EULER_SIZE] = {0.0f, 0.0f, 0.0f};
+ short order = EULER_ORDER_XYZ;
+
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError,
+ "mathutils.Euler(): "
+ "takes no keyword args");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "|Os:mathutils.Euler", &seq, &order_str)) {
+ return NULL;
+ }
+
+ switch (PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 2:
+ if ((order = euler_order_from_string(order_str, "mathutils.Euler()")) == -1) {
+ return NULL;
+ }
+ ATTR_FALLTHROUGH;
+ case 1:
+ if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1) {
+ return NULL;
+ }
+ break;
+ }
+ return Euler_CreatePyObject(eul, order, type);
}
/* internal use, assume read callback is done */
static const char *euler_order_str(EulerObject *self)
{
- static const char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
- return order[self->order - EULER_ORDER_XYZ];
+ static const char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
+ return order[self->order - EULER_ORDER_XYZ];
}
short euler_order_from_string(const char *str, const char *error_prefix)
{
- if ((str[0] && str[1] && str[2] && str[3] == '\0')) {
+ if ((str[0] && str[1] && str[2] && str[3] == '\0')) {
#ifdef __LITTLE_ENDIAN__
-# define MAKE_ID3(a, b, c) (((a)) | ((b) << 8) | ((c) << 16))
+# define MAKE_ID3(a, b, c) (((a)) | ((b) << 8) | ((c) << 16))
#else
-# define MAKE_ID3(a, b, c) (((a) << 24) | ((b) << 16) | ((c) << 8))
+# define MAKE_ID3(a, b, c) (((a) << 24) | ((b) << 16) | ((c) << 8))
#endif
- switch (*((PY_INT32_T *)str)) {
- case MAKE_ID3('X', 'Y', 'Z'): return EULER_ORDER_XYZ;
- case MAKE_ID3('X', 'Z', 'Y'): return EULER_ORDER_XZY;
- case MAKE_ID3('Y', 'X', 'Z'): return EULER_ORDER_YXZ;
- case MAKE_ID3('Y', 'Z', 'X'): return EULER_ORDER_YZX;
- case MAKE_ID3('Z', 'X', 'Y'): return EULER_ORDER_ZXY;
- case MAKE_ID3('Z', 'Y', 'X'): return EULER_ORDER_ZYX;
- }
+ switch (*((PY_INT32_T *)str)) {
+ case MAKE_ID3('X', 'Y', 'Z'):
+ return EULER_ORDER_XYZ;
+ case MAKE_ID3('X', 'Z', 'Y'):
+ return EULER_ORDER_XZY;
+ case MAKE_ID3('Y', 'X', 'Z'):
+ return EULER_ORDER_YXZ;
+ case MAKE_ID3('Y', 'Z', 'X'):
+ return EULER_ORDER_YZX;
+ case MAKE_ID3('Z', 'X', 'Y'):
+ return EULER_ORDER_ZXY;
+ case MAKE_ID3('Z', 'Y', 'X'):
+ return EULER_ORDER_ZYX;
+ }
#undef MAKE_ID3
- }
+ }
- PyErr_Format(PyExc_ValueError,
- "%s: invalid euler order '%s'",
- error_prefix, str);
- return -1;
+ PyErr_Format(PyExc_ValueError, "%s: invalid euler order '%s'", error_prefix, str);
+ 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;
+ 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----------------------------
* return a quaternion representation of the euler */
PyDoc_STRVAR(Euler_to_quaternion_doc,
-".. method:: to_quaternion()\n"
-"\n"
-" Return a quaternion representation of the euler.\n"
-"\n"
-" :return: Quaternion representation of the euler.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. method:: to_quaternion()\n"
+ "\n"
+ " Return a quaternion representation of the euler.\n"
+ "\n"
+ " :return: Quaternion representation of the euler.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Euler_to_quaternion(EulerObject *self)
{
- float quat[4];
+ float quat[4];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- eulO_to_quat(quat, self->eul, self->order);
+ eulO_to_quat(quat, self->eul, self->order);
- return Quaternion_CreatePyObject(quat, NULL);
+ return Quaternion_CreatePyObject(quat, NULL);
}
/* return a matrix representation of the euler */
PyDoc_STRVAR(Euler_to_matrix_doc,
-".. method:: to_matrix()\n"
-"\n"
-" Return a matrix representation of the euler.\n"
-"\n"
-" :return: A 3x3 rotation matrix representation of the euler.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: to_matrix()\n"
+ "\n"
+ " Return a matrix representation of the euler.\n"
+ "\n"
+ " :return: A 3x3 rotation matrix representation of the euler.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Euler_to_matrix(EulerObject *self)
{
- float mat[9];
+ float mat[9];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
+ eulO_to_mat3((float(*)[3])mat, self->eul, self->order);
- return Matrix_CreatePyObject(mat, 3, 3, NULL);
+ return Matrix_CreatePyObject(mat, 3, 3, NULL);
}
PyDoc_STRVAR(Euler_zero_doc,
-".. method:: zero()\n"
-"\n"
-" Set all values to zero.\n"
-);
+ ".. method:: zero()\n"
+ "\n"
+ " Set all values to zero.\n");
static PyObject *Euler_zero(EulerObject *self)
{
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return NULL;
+ }
- zero_v3(self->eul);
+ zero_v3(self->eul);
- if (BaseMath_WriteCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Euler_rotate_axis_doc,
-".. method:: rotate_axis(axis, angle)\n"
-"\n"
-" Rotates the euler a certain amount and returning a unique euler rotation\n"
-" (no 720 degree pitches).\n"
-"\n"
-" :arg axis: single character in ['X, 'Y', 'Z'].\n"
-" :type axis: string\n"
-" :arg angle: angle in radians.\n"
-" :type angle: float\n"
-);
+ ".. method:: rotate_axis(axis, angle)\n"
+ "\n"
+ " Rotates the euler a certain amount and returning a unique euler rotation\n"
+ " (no 720 degree pitches).\n"
+ "\n"
+ " :arg axis: single character in ['X, 'Y', 'Z'].\n"
+ " :type axis: string\n"
+ " :arg angle: angle in radians.\n"
+ " :type angle: float\n");
static PyObject *Euler_rotate_axis(EulerObject *self, PyObject *args)
{
- float angle = 0.0f;
- int axis; /* actually a character */
-
- if (!PyArg_ParseTuple(args, "Cf:rotate_axis", &axis, &angle)) {
- PyErr_SetString(PyExc_TypeError,
- "Euler.rotate_axis(): "
- "expected an axis 'X', 'Y', 'Z' and an angle (float)");
- return NULL;
- }
+ float angle = 0.0f;
+ int axis; /* actually a character */
- if (!(ELEM(axis, 'X', 'Y', 'Z'))) {
- PyErr_SetString(PyExc_ValueError,
- "Euler.rotate_axis(): "
- "expected axis to be 'X', 'Y' or 'Z'");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "Cf:rotate_axis", &axis, &angle)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Euler.rotate_axis(): "
+ "expected an axis 'X', 'Y', 'Z' and an angle (float)");
+ return NULL;
+ }
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (!(ELEM(axis, 'X', 'Y', 'Z'))) {
+ PyErr_SetString(PyExc_ValueError,
+ "Euler.rotate_axis(): "
+ "expected axis to be 'X', 'Y' or 'Z'");
+ return NULL;
+ }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- rotate_eulO(self->eul, self->order, (char)axis, angle);
+ rotate_eulO(self->eul, self->order, (char)axis, angle);
- (void)BaseMath_WriteCallback(self);
+ (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Euler_rotate_doc,
-".. method:: rotate(other)\n"
-"\n"
-" Rotates the euler by another mathutils value.\n"
-"\n"
-" :arg other: rotation component of mathutils value\n"
-" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
-);
+ ".. method:: rotate(other)\n"
+ "\n"
+ " Rotates the euler by another mathutils value.\n"
+ "\n"
+ " :arg other: rotation component of mathutils value\n"
+ " :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n");
static PyObject *Euler_rotate(EulerObject *self, PyObject *value)
{
- float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
+ float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (mathutils_any_to_rotmat(other_rmat, value, "euler.rotate(value)") == -1) {
- return NULL;
- }
+ if (mathutils_any_to_rotmat(other_rmat, value, "euler.rotate(value)") == -1) {
+ return NULL;
+ }
- eulO_to_mat3(self_rmat, self->eul, self->order);
- mul_m3_m3m3(rmat, other_rmat, self_rmat);
+ eulO_to_mat3(self_rmat, self->eul, self->order);
+ mul_m3_m3m3(rmat, other_rmat, self_rmat);
- mat3_to_compatible_eulO(self->eul, self->eul, self->order, rmat);
+ mat3_to_compatible_eulO(self->eul, self->eul, self->order, rmat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Euler_make_compatible_doc,
-".. method:: make_compatible(other)\n"
-"\n"
-" Make this euler compatible with another,\n"
-" so interpolating between them works as intended.\n"
-"\n"
-" .. note:: the rotation order is not taken into account for this function.\n"
-);
+ ".. method:: make_compatible(other)\n"
+ "\n"
+ " Make this euler compatible with another,\n"
+ " so interpolating between them works as intended.\n"
+ "\n"
+ " .. note:: the rotation order is not taken into account for this function.\n");
static PyObject *Euler_make_compatible(EulerObject *self, PyObject *value)
{
- float teul[EULER_SIZE];
+ float teul[EULER_SIZE];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse(teul, EULER_SIZE, EULER_SIZE, value,
- "euler.make_compatible(other), invalid 'other' arg") == -1)
- {
- return NULL;
- }
+ if (mathutils_array_parse(teul,
+ EULER_SIZE,
+ EULER_SIZE,
+ value,
+ "euler.make_compatible(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
- compatible_eul(self->eul, teul);
+ compatible_eul(self->eul, teul);
- (void)BaseMath_WriteCallback(self);
+ (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/* ----------------------------Euler.rotate()-----------------------
* return a copy of the euler */
PyDoc_STRVAR(Euler_copy_doc,
-".. function:: copy()\n"
-"\n"
-" Returns a copy of this euler.\n"
-"\n"
-" :return: A copy of the euler.\n"
-" :rtype: :class:`Euler`\n"
-"\n"
-" .. note:: use this to get a copy of a wrapped euler with\n"
-" no reference to the original data.\n"
-);
+ ".. function:: copy()\n"
+ "\n"
+ " Returns a copy of this euler.\n"
+ "\n"
+ " :return: A copy of the euler.\n"
+ " :rtype: :class:`Euler`\n"
+ "\n"
+ " .. note:: use this to get a copy of a wrapped euler with\n"
+ " no reference to the original data.\n");
static PyObject *Euler_copy(EulerObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Euler_CreatePyObject(self->eul, self->order, Py_TYPE(self));
+ return Euler_CreatePyObject(self->eul, self->order, Py_TYPE(self));
}
static PyObject *Euler_deepcopy(EulerObject *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return Euler_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return Euler_copy(self);
}
/* ----------------------------print object (internal)--------------
@@ -330,87 +327,94 @@ static PyObject *Euler_deepcopy(EulerObject *self, PyObject *args)
static PyObject *Euler_repr(EulerObject *self)
{
- PyObject *ret, *tuple;
+ PyObject *ret, *tuple;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- tuple = Euler_ToTupleExt(self, -1);
+ tuple = Euler_ToTupleExt(self, -1);
- ret = PyUnicode_FromFormat("Euler(%R, '%s')", tuple, euler_order_str(self));
+ ret = PyUnicode_FromFormat("Euler(%R, '%s')", tuple, euler_order_str(self));
- Py_DECREF(tuple);
- return ret;
+ Py_DECREF(tuple);
+ return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Euler_str(EulerObject *self)
{
- DynStr *ds;
+ DynStr *ds;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- ds = BLI_dynstr_new();
+ ds = BLI_dynstr_new();
- BLI_dynstr_appendf(ds, "<Euler (x=%.4f, y=%.4f, z=%.4f), order='%s'>",
- self->eul[0], self->eul[1], self->eul[2], euler_order_str(self));
+ BLI_dynstr_appendf(ds,
+ "<Euler (x=%.4f, y=%.4f, z=%.4f), order='%s'>",
+ self->eul[0],
+ self->eul[1],
+ self->eul[2],
+ euler_order_str(self));
- return mathutils_dynstr_to_py(ds); /* frees ds */
+ return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
static PyObject *Euler_richcmpr(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
-
- if (EulerObject_Check(a) && EulerObject_Check(b)) {
- EulerObject *eulA = (EulerObject *)a;
- EulerObject *eulB = (EulerObject *)b;
-
- if (BaseMath_ReadCallback(eulA) == -1 || BaseMath_ReadCallback(eulB) == -1) {
- return NULL;
- }
-
- ok = ((eulA->order == eulB->order) && EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1)) ? 0 : -1;
- }
-
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
-
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- return Py_INCREF_RET(res);
+ PyObject *res;
+ int ok = -1; /* zero is true */
+
+ if (EulerObject_Check(a) && EulerObject_Check(b)) {
+ EulerObject *eulA = (EulerObject *)a;
+ EulerObject *eulB = (EulerObject *)b;
+
+ if (BaseMath_ReadCallback(eulA) == -1 || BaseMath_ReadCallback(eulB) == -1) {
+ return NULL;
+ }
+
+ ok = ((eulA->order == eulB->order) &&
+ EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1)) ?
+ 0 :
+ -1;
+ }
+
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
+
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ return Py_INCREF_RET(res);
}
static Py_hash_t Euler_hash(EulerObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- if (BaseMathObject_Prepare_ForHash(self) == -1) {
- return -1;
- }
+ if (BaseMathObject_Prepare_ForHash(self) == -1) {
+ return -1;
+ }
- return mathutils_array_hash(self->eul, EULER_SIZE);
+ return mathutils_array_hash(self->eul, EULER_SIZE);
}
/* ---------------------SEQUENCE PROTOCOLS------------------------ */
@@ -418,449 +422,451 @@ static Py_hash_t Euler_hash(EulerObject *self)
/* sequence length */
static int Euler_len(EulerObject *UNUSED(self))
{
- return EULER_SIZE;
+ return EULER_SIZE;
}
/* ----------------------------object[]--------------------------- */
/* sequence accessor (get) */
static PyObject *Euler_item(EulerObject *self, int i)
{
- if (i < 0) {
- i = EULER_SIZE - i;
- }
-
- if (i < 0 || i >= EULER_SIZE) {
- PyErr_SetString(PyExc_IndexError,
- "euler[attribute]: "
- "array index out of range");
- return NULL;
- }
-
- if (BaseMath_ReadIndexCallback(self, i) == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(self->eul[i]);
-
+ if (i < 0) {
+ i = EULER_SIZE - i;
+ }
+
+ if (i < 0 || i >= EULER_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "euler[attribute]: "
+ "array index out of range");
+ return NULL;
+ }
+
+ if (BaseMath_ReadIndexCallback(self, i) == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(self->eul[i]);
}
/* ----------------------------object[]------------------------- */
/* sequence accessor (set) */
static int Euler_ass_item(EulerObject *self, int i, PyObject *value)
{
- float f;
-
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
-
- f = PyFloat_AsDouble(value);
- if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError,
- "euler[attribute] = x: "
- "assigned value not a number");
- return -1;
- }
-
- if (i < 0) {
- i = EULER_SIZE - i;
- }
-
- if (i < 0 || i >= EULER_SIZE) {
- PyErr_SetString(PyExc_IndexError,
- "euler[attribute] = x: "
- "array assignment index out of range");
- return -1;
- }
-
- self->eul[i] = f;
-
- if (BaseMath_WriteIndexCallback(self, i) == -1) {
- return -1;
- }
-
- return 0;
+ float f;
+
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ f = PyFloat_AsDouble(value);
+ if (f == -1 && PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError,
+ "euler[attribute] = x: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ if (i < 0) {
+ i = EULER_SIZE - i;
+ }
+
+ if (i < 0 || i >= EULER_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "euler[attribute] = x: "
+ "array assignment index out of range");
+ return -1;
+ }
+
+ self->eul[i] = f;
+
+ if (BaseMath_WriteIndexCallback(self, i) == -1) {
+ return -1;
+ }
+
+ return 0;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (get) */
static PyObject *Euler_slice(EulerObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- CLAMP(begin, 0, EULER_SIZE);
- if (end < 0) {
- end = (EULER_SIZE + 1) + end;
- }
- CLAMP(end, 0, EULER_SIZE);
- begin = MIN2(begin, end);
-
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->eul[count]));
- }
-
- return tuple;
+ PyObject *tuple;
+ int count;
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ CLAMP(begin, 0, EULER_SIZE);
+ if (end < 0) {
+ end = (EULER_SIZE + 1) + end;
+ }
+ CLAMP(end, 0, EULER_SIZE);
+ begin = MIN2(begin, end);
+
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->eul[count]));
+ }
+
+ return tuple;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (set) */
static int Euler_ass_slice(EulerObject *self, int begin, int end, PyObject *seq)
{
- int i, size;
- float eul[EULER_SIZE];
-
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
-
- CLAMP(begin, 0, EULER_SIZE);
- if (end < 0) {
- end = (EULER_SIZE + 1) + end;
- }
- CLAMP(end, 0, EULER_SIZE);
- begin = MIN2(begin, end);
-
- if ((size = mathutils_array_parse(eul, 0, EULER_SIZE, seq, "mathutils.Euler[begin:end] = []")) == -1) {
- return -1;
- }
-
- if (size != (end - begin)) {
- PyErr_SetString(PyExc_ValueError,
- "euler[begin:end] = []: "
- "size mismatch in slice assignment");
- return -1;
- }
-
- for (i = 0; i < EULER_SIZE; i++) {
- self->eul[begin + i] = eul[i];
- }
-
- (void)BaseMath_WriteCallback(self);
- return 0;
+ int i, size;
+ float eul[EULER_SIZE];
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ CLAMP(begin, 0, EULER_SIZE);
+ if (end < 0) {
+ end = (EULER_SIZE + 1) + end;
+ }
+ CLAMP(end, 0, EULER_SIZE);
+ begin = MIN2(begin, end);
+
+ if ((size = mathutils_array_parse(eul, 0, EULER_SIZE, seq, "mathutils.Euler[begin:end] = []")) ==
+ -1) {
+ return -1;
+ }
+
+ if (size != (end - begin)) {
+ PyErr_SetString(PyExc_ValueError,
+ "euler[begin:end] = []: "
+ "size mismatch in slice assignment");
+ return -1;
+ }
+
+ for (i = 0; i < EULER_SIZE; i++) {
+ self->eul[begin + i] = eul[i];
+ }
+
+ (void)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(item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Euler_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with eulers");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "euler indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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(item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Euler_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with eulers");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "euler indices must be integers, not %.200s", Py_TYPE(item)->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(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_IndexError,
- "slice steps not supported with euler");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "euler indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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(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_IndexError, "slice steps not supported with euler");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "euler indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
/* -----------------PROTCOL DECLARATIONS-------------------------- */
static PySequenceMethods Euler_SeqMethods = {
- (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 */
+ (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,
+ (lenfunc)Euler_len,
+ (binaryfunc)Euler_subscript,
+ (objobjargproc)Euler_ass_subscript,
};
/* euler axis, euler.x/y/z */
-PyDoc_STRVAR(Euler_axis_doc,
-"Euler axis angle in radians.\n\n:type: float"
-);
+PyDoc_STRVAR(Euler_axis_doc, "Euler axis angle in radians.\n\n:type: float");
static PyObject *Euler_axis_get(EulerObject *self, void *type)
{
- return Euler_item(self, POINTER_AS_INT(type));
+ return Euler_item(self, POINTER_AS_INT(type));
}
static int Euler_axis_set(EulerObject *self, PyObject *value, void *type)
{
- return Euler_ass_item(self, POINTER_AS_INT(type), value);
+ return Euler_ass_item(self, POINTER_AS_INT(type), value);
}
/* rotation order */
-PyDoc_STRVAR(Euler_order_doc,
-"Euler rotation order.\n\n:type: string in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']"
-);
+PyDoc_STRVAR(
+ Euler_order_doc,
+ "Euler rotation order.\n\n:type: string in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']");
static PyObject *Euler_order_get(EulerObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- /* can read order too */
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ /* can read order too */
+ return NULL;
+ }
- return PyUnicode_FromString(euler_order_str(self));
+ return PyUnicode_FromString(euler_order_str(self));
}
static int Euler_order_set(EulerObject *self, PyObject *value, void *UNUSED(closure))
{
- const char *order_str;
- short order;
-
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
-
- if (((order_str = _PyUnicode_AsString(value)) == NULL) ||
- ((order = euler_order_from_string(order_str, "euler.order")) == -1))
- {
- return -1;
- }
-
- self->order = order;
- (void)BaseMath_WriteCallback(self); /* order can be written back */
- return 0;
+ const char *order_str;
+ short order;
+
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ if (((order_str = _PyUnicode_AsString(value)) == NULL) ||
+ ((order = euler_order_from_string(order_str, "euler.order")) == -1)) {
+ return -1;
+ }
+
+ self->order = order;
+ (void)BaseMath_WriteCallback(self); /* order can be written back */
+ return 0;
}
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Euler_getseters[] = {
- {(char *)"x", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)0},
- {(char *)"y", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)1},
- {(char *)"z", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)2},
- {(char *)"order", (getter)Euler_order_get, (setter)Euler_order_set, Euler_order_doc, (void *)NULL},
-
- {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
- {(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
- {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"x", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)0},
+ {(char *)"y", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)1},
+ {(char *)"z", (getter)Euler_axis_get, (setter)Euler_axis_set, Euler_axis_doc, (void *)2},
+ {(char *)"order",
+ (getter)Euler_order_get,
+ (setter)Euler_order_set,
+ Euler_order_doc,
+ (void *)NULL},
+
+ {(char *)"is_wrapped",
+ (getter)BaseMathObject_is_wrapped_get,
+ (setter)NULL,
+ BaseMathObject_is_wrapped_doc,
+ NULL},
+ {(char *)"is_frozen",
+ (getter)BaseMathObject_is_frozen_get,
+ (setter)NULL,
+ BaseMathObject_is_frozen_doc,
+ NULL},
+ {(char *)"owner",
+ (getter)BaseMathObject_owner_get,
+ (setter)NULL,
+ BaseMathObject_owner_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
-
/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Euler_methods[] = {
- {"zero", (PyCFunction) Euler_zero, METH_NOARGS, Euler_zero_doc},
- {"to_matrix", (PyCFunction) Euler_to_matrix, METH_NOARGS, Euler_to_matrix_doc},
- {"to_quaternion", (PyCFunction) Euler_to_quaternion, METH_NOARGS, Euler_to_quaternion_doc},
- {"rotate_axis", (PyCFunction) Euler_rotate_axis, METH_VARARGS, Euler_rotate_axis_doc},
- {"rotate", (PyCFunction) Euler_rotate, METH_O, Euler_rotate_doc},
- {"make_compatible", (PyCFunction) Euler_make_compatible, METH_O, Euler_make_compatible_doc},
- {"copy", (PyCFunction) Euler_copy, METH_NOARGS, Euler_copy_doc},
- {"__copy__", (PyCFunction) Euler_copy, METH_NOARGS, Euler_copy_doc},
- {"__deepcopy__", (PyCFunction) Euler_deepcopy, METH_VARARGS, Euler_copy_doc},
-
- /* base-math methods */
- {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
- {NULL, NULL, 0, NULL},
+ {"zero", (PyCFunction)Euler_zero, METH_NOARGS, Euler_zero_doc},
+ {"to_matrix", (PyCFunction)Euler_to_matrix, METH_NOARGS, Euler_to_matrix_doc},
+ {"to_quaternion", (PyCFunction)Euler_to_quaternion, METH_NOARGS, Euler_to_quaternion_doc},
+ {"rotate_axis", (PyCFunction)Euler_rotate_axis, METH_VARARGS, Euler_rotate_axis_doc},
+ {"rotate", (PyCFunction)Euler_rotate, METH_O, Euler_rotate_doc},
+ {"make_compatible", (PyCFunction)Euler_make_compatible, METH_O, Euler_make_compatible_doc},
+ {"copy", (PyCFunction)Euler_copy, METH_NOARGS, Euler_copy_doc},
+ {"__copy__", (PyCFunction)Euler_copy, METH_NOARGS, Euler_copy_doc},
+ {"__deepcopy__", (PyCFunction)Euler_deepcopy, METH_VARARGS, Euler_copy_doc},
+
+ /* base-math methods */
+ {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
+ {NULL, NULL, 0, NULL},
};
/* ------------------PY_OBECT DEFINITION-------------------------- */
-PyDoc_STRVAR(euler_doc,
-".. class:: Euler(angles, order='XYZ')\n"
-"\n"
-" This object gives access to Eulers in Blender.\n"
-"\n"
-" .. seealso:: `Euler angles <https://en.wikipedia.org/wiki/Euler_angles>`__ on Wikipedia.\n"
-"\n"
-" :param angles: Three angles, in radians.\n"
-" :type angles: 3d vector\n"
-" :param order: Optional order of the angles, a permutation of ``XYZ``.\n"
-" :type order: str\n"
-);
+PyDoc_STRVAR(
+ euler_doc,
+ ".. class:: Euler(angles, order='XYZ')\n"
+ "\n"
+ " This object gives access to Eulers in Blender.\n"
+ "\n"
+ " .. seealso:: `Euler angles <https://en.wikipedia.org/wiki/Euler_angles>`__ on Wikipedia.\n"
+ "\n"
+ " :param angles: Three angles, in radians.\n"
+ " :type angles: 3d vector\n"
+ " :param order: Optional order of the angles, a permutation of ``XYZ``.\n"
+ " :type order: str\n");
PyTypeObject euler_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Euler", /* tp_name */
- sizeof(EulerObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)BaseMathObject_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- (reprfunc) Euler_repr, /* tp_repr */
- NULL, /* tp_as_number */
- &Euler_SeqMethods, /* tp_as_sequence */
- &Euler_AsMapping, /* tp_as_mapping */
- (hashfunc)Euler_hash, /* tp_hash */
- NULL, /* tp_call */
+ PyVarObject_HEAD_INIT(NULL, 0) "Euler", /* tp_name */
+ sizeof(EulerObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc)Euler_repr, /* tp_repr */
+ NULL, /* tp_as_number */
+ &Euler_SeqMethods, /* tp_as_sequence */
+ &Euler_AsMapping, /* tp_as_mapping */
+ (hashfunc)Euler_hash, /* tp_hash */
+ NULL, /* tp_call */
#ifndef MATH_STANDALONE
- (reprfunc) Euler_str, /* tp_str */
+ (reprfunc)Euler_str, /* tp_str */
#else
- NULL, /* tp_str */
+ NULL, /* tp_str */
#endif
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- euler_doc, /* tp_doc */
- (traverseproc)BaseMathObject_traverse, /* tp_traverse */
- (inquiry)BaseMathObject_clear, /* tp_clear */
- (richcmpfunc)Euler_richcmpr, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- Euler_methods, /* tp_methods */
- NULL, /* tp_members */
- Euler_getseters, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- NULL, /* tp_init */
- NULL, /* tp_alloc */
- Euler_new, /* tp_new */
- NULL, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- NULL, /* tp_del */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ euler_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Euler_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Euler_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Euler_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Euler_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL, /* tp_del */
};
-
-PyObject *Euler_CreatePyObject(
- const float eul[3], const short order,
- PyTypeObject *base_type)
+PyObject *Euler_CreatePyObject(const float eul[3], const short order, PyTypeObject *base_type)
{
- EulerObject *self;
- float *eul_alloc;
-
- eul_alloc = PyMem_Malloc(EULER_SIZE * sizeof(float));
- if (UNLIKELY(eul_alloc == NULL)) {
- PyErr_SetString(PyExc_MemoryError,
- "Euler(): "
- "problem allocating data");
- return NULL;
- }
-
- self = BASE_MATH_NEW(EulerObject, euler_Type, base_type);
- if (self) {
- self->eul = eul_alloc;
-
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- if (eul) {
- copy_v3_v3(self->eul, eul);
- }
- else {
- zero_v3(self->eul);
- }
-
- self->flag = BASE_MATH_FLAG_DEFAULT;
- self->order = order;
- }
- else {
- PyMem_Free(eul_alloc);
- }
-
- return (PyObject *)self;
+ EulerObject *self;
+ float *eul_alloc;
+
+ eul_alloc = PyMem_Malloc(EULER_SIZE * sizeof(float));
+ if (UNLIKELY(eul_alloc == NULL)) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Euler(): "
+ "problem allocating data");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(EulerObject, euler_Type, base_type);
+ if (self) {
+ self->eul = eul_alloc;
+
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ if (eul) {
+ copy_v3_v3(self->eul, eul);
+ }
+ else {
+ zero_v3(self->eul);
+ }
+
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ self->order = order;
+ }
+ else {
+ PyMem_Free(eul_alloc);
+ }
+
+ return (PyObject *)self;
}
-PyObject *Euler_CreatePyObject_wrap(
- float eul[3], const short order,
- PyTypeObject *base_type)
+PyObject *Euler_CreatePyObject_wrap(float eul[3], const short order, PyTypeObject *base_type)
{
- EulerObject *self;
+ EulerObject *self;
- self = BASE_MATH_NEW(EulerObject, euler_Type, base_type);
- if (self) {
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
+ self = BASE_MATH_NEW(EulerObject, euler_Type, base_type);
+ if (self) {
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
- self->eul = eul;
- self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
+ self->eul = eul;
+ self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
- self->order = order;
- }
+ self->order = order;
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
-PyObject *Euler_CreatePyObject_cb(
- PyObject *cb_user, const short order,
- unsigned char cb_type, unsigned char cb_subtype)
+PyObject *Euler_CreatePyObject_cb(PyObject *cb_user,
+ const short order,
+ unsigned char cb_type,
+ unsigned char cb_subtype)
{
- EulerObject *self = (EulerObject *)Euler_CreatePyObject(NULL, order, NULL);
- if (self) {
- Py_INCREF(cb_user);
- self->cb_user = cb_user;
- self->cb_type = cb_type;
- self->cb_subtype = cb_subtype;
- PyObject_GC_Track(self);
- }
-
- return (PyObject *)self;
+ EulerObject *self = (EulerObject *)Euler_CreatePyObject(NULL, order, NULL);
+ if (self) {
+ Py_INCREF(cb_user);
+ self->cb_user = cb_user;
+ self->cb_type = cb_type;
+ self->cb_subtype = cb_subtype;
+ PyObject_GC_Track(self);
+ }
+
+ return (PyObject *)self;
}
diff --git a/source/blender/python/mathutils/mathutils_Euler.h b/source/blender/python/mathutils/mathutils_Euler.h
index 55ca3cd6df6..c56962395e5 100644
--- a/source/blender/python/mathutils/mathutils_Euler.h
+++ b/source/blender/python/mathutils/mathutils_Euler.h
@@ -26,8 +26,8 @@ extern PyTypeObject euler_Type;
#define EulerObject_CheckExact(v) (Py_TYPE(v) == &euler_Type)
typedef struct {
- BASE_MATH_MEMBERS(eul);
- unsigned char order; /* rotation order */
+ BASE_MATH_MEMBERS(eul);
+ unsigned char order; /* rotation order */
} EulerObject;
@@ -37,20 +37,18 @@ typedef struct {
* blender (stored in blend_data). This is an either/or struct not both */
/* prototypes */
-PyObject *Euler_CreatePyObject(
- const float eul[3], const short order,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Euler_CreatePyObject_wrap(
- float eul[3], const short order,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-PyObject *Euler_CreatePyObject_cb(
- PyObject *cb_user, const short order,
- unsigned char cb_type, unsigned char cb_subtype
- ) ATTR_WARN_UNUSED_RESULT;
+PyObject *Euler_CreatePyObject(const float eul[3],
+ const short order,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT;
+PyObject *Euler_CreatePyObject_wrap(float eul[3],
+ const short order,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+PyObject *Euler_CreatePyObject_cb(PyObject *cb_user,
+ const short order,
+ unsigned char cb_type,
+ unsigned char cb_subtype) ATTR_WARN_UNUSED_RESULT;
short euler_order_from_string(const char *str, const char *error_prefix);
-
#endif /* __MATHUTILS_EULER_H__ */
diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c
index 724fcd263d4..6ccb3c2a291 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.c
+++ b/source/blender/python/mathutils/mathutils_Matrix.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -35,8 +34,8 @@
#endif
typedef enum eMatrixAccess_t {
- MAT_ACCESS_ROW,
- MAT_ACCESS_COL,
+ MAT_ACCESS_ROW,
+ MAT_ACCESS_COL,
} eMatrixAccess_t;
static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix);
@@ -48,28 +47,28 @@ static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrix
static int matrix_row_vector_check(MatrixObject *mat, VectorObject *vec, int row)
{
- if ((vec->size != mat->num_col) || (row >= mat->num_row)) {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix(): "
- "owner matrix has been resized since this row vector was created");
- return 0;
- }
- else {
- return 1;
- }
+ if ((vec->size != mat->num_col) || (row >= mat->num_row)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix(): "
+ "owner matrix has been resized since this row vector was created");
+ return 0;
+ }
+ else {
+ return 1;
+ }
}
static int matrix_col_vector_check(MatrixObject *mat, VectorObject *vec, int col)
{
- if ((vec->size != mat->num_row) || (col >= mat->num_col)) {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix(): "
- "owner matrix has been resized since this column vector was created");
- return 0;
- }
- else {
- return 1;
- }
+ if ((vec->size != mat->num_row) || (col >= mat->num_col)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix(): "
+ "owner matrix has been resized since this column vector was created");
+ return 0;
+ }
+ else {
+ return 1;
+ }
}
/* ----------------------------------------------------------------------------
@@ -80,90 +79,89 @@ unsigned char mathutils_matrix_row_cb_index = -1;
static int mathutils_matrix_row_check(BaseMathObject *bmo)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- return BaseMath_ReadCallback(self);
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_row_get(BaseMathObject *bmo, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int col;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int col;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
- if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
+ if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
+ return -1;
+ }
- for (col = 0; col < self->num_col; col++) {
- bmo->data[col] = MATRIX_ITEM(self, row, col);
- }
+ for (col = 0; col < self->num_col; col++) {
+ bmo->data[col] = MATRIX_ITEM(self, row, col);
+ }
- return 0;
+ return 0;
}
static int mathutils_matrix_row_set(BaseMathObject *bmo, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int col;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int col;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
- if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+ if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
+ return -1;
+ }
- for (col = 0; col < self->num_col; col++) {
- MATRIX_ITEM(self, row, col) = bmo->data[col];
- }
+ for (col = 0; col < self->num_col; col++) {
+ MATRIX_ITEM(self, row, col) = bmo->data[col];
+ }
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
static int mathutils_matrix_row_get_index(BaseMathObject *bmo, int row, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
- if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
+ if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
+ return -1;
+ }
- bmo->data[col] = MATRIX_ITEM(self, row, col);
- return 0;
+ bmo->data[col] = MATRIX_ITEM(self, row, col);
+ return 0;
}
static int mathutils_matrix_row_set_index(BaseMathObject *bmo, int row, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
- if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+ if (!matrix_row_vector_check(self, (VectorObject *)bmo, row)) {
+ return -1;
+ }
- MATRIX_ITEM(self, row, col) = bmo->data[col];
+ MATRIX_ITEM(self, row, col) = bmo->data[col];
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
Mathutils_Callback mathutils_matrix_row_cb = {
- mathutils_matrix_row_check,
- mathutils_matrix_row_get,
- mathutils_matrix_row_set,
- mathutils_matrix_row_get_index,
- mathutils_matrix_row_set_index,
+ mathutils_matrix_row_check,
+ mathutils_matrix_row_get,
+ mathutils_matrix_row_set,
+ mathutils_matrix_row_get_index,
+ mathutils_matrix_row_set_index,
};
-
/* ----------------------------------------------------------------------------
* matrix row callbacks
* this is so you can do matrix.col[i][j] = val */
@@ -172,98 +170,97 @@ unsigned char mathutils_matrix_col_cb_index = -1;
static int mathutils_matrix_col_check(BaseMathObject *bmo)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- return BaseMath_ReadCallback(self);
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_col_get(BaseMathObject *bmo, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int num_row;
- int row;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int num_row;
+ int row;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
- if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
+ if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
+ return -1;
+ }
- /* for 'translation' size will always be '3' even on 4x4 vec */
- num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
+ /* for 'translation' size will always be '3' even on 4x4 vec */
+ num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
- for (row = 0; row < num_row; row++) {
- bmo->data[row] = MATRIX_ITEM(self, row, col);
- }
+ for (row = 0; row < num_row; row++) {
+ bmo->data[row] = MATRIX_ITEM(self, row, col);
+ }
- return 0;
+ return 0;
}
static int mathutils_matrix_col_set(BaseMathObject *bmo, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int num_row;
- int row;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int num_row;
+ int row;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
- if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+ if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
+ return -1;
+ }
- /* for 'translation' size will always be '3' even on 4x4 vec */
- num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
+ /* for 'translation' size will always be '3' even on 4x4 vec */
+ num_row = min_ii(self->num_row, ((VectorObject *)bmo)->size);
- for (row = 0; row < num_row; row++) {
- MATRIX_ITEM(self, row, col) = bmo->data[row];
- }
+ for (row = 0; row < num_row; row++) {
+ MATRIX_ITEM(self, row, col) = bmo->data[row];
+ }
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
static int mathutils_matrix_col_get_index(BaseMathObject *bmo, int col, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
- if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
+ if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
+ return -1;
+ }
- bmo->data[row] = MATRIX_ITEM(self, row, col);
- return 0;
+ bmo->data[row] = MATRIX_ITEM(self, row, col);
+ return 0;
}
static int mathutils_matrix_col_set_index(BaseMathObject *bmo, int col, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
- if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+ if (!matrix_col_vector_check(self, (VectorObject *)bmo, col)) {
+ return -1;
+ }
- MATRIX_ITEM(self, row, col) = bmo->data[row];
+ MATRIX_ITEM(self, row, col) = bmo->data[row];
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
Mathutils_Callback mathutils_matrix_col_cb = {
- mathutils_matrix_col_check,
- mathutils_matrix_col_get,
- mathutils_matrix_col_set,
- mathutils_matrix_col_get_index,
- mathutils_matrix_col_set_index,
+ mathutils_matrix_col_check,
+ mathutils_matrix_col_get,
+ mathutils_matrix_col_set,
+ mathutils_matrix_col_get_index,
+ mathutils_matrix_col_set_index,
};
-
/* ----------------------------------------------------------------------------
* matrix row callbacks
* this is so you can do matrix.translation = val
@@ -273,78 +270,77 @@ unsigned char mathutils_matrix_translation_cb_index = -1;
static int mathutils_matrix_translation_check(BaseMathObject *bmo)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- return BaseMath_ReadCallback(self);
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ return BaseMath_ReadCallback(self);
}
static int mathutils_matrix_translation_get(BaseMathObject *bmo, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int row;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int row;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- for (row = 0; row < 3; row++) {
- bmo->data[row] = MATRIX_ITEM(self, row, col);
- }
+ for (row = 0; row < 3; row++) {
+ bmo->data[row] = MATRIX_ITEM(self, row, col);
+ }
- return 0;
+ return 0;
}
static int mathutils_matrix_translation_set(BaseMathObject *bmo, int col)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
- int row;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ int row;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- for (row = 0; row < 3; row++) {
- MATRIX_ITEM(self, row, col) = bmo->data[row];
- }
+ for (row = 0; row < 3; row++) {
+ MATRIX_ITEM(self, row, col) = bmo->data[row];
+ }
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
static int mathutils_matrix_translation_get_index(BaseMathObject *bmo, int col, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- bmo->data[row] = MATRIX_ITEM(self, row, col);
- return 0;
+ bmo->data[row] = MATRIX_ITEM(self, row, col);
+ return 0;
}
static int mathutils_matrix_translation_set_index(BaseMathObject *bmo, int col, int row)
{
- MatrixObject *self = (MatrixObject *)bmo->cb_user;
+ MatrixObject *self = (MatrixObject *)bmo->cb_user;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- MATRIX_ITEM(self, row, col) = bmo->data[row];
+ MATRIX_ITEM(self, row, col) = bmo->data[row];
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
Mathutils_Callback mathutils_matrix_translation_cb = {
- mathutils_matrix_translation_check,
- mathutils_matrix_translation_get,
- mathutils_matrix_translation_set,
- mathutils_matrix_translation_get_index,
- mathutils_matrix_translation_set_index,
+ mathutils_matrix_translation_check,
+ mathutils_matrix_translation_get,
+ mathutils_matrix_translation_set,
+ mathutils_matrix_translation_get_index,
+ mathutils_matrix_translation_set_index,
};
-
/* matrix column callbacks, this is so you can do matrix.translation = Vector() */
/* ----------------------------------mathutils.Matrix() ----------------- */
@@ -352,644 +348,696 @@ Mathutils_Callback mathutils_matrix_translation_cb = {
/* create a new matrix type */
static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "Matrix(): "
- "takes no keyword args");
- return NULL;
- }
-
- switch (PyTuple_GET_SIZE(args)) {
- case 0:
- return Matrix_CreatePyObject(NULL, 4, 4, type);
- case 1:
- {
- PyObject *arg = PyTuple_GET_ITEM(args, 0);
-
- /* Input is now as a sequence of rows so length of sequence
- * is the number of rows */
- /* -1 is an error, size checks will account for this */
- const unsigned short num_row = PySequence_Size(arg);
-
- if (num_row >= 2 && num_row <= 4) {
- PyObject *item = PySequence_GetItem(arg, 0);
- /* Since each item is a row, number of items is the
- * same as the number of columns */
- const unsigned short num_col = PySequence_Size(item);
- Py_XDECREF(item);
-
- if (num_col >= 2 && num_col <= 4) {
- /* sane row & col size, new matrix and assign as slice */
- PyObject *matrix = Matrix_CreatePyObject(NULL, num_col, num_row, type);
- if (Matrix_ass_slice((MatrixObject *)matrix, 0, INT_MAX, arg) == 0) {
- return matrix;
- }
- else { /* matrix ok, slice assignment not */
- Py_DECREF(matrix);
- }
- }
- }
- break;
- }
- }
-
- /* will overwrite error */
- PyErr_SetString(PyExc_TypeError,
- "Matrix(): "
- "expects no args or a single arg containing 2-4 numeric sequences");
- return NULL;
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix(): "
+ "takes no keyword args");
+ return NULL;
+ }
+
+ switch (PyTuple_GET_SIZE(args)) {
+ case 0:
+ return Matrix_CreatePyObject(NULL, 4, 4, type);
+ case 1: {
+ PyObject *arg = PyTuple_GET_ITEM(args, 0);
+
+ /* Input is now as a sequence of rows so length of sequence
+ * is the number of rows */
+ /* -1 is an error, size checks will account for this */
+ const unsigned short num_row = PySequence_Size(arg);
+
+ if (num_row >= 2 && num_row <= 4) {
+ PyObject *item = PySequence_GetItem(arg, 0);
+ /* Since each item is a row, number of items is the
+ * same as the number of columns */
+ const unsigned short num_col = PySequence_Size(item);
+ Py_XDECREF(item);
+
+ if (num_col >= 2 && num_col <= 4) {
+ /* sane row & col size, new matrix and assign as slice */
+ PyObject *matrix = Matrix_CreatePyObject(NULL, num_col, num_row, type);
+ if (Matrix_ass_slice((MatrixObject *)matrix, 0, INT_MAX, arg) == 0) {
+ return matrix;
+ }
+ else { /* matrix ok, slice assignment not */
+ Py_DECREF(matrix);
+ }
+ }
+ }
+ break;
+ }
+ }
+
+ /* will overwrite error */
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix(): "
+ "expects no args or a single arg containing 2-4 numeric sequences");
+ return NULL;
}
static PyObject *matrix__apply_to_copy(PyNoArgsFunction matrix_func, MatrixObject *self)
{
- PyObject *ret = Matrix_copy(self);
- if (ret) {
- PyObject *ret_dummy = matrix_func(ret);
- if (ret_dummy) {
- Py_DECREF(ret_dummy);
- return (PyObject *)ret;
- }
- else { /* error */
- Py_DECREF(ret);
- return NULL;
- }
- }
- else {
- /* copy may fail if the read callback errors out */
- return NULL;
- }
+ PyObject *ret = Matrix_copy(self);
+ if (ret) {
+ PyObject *ret_dummy = matrix_func(ret);
+ if (ret_dummy) {
+ Py_DECREF(ret_dummy);
+ return (PyObject *)ret;
+ }
+ else { /* error */
+ Py_DECREF(ret);
+ return NULL;
+ }
+ }
+ else {
+ /* copy may fail if the read callback errors out */
+ return NULL;
+ }
}
/* when a matrix is 4x4 size but initialized as a 3x3, re-assign values for 4x4 */
static void matrix_3x3_as_4x4(float mat[16])
{
- mat[10] = mat[8];
- mat[9] = mat[7];
- mat[8] = mat[6];
- mat[7] = 0.0f;
- mat[6] = mat[5];
- mat[5] = mat[4];
- mat[4] = mat[3];
- mat[3] = 0.0f;
+ mat[10] = mat[8];
+ mat[9] = mat[7];
+ mat[8] = mat[6];
+ mat[7] = 0.0f;
+ mat[6] = mat[5];
+ mat[5] = mat[4];
+ mat[4] = mat[3];
+ mat[3] = 0.0f;
}
/*-----------------------CLASS-METHODS----------------------------*/
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Identity_doc,
-".. classmethod:: Identity(size)\n"
-"\n"
-" Create an identity matrix.\n"
-"\n"
-" :arg size: The size of the identity matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :return: A new identity matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: Identity(size)\n"
+ "\n"
+ " Create an identity matrix.\n"
+ "\n"
+ " :arg size: The size of the identity matrix to construct [2, 4].\n"
+ " :type size: int\n"
+ " :return: A new identity matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Identity(PyObject *cls, PyObject *args)
{
- int matSize;
+ int matSize;
- if (!PyArg_ParseTuple(args, "i:Matrix.Identity", &matSize)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "i:Matrix.Identity", &matSize)) {
+ return NULL;
+ }
- if (matSize < 2 || matSize > 4) {
- PyErr_SetString(PyExc_RuntimeError,
- "Matrix.Identity(): "
- "size must be between 2 and 4");
- return NULL;
- }
+ if (matSize < 2 || matSize > 4) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Matrix.Identity(): "
+ "size must be between 2 and 4");
+ return NULL;
+ }
- return Matrix_CreatePyObject(NULL, matSize, matSize, (PyTypeObject *)cls);
+ return Matrix_CreatePyObject(NULL, matSize, matSize, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Matrix_Rotation_doc,
-".. classmethod:: Rotation(angle, size, axis)\n"
-"\n"
-" Create a matrix representing a rotation.\n"
-"\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"
-" :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object\n"
-" (optional when size is 2).\n"
-" :type axis: string or :class:`Vector`\n"
-" :return: A new rotation matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: Rotation(angle, size, axis)\n"
+ "\n"
+ " Create a matrix representing a rotation.\n"
+ "\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"
+ " :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object\n"
+ " (optional when size is 2).\n"
+ " :type axis: string or :class:`Vector`\n"
+ " :return: A new rotation matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
{
- PyObject *vec = NULL;
- const char *axis = NULL;
- int matSize;
- double angle; /* use double because of precision problems at high values */
- float mat[16] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f,
- };
-
- if (!PyArg_ParseTuple(args, "di|O:Matrix.Rotation", &angle, &matSize, &vec)) {
- return NULL;
- }
-
- if (vec && PyUnicode_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_ValueError,
- "Matrix.Rotation(): "
- "3rd argument axis value must be a 3D vector "
- "or a string in 'X', 'Y', 'Z'");
- return NULL;
- }
- else {
- /* use the string */
- vec = NULL;
- }
- }
-
- angle = angle_wrap_rad(angle);
-
- if (matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Rotation(): "
- "can only return a 2x2 3x3 or 4x4 matrix");
- return NULL;
- }
- if (matSize == 2 && (vec != NULL)) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Rotation(): "
- "cannot create a 2x2 rotation matrix around arbitrary axis");
- return NULL;
- }
- if ((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Rotation(): "
- "axis of rotation for 3d and 4d matrices is required");
- return NULL;
- }
-
- /* check for valid vector/axis above */
- if (vec) {
- float tvec[3];
-
- if (mathutils_array_parse(tvec, 3, 3, vec, "Matrix.Rotation(angle, size, axis), invalid 'axis' arg") == -1) {
- return NULL;
- }
-
- axis_angle_to_mat3((float (*)[3])mat, tvec, angle);
- }
- else if (matSize == 2) {
- angle_to_mat2((float (*)[2])mat, angle);
-
- }
- else {
- /* valid axis checked above */
- axis_angle_to_mat3_single((float (*)[3])mat, axis[0], angle);
- }
-
- if (matSize == 4) {
- matrix_3x3_as_4x4(mat);
- }
- /* pass to matrix creation */
- return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
+ PyObject *vec = NULL;
+ const char *axis = NULL;
+ int matSize;
+ double angle; /* use double because of precision problems at high values */
+ float mat[16] = {
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ };
+
+ if (!PyArg_ParseTuple(args, "di|O:Matrix.Rotation", &angle, &matSize, &vec)) {
+ return NULL;
+ }
+
+ if (vec && PyUnicode_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_ValueError,
+ "Matrix.Rotation(): "
+ "3rd argument axis value must be a 3D vector "
+ "or a string in 'X', 'Y', 'Z'");
+ return NULL;
+ }
+ else {
+ /* use the string */
+ vec = NULL;
+ }
+ }
+
+ angle = angle_wrap_rad(angle);
+
+ if (matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Rotation(): "
+ "can only return a 2x2 3x3 or 4x4 matrix");
+ return NULL;
+ }
+ if (matSize == 2 && (vec != NULL)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Rotation(): "
+ "cannot create a 2x2 rotation matrix around arbitrary axis");
+ return NULL;
+ }
+ if ((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Rotation(): "
+ "axis of rotation for 3d and 4d matrices is required");
+ return NULL;
+ }
+
+ /* check for valid vector/axis above */
+ if (vec) {
+ float tvec[3];
+
+ if (mathutils_array_parse(
+ tvec, 3, 3, vec, "Matrix.Rotation(angle, size, axis), invalid 'axis' arg") == -1) {
+ return NULL;
+ }
+
+ axis_angle_to_mat3((float(*)[3])mat, tvec, angle);
+ }
+ else if (matSize == 2) {
+ angle_to_mat2((float(*)[2])mat, angle);
+ }
+ else {
+ /* valid axis checked above */
+ axis_angle_to_mat3_single((float(*)[3])mat, axis[0], angle);
+ }
+
+ if (matSize == 4) {
+ matrix_3x3_as_4x4(mat);
+ }
+ /* pass to matrix creation */
+ return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
-
PyDoc_STRVAR(C_Matrix_Translation_doc,
-".. classmethod:: Translation(vector)\n"
-"\n"
-" Create a matrix representing a translation.\n"
-"\n"
-" :arg vector: The translation vector.\n"
-" :type vector: :class:`Vector`\n"
-" :return: An identity matrix with a translation.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: Translation(vector)\n"
+ "\n"
+ " Create a matrix representing a translation.\n"
+ "\n"
+ " :arg vector: The translation vector.\n"
+ " :type vector: :class:`Vector`\n"
+ " :return: An identity matrix with a translation.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Translation(PyObject *cls, PyObject *value)
{
- float mat[4][4];
+ float mat[4][4];
- unit_m4(mat);
+ unit_m4(mat);
- if (mathutils_array_parse(mat[3], 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(
+ mat[3], 3, 4, value, "mathutils.Matrix.Translation(vector), invalid vector arg") == -1) {
+ return NULL;
+ }
- return Matrix_CreatePyObject(&mat[0][0], 4, 4, (PyTypeObject *)cls);
+ return Matrix_CreatePyObject(&mat[0][0], 4, 4, (PyTypeObject *)cls);
}
/* ----------------------------------mathutils.Matrix.Scale() ------------- */
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_Scale_doc,
-".. classmethod:: Scale(factor, size, axis)\n"
-"\n"
-" Create a matrix representing a scaling.\n"
-"\n"
-" :arg factor: The factor of scaling to apply.\n"
-" :type factor: float\n"
-" :arg size: The size of the scale matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :arg axis: Direction to influence scale. (optional).\n"
-" :type axis: :class:`Vector`\n"
-" :return: A new scale matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: Scale(factor, size, axis)\n"
+ "\n"
+ " Create a matrix representing a scaling.\n"
+ "\n"
+ " :arg factor: The factor of scaling to apply.\n"
+ " :type factor: float\n"
+ " :arg size: The size of the scale matrix to construct [2, 4].\n"
+ " :type size: int\n"
+ " :arg axis: Direction to influence scale. (optional).\n"
+ " :type axis: :class:`Vector`\n"
+ " :return: A new scale matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
{
- PyObject *vec = NULL;
- int vec_size;
- float tvec[3];
- float factor;
- int matSize;
- float mat[16] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f,
- };
-
- if (!PyArg_ParseTuple(args, "fi|O:Matrix.Scale", &factor, &matSize, &vec)) {
- return NULL;
- }
- if (matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Scale(): "
- "can only return a 2x2 3x3 or 4x4 matrix");
- return NULL;
- }
- if (vec) {
- vec_size = (matSize == 2 ? 2 : 3);
- if (mathutils_array_parse(tvec, vec_size, vec_size, vec,
- "Matrix.Scale(factor, size, axis), invalid 'axis' arg") == -1)
- {
- return NULL;
- }
- }
- if (vec == NULL) { /* scaling along axis */
- if (matSize == 2) {
- mat[0] = factor;
- mat[3] = factor;
- }
- else {
- mat[0] = factor;
- mat[4] = factor;
- mat[8] = factor;
- }
- }
- else {
- /* scaling in arbitrary direction
- * normalize arbitrary axis */
- float norm = 0.0f;
- int x;
- for (x = 0; x < vec_size; x++) {
- norm += tvec[x] * tvec[x];
- }
- norm = sqrtf(norm);
- for (x = 0; x < vec_size; x++) {
- tvec[x] /= norm;
- }
- if (matSize == 2) {
- mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
- mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
- mat[2] = ((factor - 1) * (tvec[0] * tvec[1]));
- mat[3] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
- }
- else {
- mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
- mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
- mat[2] = ((factor - 1) * (tvec[0] * tvec[2]));
- mat[3] = ((factor - 1) * (tvec[0] * tvec[1]));
- mat[4] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
- mat[5] = ((factor - 1) * (tvec[1] * tvec[2]));
- mat[6] = ((factor - 1) * (tvec[0] * tvec[2]));
- mat[7] = ((factor - 1) * (tvec[1] * tvec[2]));
- mat[8] = 1 + ((factor - 1) * (tvec[2] * tvec[2]));
- }
- }
- if (matSize == 4) {
- matrix_3x3_as_4x4(mat);
- }
- /* pass to matrix creation */
- return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
+ PyObject *vec = NULL;
+ int vec_size;
+ float tvec[3];
+ float factor;
+ int matSize;
+ float mat[16] = {
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ };
+
+ if (!PyArg_ParseTuple(args, "fi|O:Matrix.Scale", &factor, &matSize, &vec)) {
+ return NULL;
+ }
+ if (matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Scale(): "
+ "can only return a 2x2 3x3 or 4x4 matrix");
+ return NULL;
+ }
+ if (vec) {
+ vec_size = (matSize == 2 ? 2 : 3);
+ if (mathutils_array_parse(tvec,
+ vec_size,
+ vec_size,
+ vec,
+ "Matrix.Scale(factor, size, axis), invalid 'axis' arg") == -1) {
+ return NULL;
+ }
+ }
+ if (vec == NULL) { /* scaling along axis */
+ if (matSize == 2) {
+ mat[0] = factor;
+ mat[3] = factor;
+ }
+ else {
+ mat[0] = factor;
+ mat[4] = factor;
+ mat[8] = factor;
+ }
+ }
+ else {
+ /* scaling in arbitrary direction
+ * normalize arbitrary axis */
+ float norm = 0.0f;
+ int x;
+ for (x = 0; x < vec_size; x++) {
+ norm += tvec[x] * tvec[x];
+ }
+ norm = sqrtf(norm);
+ for (x = 0; x < vec_size; x++) {
+ tvec[x] /= norm;
+ }
+ if (matSize == 2) {
+ mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
+ mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
+ mat[2] = ((factor - 1) * (tvec[0] * tvec[1]));
+ mat[3] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
+ }
+ else {
+ mat[0] = 1 + ((factor - 1) * (tvec[0] * tvec[0]));
+ mat[1] = ((factor - 1) * (tvec[0] * tvec[1]));
+ mat[2] = ((factor - 1) * (tvec[0] * tvec[2]));
+ mat[3] = ((factor - 1) * (tvec[0] * tvec[1]));
+ mat[4] = 1 + ((factor - 1) * (tvec[1] * tvec[1]));
+ mat[5] = ((factor - 1) * (tvec[1] * tvec[2]));
+ mat[6] = ((factor - 1) * (tvec[0] * tvec[2]));
+ mat[7] = ((factor - 1) * (tvec[1] * tvec[2]));
+ mat[8] = 1 + ((factor - 1) * (tvec[2] * tvec[2]));
+ }
+ }
+ if (matSize == 4) {
+ matrix_3x3_as_4x4(mat);
+ }
+ /* pass to matrix creation */
+ return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
/* ----------------------------------mathutils.Matrix.OrthoProjection() --- */
/* mat is a 1D array of floats - row[0][0], row[0][1], row[1][0], etc. */
PyDoc_STRVAR(C_Matrix_OrthoProjection_doc,
-".. classmethod:: OrthoProjection(axis, size)\n"
-"\n"
-" Create a matrix to represent an orthographic projection.\n"
-"\n"
-" :arg axis: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
-" where a single axis is for a 2D matrix.\n"
-" Or a vector for an arbitrary axis\n"
-" :type axis: string or :class:`Vector`\n"
-" :arg size: The size of the projection matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :return: A new projection matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: OrthoProjection(axis, size)\n"
+ "\n"
+ " Create a matrix to represent an orthographic projection.\n"
+ "\n"
+ " :arg axis: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
+ " where a single axis is for a 2D matrix.\n"
+ " Or a vector for an arbitrary axis\n"
+ " :type axis: string or :class:`Vector`\n"
+ " :arg size: The size of the projection matrix to construct [2, 4].\n"
+ " :type size: int\n"
+ " :return: A new projection matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
{
- PyObject *axis;
-
- int matSize, x;
- float norm = 0.0f;
- float mat[16] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f,
- };
-
- if (!PyArg_ParseTuple(args, "Oi:Matrix.OrthoProjection", &axis, &matSize)) {
- return NULL;
- }
- if (matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.OrthoProjection(): "
- "can only return a 2x2 3x3 or 4x4 matrix");
- return NULL;
- }
-
- if (PyUnicode_Check(axis)) { /* ortho projection onto cardinal plane */
- Py_ssize_t plane_len;
- const char *plane = _PyUnicode_AsStringAndSize(axis, &plane_len);
- if (matSize == 2) {
- if (plane_len == 1 && plane[0] == 'X') {
- mat[0] = 1.0f;
- }
- else if (plane_len == 1 && plane[0] == 'Y') {
- mat[3] = 1.0f;
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "Matrix.OrthoProjection(): "
- "unknown plane, expected: X, Y, not '%.200s'",
- plane);
- return NULL;
- }
- }
- else {
- if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Y') {
- mat[0] = 1.0f;
- mat[4] = 1.0f;
- }
- else if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Z') {
- mat[0] = 1.0f;
- mat[8] = 1.0f;
- }
- else if (plane_len == 2 && plane[0] == 'Y' && plane[1] == 'Z') {
- mat[4] = 1.0f;
- mat[8] = 1.0f;
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "Matrix.OrthoProjection(): "
- "unknown plane, expected: XY, XZ, YZ, not '%.200s'",
- plane);
- return NULL;
- }
- }
- }
- else {
- /* arbitrary plane */
-
- int vec_size = (matSize == 2 ? 2 : 3);
- float tvec[4];
-
- if (mathutils_array_parse(tvec, vec_size, vec_size, axis,
- "Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1)
- {
- return NULL;
- }
-
- /* normalize arbitrary axis */
- for (x = 0; x < vec_size; x++) {
- norm += tvec[x] * tvec[x];
- }
- norm = sqrtf(norm);
- for (x = 0; x < vec_size; x++) {
- tvec[x] /= norm;
- }
- if (matSize == 2) {
- mat[0] = 1 - (tvec[0] * tvec[0]);
- mat[1] = - (tvec[0] * tvec[1]);
- mat[2] = - (tvec[0] * tvec[1]);
- mat[3] = 1 - (tvec[1] * tvec[1]);
- }
- else if (matSize > 2) {
- mat[0] = 1 - (tvec[0] * tvec[0]);
- mat[1] = - (tvec[0] * tvec[1]);
- mat[2] = - (tvec[0] * tvec[2]);
- mat[3] = - (tvec[0] * tvec[1]);
- mat[4] = 1 - (tvec[1] * tvec[1]);
- mat[5] = - (tvec[1] * tvec[2]);
- mat[6] = - (tvec[0] * tvec[2]);
- mat[7] = - (tvec[1] * tvec[2]);
- mat[8] = 1 - (tvec[2] * tvec[2]);
- }
- }
- if (matSize == 4) {
- matrix_3x3_as_4x4(mat);
- }
- /* pass to matrix creation */
- return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
+ PyObject *axis;
+
+ int matSize, x;
+ float norm = 0.0f;
+ float mat[16] = {
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ };
+
+ if (!PyArg_ParseTuple(args, "Oi:Matrix.OrthoProjection", &axis, &matSize)) {
+ return NULL;
+ }
+ if (matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.OrthoProjection(): "
+ "can only return a 2x2 3x3 or 4x4 matrix");
+ return NULL;
+ }
+
+ if (PyUnicode_Check(axis)) { /* ortho projection onto cardinal plane */
+ Py_ssize_t plane_len;
+ const char *plane = _PyUnicode_AsStringAndSize(axis, &plane_len);
+ if (matSize == 2) {
+ if (plane_len == 1 && plane[0] == 'X') {
+ mat[0] = 1.0f;
+ }
+ else if (plane_len == 1 && plane[0] == 'Y') {
+ mat[3] = 1.0f;
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "Matrix.OrthoProjection(): "
+ "unknown plane, expected: X, Y, not '%.200s'",
+ plane);
+ return NULL;
+ }
+ }
+ else {
+ if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Y') {
+ mat[0] = 1.0f;
+ mat[4] = 1.0f;
+ }
+ else if (plane_len == 2 && plane[0] == 'X' && plane[1] == 'Z') {
+ mat[0] = 1.0f;
+ mat[8] = 1.0f;
+ }
+ else if (plane_len == 2 && plane[0] == 'Y' && plane[1] == 'Z') {
+ mat[4] = 1.0f;
+ mat[8] = 1.0f;
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "Matrix.OrthoProjection(): "
+ "unknown plane, expected: XY, XZ, YZ, not '%.200s'",
+ plane);
+ return NULL;
+ }
+ }
+ }
+ else {
+ /* arbitrary plane */
+
+ int vec_size = (matSize == 2 ? 2 : 3);
+ float tvec[4];
+
+ if (mathutils_array_parse(tvec,
+ vec_size,
+ vec_size,
+ axis,
+ "Matrix.OrthoProjection(axis, size), invalid 'axis' arg") == -1) {
+ return NULL;
+ }
+
+ /* normalize arbitrary axis */
+ for (x = 0; x < vec_size; x++) {
+ norm += tvec[x] * tvec[x];
+ }
+ norm = sqrtf(norm);
+ for (x = 0; x < vec_size; x++) {
+ tvec[x] /= norm;
+ }
+ if (matSize == 2) {
+ mat[0] = 1 - (tvec[0] * tvec[0]);
+ mat[1] = -(tvec[0] * tvec[1]);
+ mat[2] = -(tvec[0] * tvec[1]);
+ mat[3] = 1 - (tvec[1] * tvec[1]);
+ }
+ else if (matSize > 2) {
+ mat[0] = 1 - (tvec[0] * tvec[0]);
+ mat[1] = -(tvec[0] * tvec[1]);
+ mat[2] = -(tvec[0] * tvec[2]);
+ mat[3] = -(tvec[0] * tvec[1]);
+ mat[4] = 1 - (tvec[1] * tvec[1]);
+ mat[5] = -(tvec[1] * tvec[2]);
+ mat[6] = -(tvec[0] * tvec[2]);
+ mat[7] = -(tvec[1] * tvec[2]);
+ mat[8] = 1 - (tvec[2] * tvec[2]);
+ }
+ }
+ if (matSize == 4) {
+ matrix_3x3_as_4x4(mat);
+ }
+ /* pass to matrix creation */
+ return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Matrix_Shear_doc,
-".. classmethod:: Shear(plane, size, factor)\n"
-"\n"
-" Create a matrix to represent an shear transformation.\n"
-"\n"
-" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
-" where a single axis is for a 2D matrix only.\n"
-" :type plane: string\n"
-" :arg size: The size of the shear matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :arg factor: The factor of shear to apply. For a 3 or 4 *size* matrix\n"
-" pass a pair of floats corresponding with the *plane* axis.\n"
-" :type factor: float or float pair\n"
-" :return: A new shear matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. classmethod:: Shear(plane, size, factor)\n"
+ "\n"
+ " Create a matrix to represent an shear transformation.\n"
+ "\n"
+ " :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'],\n"
+ " where a single axis is for a 2D matrix only.\n"
+ " :type plane: string\n"
+ " :arg size: The size of the shear matrix to construct [2, 4].\n"
+ " :type size: int\n"
+ " :arg factor: The factor of shear to apply. For a 3 or 4 *size* matrix\n"
+ " pass a pair of floats corresponding with the *plane* axis.\n"
+ " :type factor: float or float pair\n"
+ " :return: A new shear matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
{
- int matSize;
- const char *plane;
- PyObject *fac;
- float mat[16] = {
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 1.0f,
- };
-
- if (!PyArg_ParseTuple(args, "siO:Matrix.Shear", &plane, &matSize, &fac)) {
- return NULL;
- }
- if (matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Shear(): "
- "can only return a 2x2 3x3 or 4x4 matrix");
- return NULL;
- }
-
- if (matSize == 2) {
- float const factor = PyFloat_AsDouble(fac);
-
- if (factor == -1.0f && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "Matrix.Shear(): "
- "the factor to be a float");
- return NULL;
- }
-
- /* unit */
- mat[0] = 1.0f;
- mat[3] = 1.0f;
-
- if (STREQ(plane, "X")) {
- mat[2] = factor;
- }
- else if (STREQ(plane, "Y")) {
- mat[1] = factor;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Shear(): "
- "expected: X, Y or wrong matrix size for shearing plane");
- return NULL;
- }
- }
- else {
- /* 3 or 4, apply as 3x3, resize later if needed */
- float factor[2];
-
- if (mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") == -1) {
- return NULL;
- }
-
- /* unit */
- mat[0] = 1.0f;
- mat[4] = 1.0f;
- mat[8] = 1.0f;
-
- if (STREQ(plane, "XY")) {
- mat[6] = factor[0];
- mat[7] = factor[1];
- }
- else if (STREQ(plane, "XZ")) {
- mat[3] = factor[0];
- mat[5] = factor[1];
- }
- else if (STREQ(plane, "YZ")) {
- mat[1] = factor[0];
- mat[2] = factor[1];
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.Shear(): "
- "expected: X, Y, XY, XZ, YZ");
- return NULL;
- }
- }
-
- if (matSize == 4) {
- matrix_3x3_as_4x4(mat);
- }
- /* pass to matrix creation */
- return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
+ int matSize;
+ const char *plane;
+ PyObject *fac;
+ float mat[16] = {
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ };
+
+ if (!PyArg_ParseTuple(args, "siO:Matrix.Shear", &plane, &matSize, &fac)) {
+ return NULL;
+ }
+ if (matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Shear(): "
+ "can only return a 2x2 3x3 or 4x4 matrix");
+ return NULL;
+ }
+
+ if (matSize == 2) {
+ float const factor = PyFloat_AsDouble(fac);
+
+ if (factor == -1.0f && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix.Shear(): "
+ "the factor to be a float");
+ return NULL;
+ }
+
+ /* unit */
+ mat[0] = 1.0f;
+ mat[3] = 1.0f;
+
+ if (STREQ(plane, "X")) {
+ mat[2] = factor;
+ }
+ else if (STREQ(plane, "Y")) {
+ mat[1] = factor;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Shear(): "
+ "expected: X, Y or wrong matrix size for shearing plane");
+ return NULL;
+ }
+ }
+ else {
+ /* 3 or 4, apply as 3x3, resize later if needed */
+ float factor[2];
+
+ if (mathutils_array_parse(factor, 2, 2, fac, "Matrix.Shear()") == -1) {
+ return NULL;
+ }
+
+ /* unit */
+ mat[0] = 1.0f;
+ mat[4] = 1.0f;
+ mat[8] = 1.0f;
+
+ if (STREQ(plane, "XY")) {
+ mat[6] = factor[0];
+ mat[7] = factor[1];
+ }
+ else if (STREQ(plane, "XZ")) {
+ mat[3] = factor[0];
+ mat[5] = factor[1];
+ }
+ else if (STREQ(plane, "YZ")) {
+ mat[1] = factor[0];
+ mat[2] = factor[1];
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.Shear(): "
+ "expected: X, Y, XY, XZ, YZ");
+ return NULL;
+ }
+ }
+
+ if (matSize == 4) {
+ matrix_3x3_as_4x4(mat);
+ }
+ /* pass to matrix creation */
+ return Matrix_CreatePyObject(mat, matSize, matSize, (PyTypeObject *)cls);
}
void matrix_as_3x3(float mat[3][3], MatrixObject *self)
{
- copy_v3_v3(mat[0], MATRIX_COL_PTR(self, 0));
- copy_v3_v3(mat[1], MATRIX_COL_PTR(self, 1));
- copy_v3_v3(mat[2], MATRIX_COL_PTR(self, 2));
+ copy_v3_v3(mat[0], MATRIX_COL_PTR(self, 0));
+ copy_v3_v3(mat[1], MATRIX_COL_PTR(self, 1));
+ copy_v3_v3(mat[2], MATRIX_COL_PTR(self, 2));
}
static void matrix_copy(MatrixObject *mat_dst, const MatrixObject *mat_src)
{
- BLI_assert((mat_dst->num_col == mat_src->num_col) &&
- (mat_dst->num_row == mat_src->num_row));
- BLI_assert(mat_dst != mat_src);
+ BLI_assert((mat_dst->num_col == mat_src->num_col) && (mat_dst->num_row == mat_src->num_row));
+ BLI_assert(mat_dst != mat_src);
- memcpy(mat_dst->matrix, mat_src->matrix, sizeof(float) * (mat_dst->num_col * mat_dst->num_row));
+ memcpy(mat_dst->matrix, mat_src->matrix, sizeof(float) * (mat_dst->num_col * mat_dst->num_row));
}
/* transposes memory layout, rol/col's don't have to match */
static void matrix_transpose_internal(float mat_dst_fl[], const MatrixObject *mat_src)
{
- unsigned short col, row;
- unsigned int i = 0;
+ unsigned short col, row;
+ unsigned int i = 0;
- for (row = 0; row < mat_src->num_row; row++) {
- for (col = 0; col < mat_src->num_col; col++) {
- mat_dst_fl[i++] = MATRIX_ITEM(mat_src, row, col);
- }
- }
+ for (row = 0; row < mat_src->num_row; row++) {
+ for (col = 0; col < mat_src->num_col; col++) {
+ mat_dst_fl[i++] = MATRIX_ITEM(mat_src, row, col);
+ }
+ }
}
/* assumes rowsize == colsize is checked and the read callback has run */
static float matrix_determinant_internal(const MatrixObject *self)
{
- if (self->num_col == 2) {
- return determinant_m2(MATRIX_ITEM(self, 0, 0), MATRIX_ITEM(self, 0, 1),
- MATRIX_ITEM(self, 1, 0), MATRIX_ITEM(self, 1, 1));
- }
- else if (self->num_col == 3) {
- return determinant_m3(MATRIX_ITEM(self, 0, 0), MATRIX_ITEM(self, 0, 1), MATRIX_ITEM(self, 0, 2),
- MATRIX_ITEM(self, 1, 0), MATRIX_ITEM(self, 1, 1), MATRIX_ITEM(self, 1, 2),
- MATRIX_ITEM(self, 2, 0), MATRIX_ITEM(self, 2, 1), MATRIX_ITEM(self, 2, 2));
- }
- else {
- return determinant_m4((float (*)[4])self->matrix);
- }
+ if (self->num_col == 2) {
+ return determinant_m2(MATRIX_ITEM(self, 0, 0),
+ MATRIX_ITEM(self, 0, 1),
+ MATRIX_ITEM(self, 1, 0),
+ MATRIX_ITEM(self, 1, 1));
+ }
+ else if (self->num_col == 3) {
+ return determinant_m3(MATRIX_ITEM(self, 0, 0),
+ MATRIX_ITEM(self, 0, 1),
+ MATRIX_ITEM(self, 0, 2),
+ MATRIX_ITEM(self, 1, 0),
+ MATRIX_ITEM(self, 1, 1),
+ MATRIX_ITEM(self, 1, 2),
+ MATRIX_ITEM(self, 2, 0),
+ MATRIX_ITEM(self, 2, 1),
+ MATRIX_ITEM(self, 2, 2));
+ }
+ else {
+ return determinant_m4((float(*)[4])self->matrix);
+ }
}
static void adjoint_matrix_n(float *mat_dst, const float *mat_src, const unsigned short dim)
{
- /* calculate the classical adjoint */
- switch (dim) {
- case 2:
- {
- adjoint_m2_m2((float (*)[2])mat_dst, (float (*)[2])mat_src);
- break;
- }
- case 3:
- {
- adjoint_m3_m3((float (*)[3])mat_dst, (float (*)[3])mat_src);
- break;
- }
- case 4:
- {
- adjoint_m4_m4((float (*)[4])mat_dst, (float (*)[4])mat_src);
- break;
- }
- default:
- BLI_assert(0);
- }
-}
-
-static void matrix_invert_with_det_n_internal(float *mat_dst, const float *mat_src, const float det, const unsigned short dim)
-{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- unsigned short i, j, k;
-
- BLI_assert(det != 0.0f);
-
- adjoint_matrix_n(mat, mat_src, dim);
-
- /* divide by determinant & set values */
- k = 0;
- for (i = 0; i < dim; i++) { /* num_col */
- for (j = 0; j < dim; j++) { /* num_row */
- mat_dst[MATRIX_ITEM_INDEX_NUMROW(dim, j, i)] = mat[k++] / det;
- }
- }
+ /* calculate the classical adjoint */
+ switch (dim) {
+ case 2: {
+ adjoint_m2_m2((float(*)[2])mat_dst, (float(*)[2])mat_src);
+ break;
+ }
+ case 3: {
+ adjoint_m3_m3((float(*)[3])mat_dst, (float(*)[3])mat_src);
+ break;
+ }
+ case 4: {
+ adjoint_m4_m4((float(*)[4])mat_dst, (float(*)[4])mat_src);
+ break;
+ }
+ default:
+ BLI_assert(0);
+ }
+}
+
+static void matrix_invert_with_det_n_internal(float *mat_dst,
+ const float *mat_src,
+ const float det,
+ const unsigned short dim)
+{
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ unsigned short i, j, k;
+
+ BLI_assert(det != 0.0f);
+
+ adjoint_matrix_n(mat, mat_src, dim);
+
+ /* divide by determinant & set values */
+ k = 0;
+ for (i = 0; i < dim; i++) { /* num_col */
+ for (j = 0; j < dim; j++) { /* num_row */
+ mat_dst[MATRIX_ITEM_INDEX_NUMROW(dim, j, i)] = mat[k++] / det;
+ }
+ }
}
/**
@@ -997,17 +1045,17 @@ static void matrix_invert_with_det_n_internal(float *mat_dst, const float *mat_s
*/
static bool matrix_invert_internal(const MatrixObject *self, float *r_mat)
{
- float det;
- BLI_assert(self->num_col == self->num_row);
- det = matrix_determinant_internal(self);
+ float det;
+ BLI_assert(self->num_col == self->num_row);
+ det = matrix_determinant_internal(self);
- if (det != 0.0f) {
- matrix_invert_with_det_n_internal(r_mat, self->matrix, det, self->num_col);
- return true;
- }
- else {
- return false;
- }
+ if (det != 0.0f) {
+ matrix_invert_with_det_n_internal(r_mat, self->matrix, det, self->num_col);
+ return true;
+ }
+ else {
+ return false;
+ }
}
/**
@@ -1016,358 +1064,347 @@ static bool matrix_invert_internal(const MatrixObject *self, float *r_mat)
*/
static void matrix_invert_safe_internal(const MatrixObject *self, float *r_mat)
{
- float det;
- float *in_mat = self->matrix;
- BLI_assert(self->num_col == self->num_row);
- det = matrix_determinant_internal(self);
-
- if (det == 0.0f) {
- const float eps = PSEUDOINVERSE_EPSILON;
-
- /* We will copy self->matrix into r_mat (if needed), and modify it in place to add diagonal epsilon. */
- in_mat = r_mat;
-
- switch (self->num_col) {
- case 2:
- {
- float (*mat)[2] = (float (*)[2])in_mat;
-
- if (in_mat != self->matrix) {
- copy_m2_m2(mat, (float (*)[2])self->matrix);
- }
- mat[0][0] += eps;
- mat[1][1] += eps;
-
- if (UNLIKELY((det = determinant_m2(mat[0][0], mat[0][1], mat[1][0], mat[1][1])) == 0.0f)) {
- unit_m2(mat);
- det = 1.0f;
- }
- break;
- }
- case 3:
- {
- float (*mat)[3] = (float (*)[3])in_mat;
-
- if (in_mat != self->matrix) {
- copy_m3_m3(mat, (float (*)[3])self->matrix);
- }
- mat[0][0] += eps;
- mat[1][1] += eps;
- mat[2][2] += eps;
-
- if (UNLIKELY((det = determinant_m3_array(mat)) == 0.0f)) {
- unit_m3(mat);
- det = 1.0f;
- }
- break;
- }
- case 4:
- {
- float (*mat)[4] = (float (*)[4])in_mat;
-
- if (in_mat != self->matrix) {
- copy_m4_m4(mat, (float (*)[4])self->matrix);
- }
- mat[0][0] += eps;
- mat[1][1] += eps;
- mat[2][2] += eps;
- mat[3][3] += eps;
-
- if (UNLIKELY(det = determinant_m4(mat)) == 0.0f) {
- unit_m4(mat);
- det = 1.0f;
- }
- break;
- }
- default:
- BLI_assert(0);
- }
- }
-
- matrix_invert_with_det_n_internal(r_mat, in_mat, det, self->num_col);
+ float det;
+ float *in_mat = self->matrix;
+ BLI_assert(self->num_col == self->num_row);
+ det = matrix_determinant_internal(self);
+
+ if (det == 0.0f) {
+ const float eps = PSEUDOINVERSE_EPSILON;
+
+ /* We will copy self->matrix into r_mat (if needed), and modify it in place to add diagonal epsilon. */
+ in_mat = r_mat;
+
+ switch (self->num_col) {
+ case 2: {
+ float(*mat)[2] = (float(*)[2])in_mat;
+
+ if (in_mat != self->matrix) {
+ copy_m2_m2(mat, (float(*)[2])self->matrix);
+ }
+ mat[0][0] += eps;
+ mat[1][1] += eps;
+
+ if (UNLIKELY((det = determinant_m2(mat[0][0], mat[0][1], mat[1][0], mat[1][1])) == 0.0f)) {
+ unit_m2(mat);
+ det = 1.0f;
+ }
+ break;
+ }
+ case 3: {
+ float(*mat)[3] = (float(*)[3])in_mat;
+
+ if (in_mat != self->matrix) {
+ copy_m3_m3(mat, (float(*)[3])self->matrix);
+ }
+ mat[0][0] += eps;
+ mat[1][1] += eps;
+ mat[2][2] += eps;
+
+ if (UNLIKELY((det = determinant_m3_array(mat)) == 0.0f)) {
+ unit_m3(mat);
+ det = 1.0f;
+ }
+ break;
+ }
+ case 4: {
+ float(*mat)[4] = (float(*)[4])in_mat;
+
+ if (in_mat != self->matrix) {
+ copy_m4_m4(mat, (float(*)[4])self->matrix);
+ }
+ mat[0][0] += eps;
+ mat[1][1] += eps;
+ mat[2][2] += eps;
+ mat[3][3] += eps;
+
+ if (UNLIKELY(det = determinant_m4(mat)) == 0.0f) {
+ unit_m4(mat);
+ det = 1.0f;
+ }
+ break;
+ }
+ default:
+ BLI_assert(0);
+ }
+ }
+
+ matrix_invert_with_det_n_internal(r_mat, in_mat, det, self->num_col);
}
-
/*-----------------------------METHODS----------------------------*/
PyDoc_STRVAR(Matrix_to_quaternion_doc,
-".. method:: to_quaternion()\n"
-"\n"
-" Return a quaternion representation of the rotation matrix.\n"
-"\n"
-" :return: Quaternion representation of the rotation matrix.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. method:: to_quaternion()\n"
+ "\n"
+ " Return a quaternion representation of the rotation matrix.\n"
+ "\n"
+ " :return: Quaternion representation of the rotation matrix.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Matrix_to_quaternion(MatrixObject *self)
{
- float quat[4];
+ float quat[4];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- /* must be 3-4 cols, 3-4 rows, square matrix */
- if ((self->num_row < 3) || (self->num_col < 3) || (self->num_row != self->num_col)) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_quat(): "
- "inappropriate matrix size - expects 3x3 or 4x4 matrix");
- return NULL;
- }
- if (self->num_row == 3) {
- mat3_to_quat(quat, (float (*)[3])self->matrix);
- }
- else {
- mat4_to_quat(quat, (float (*)[4])self->matrix);
- }
+ /* must be 3-4 cols, 3-4 rows, square matrix */
+ if ((self->num_row < 3) || (self->num_col < 3) || (self->num_row != self->num_col)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.to_quat(): "
+ "inappropriate matrix size - expects 3x3 or 4x4 matrix");
+ return NULL;
+ }
+ if (self->num_row == 3) {
+ mat3_to_quat(quat, (float(*)[3])self->matrix);
+ }
+ else {
+ mat4_to_quat(quat, (float(*)[4])self->matrix);
+ }
- return Quaternion_CreatePyObject(quat, NULL);
+ return Quaternion_CreatePyObject(quat, NULL);
}
/*---------------------------matrix.toEuler() --------------------*/
PyDoc_STRVAR(Matrix_to_euler_doc,
-".. method:: to_euler(order, euler_compat)\n"
-"\n"
-" Return an Euler representation of the rotation matrix\n"
-" (3x3 or 4x4 matrix only).\n"
-"\n"
-" :arg order: Optional rotation order argument in\n"
-" ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
-" :type order: string\n"
-" :arg euler_compat: Optional euler argument the new euler will be made\n"
-" compatible with (no axis flipping between them).\n"
-" Useful for converting a series of matrices to animation curves.\n"
-" :type euler_compat: :class:`Euler`\n"
-" :return: Euler representation of the matrix.\n"
-" :rtype: :class:`Euler`\n"
-);
+ ".. method:: to_euler(order, euler_compat)\n"
+ "\n"
+ " Return an Euler representation of the rotation matrix\n"
+ " (3x3 or 4x4 matrix only).\n"
+ "\n"
+ " :arg order: Optional rotation order argument in\n"
+ " ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
+ " :type order: string\n"
+ " :arg euler_compat: Optional euler argument the new euler will be made\n"
+ " compatible with (no axis flipping between them).\n"
+ " Useful for converting a series of matrices to animation curves.\n"
+ " :type euler_compat: :class:`Euler`\n"
+ " :return: Euler representation of the matrix.\n"
+ " :rtype: :class:`Euler`\n");
static PyObject *Matrix_to_euler(MatrixObject *self, PyObject *args)
{
- const char *order_str = NULL;
- short order = EULER_ORDER_XYZ;
- float eul[3], eul_compatf[3];
- EulerObject *eul_compat = NULL;
-
- float mat[3][3];
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
- return NULL;
- }
-
- if (eul_compat) {
- if (BaseMath_ReadCallback(eul_compat) == -1) {
- return NULL;
- }
-
- copy_v3_v3(eul_compatf, eul_compat->eul);
- }
-
- /*must be 3-4 cols, 3-4 rows, square matrix */
- if (self->num_row == 3 && self->num_col == 3) {
- copy_m3_m3(mat, (float (*)[3])self->matrix);
- }
- else if (self->num_row == 4 && self->num_col == 4) {
- copy_m3_m4(mat, (float (*)[4])self->matrix);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_euler(): "
- "inappropriate matrix size - expects 3x3 or 4x4 matrix");
- return NULL;
- }
-
- if (order_str) {
- order = euler_order_from_string(order_str, "Matrix.to_euler()");
-
- if (order == -1) {
- return NULL;
- }
- }
-
- normalize_m3(mat);
-
- if (eul_compat) {
- if (order == 1) {
- mat3_normalized_to_compatible_eul(eul, eul_compatf, mat);
- }
- else {
- mat3_normalized_to_compatible_eulO(eul, eul_compatf, order, mat);
- }
- }
- else {
- if (order == 1) {
- mat3_normalized_to_eul(eul, mat);
- }
- else {
- mat3_normalized_to_eulO(eul, order, mat);
- }
- }
-
- return Euler_CreatePyObject(eul, order, NULL);
+ const char *order_str = NULL;
+ short order = EULER_ORDER_XYZ;
+ float eul[3], eul_compatf[3];
+ EulerObject *eul_compat = NULL;
+
+ float mat[3][3];
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
+ return NULL;
+ }
+
+ if (eul_compat) {
+ if (BaseMath_ReadCallback(eul_compat) == -1) {
+ return NULL;
+ }
+
+ copy_v3_v3(eul_compatf, eul_compat->eul);
+ }
+
+ /*must be 3-4 cols, 3-4 rows, square matrix */
+ if (self->num_row == 3 && self->num_col == 3) {
+ copy_m3_m3(mat, (float(*)[3])self->matrix);
+ }
+ else if (self->num_row == 4 && self->num_col == 4) {
+ copy_m3_m4(mat, (float(*)[4])self->matrix);
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.to_euler(): "
+ "inappropriate matrix size - expects 3x3 or 4x4 matrix");
+ return NULL;
+ }
+
+ if (order_str) {
+ order = euler_order_from_string(order_str, "Matrix.to_euler()");
+
+ if (order == -1) {
+ return NULL;
+ }
+ }
+
+ normalize_m3(mat);
+
+ if (eul_compat) {
+ if (order == 1) {
+ mat3_normalized_to_compatible_eul(eul, eul_compatf, mat);
+ }
+ else {
+ mat3_normalized_to_compatible_eulO(eul, eul_compatf, order, mat);
+ }
+ }
+ else {
+ if (order == 1) {
+ mat3_normalized_to_eul(eul, mat);
+ }
+ else {
+ mat3_normalized_to_eulO(eul, order, mat);
+ }
+ }
+
+ return Euler_CreatePyObject(eul, order, NULL);
}
PyDoc_STRVAR(Matrix_resize_4x4_doc,
-".. method:: resize_4x4()\n"
-"\n"
-" Resize the matrix to 4x4.\n"
-);
+ ".. method:: resize_4x4()\n"
+ "\n"
+ " Resize the matrix to 4x4.\n");
static PyObject *Matrix_resize_4x4(MatrixObject *self)
{
- float mat[4][4];
- int col;
+ float mat[4][4];
+ int col;
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.resize_4x4(): "
- "cannot resize wrapped data - make a copy and resize that");
- return NULL;
- }
- if (self->cb_user) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.resize_4x4(): "
- "cannot resize owned data - make a copy and resize that");
- return NULL;
- }
+ if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.resize_4x4(): "
+ "cannot resize wrapped data - make a copy and resize that");
+ return NULL;
+ }
+ if (self->cb_user) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.resize_4x4(): "
+ "cannot resize owned data - make a copy and resize that");
+ return NULL;
+ }
- self->matrix = PyMem_Realloc(self->matrix, (sizeof(float) * (MATRIX_MAX_DIM * MATRIX_MAX_DIM)));
- if (self->matrix == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Matrix.resize_4x4(): "
- "problem allocating pointer space");
- return NULL;
- }
+ self->matrix = PyMem_Realloc(self->matrix, (sizeof(float) * (MATRIX_MAX_DIM * MATRIX_MAX_DIM)));
+ if (self->matrix == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Matrix.resize_4x4(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- unit_m4(mat);
+ unit_m4(mat);
- for (col = 0; col < self->num_col; col++) {
- memcpy(mat[col], MATRIX_COL_PTR(self, col), self->num_row * sizeof(float));
- }
+ for (col = 0; col < self->num_col; col++) {
+ memcpy(mat[col], MATRIX_COL_PTR(self, col), self->num_row * sizeof(float));
+ }
- copy_m4_m4((float (*)[4])self->matrix, (float (*)[4])mat);
+ copy_m4_m4((float(*)[4])self->matrix, (float(*)[4])mat);
- self->num_col = 4;
- self->num_row = 4;
+ self->num_col = 4;
+ self->num_row = 4;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_to_4x4_doc,
-".. method:: to_4x4()\n"
-"\n"
-" Return a 4x4 copy of this matrix.\n"
-"\n"
-" :return: a new matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: to_4x4()\n"
+ "\n"
+ " Return a 4x4 copy of this matrix.\n"
+ "\n"
+ " :return: a new matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_to_4x4(MatrixObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (self->num_row == 4 && self->num_col == 4) {
- return Matrix_CreatePyObject(self->matrix, 4, 4, Py_TYPE(self));
- }
- else if (self->num_row == 3 && self->num_col == 3) {
- float mat[4][4];
- copy_m4_m3(mat, (float (*)[3])self->matrix);
- return Matrix_CreatePyObject((float *)mat, 4, 4, Py_TYPE(self));
- }
- /* TODO, 2x2 matrix */
+ if (self->num_row == 4 && self->num_col == 4) {
+ return Matrix_CreatePyObject(self->matrix, 4, 4, Py_TYPE(self));
+ }
+ else if (self->num_row == 3 && self->num_col == 3) {
+ float mat[4][4];
+ copy_m4_m3(mat, (float(*)[3])self->matrix);
+ return Matrix_CreatePyObject((float *)mat, 4, 4, Py_TYPE(self));
+ }
+ /* TODO, 2x2 matrix */
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_4x4(): "
- "inappropriate matrix size");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.to_4x4(): "
+ "inappropriate matrix size");
+ return NULL;
}
PyDoc_STRVAR(Matrix_to_3x3_doc,
-".. method:: to_3x3()\n"
-"\n"
-" Return a 3x3 copy of this matrix.\n"
-"\n"
-" :return: a new matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: to_3x3()\n"
+ "\n"
+ " Return a 3x3 copy of this matrix.\n"
+ "\n"
+ " :return: a new matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_to_3x3(MatrixObject *self)
{
- float mat[3][3];
+ float mat[3][3];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if ((self->num_row < 3) || (self->num_col < 3)) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_3x3(): inappropriate matrix size");
- return NULL;
- }
+ if ((self->num_row < 3) || (self->num_col < 3)) {
+ PyErr_SetString(PyExc_ValueError, "Matrix.to_3x3(): inappropriate matrix size");
+ return NULL;
+ }
- matrix_as_3x3(mat, self);
+ matrix_as_3x3(mat, self);
- return Matrix_CreatePyObject((float *)mat, 3, 3, Py_TYPE(self));
+ return Matrix_CreatePyObject((float *)mat, 3, 3, Py_TYPE(self));
}
PyDoc_STRVAR(Matrix_to_translation_doc,
-".. method:: to_translation()\n"
-"\n"
-" Return the translation part of a 4 row matrix.\n"
-"\n"
-" :return: Return the translation of a matrix.\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: to_translation()\n"
+ "\n"
+ " Return the translation part of a 4 row matrix.\n"
+ "\n"
+ " :return: Return the translation of a matrix.\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Matrix_to_translation(MatrixObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if ((self->num_row < 3) || self->num_col < 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_translation(): "
- "inappropriate matrix size");
- return NULL;
- }
+ if ((self->num_row < 3) || self->num_col < 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.to_translation(): "
+ "inappropriate matrix size");
+ return NULL;
+ }
- return Vector_CreatePyObject(MATRIX_COL_PTR(self, 3), 3, NULL);
+ return Vector_CreatePyObject(MATRIX_COL_PTR(self, 3), 3, NULL);
}
PyDoc_STRVAR(Matrix_to_scale_doc,
-".. method:: to_scale()\n"
-"\n"
-" Return the scale part of a 3x3 or 4x4 matrix.\n"
-"\n"
-" :return: Return the scale of a matrix.\n"
-" :rtype: :class:`Vector`\n"
-"\n"
-" .. note:: This method does not return a negative scale on any axis because it is not possible to obtain this data from the matrix alone.\n"
-);
+ ".. method:: to_scale()\n"
+ "\n"
+ " Return the scale part of a 3x3 or 4x4 matrix.\n"
+ "\n"
+ " :return: Return the scale of a matrix.\n"
+ " :rtype: :class:`Vector`\n"
+ "\n"
+ " .. note:: This method does not return a negative scale on any axis because it is "
+ "not possible to obtain this data from the matrix alone.\n");
static PyObject *Matrix_to_scale(MatrixObject *self)
{
- float rot[3][3];
- float mat[3][3];
- float size[3];
+ float rot[3][3];
+ float mat[3][3];
+ float size[3];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- /*must be 3-4 cols, 3-4 rows, square matrix */
- if ((self->num_row < 3) || (self->num_col < 3)) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.to_scale(): "
- "inappropriate matrix size, 3x3 minimum size");
- return NULL;
- }
+ /*must be 3-4 cols, 3-4 rows, square matrix */
+ if ((self->num_row < 3) || (self->num_col < 3)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.to_scale(): "
+ "inappropriate matrix size, 3x3 minimum size");
+ return NULL;
+ }
- matrix_as_3x3(mat, self);
+ matrix_as_3x3(mat, self);
- /* compatible mat4_to_loc_rot_size */
- mat3_to_rot_size(rot, size, mat);
+ /* compatible mat4_to_loc_rot_size */
+ mat3_to_rot_size(rot, size, mat);
- return Vector_CreatePyObject(size, 3, NULL);
+ return Vector_CreatePyObject(size, 3, NULL);
}
/*---------------------------matrix.invert() ---------------------*/
@@ -1375,774 +1412,777 @@ static PyObject *Matrix_to_scale(MatrixObject *self)
/* re-usable checks for invert */
static bool matrix_invert_is_compat(const MatrixObject *self)
{
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.invert(ed): "
- "only square matrices are supported");
- return false;
- }
- else {
- return true;
- }
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.invert(ed): "
+ "only square matrices are supported");
+ return false;
+ }
+ else {
+ return true;
+ }
}
static bool matrix_invert_args_check(const MatrixObject *self, PyObject *args, bool check_type)
{
- switch (PyTuple_GET_SIZE(args)) {
- case 0:
- return true;
- case 1:
- if (check_type) {
- const MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
- if (!MatrixObject_Check(fallback)) {
- PyErr_SetString(PyExc_TypeError,
- "Matrix.invert: "
- "expects a matrix argument or nothing");
- return false;
- }
-
- if ((self->num_col != fallback->num_col) ||
- (self->num_row != fallback->num_row))
- {
- PyErr_SetString(PyExc_TypeError,
- "Matrix.invert: "
- "matrix argument has different dimensions");
- return false;
- }
- }
-
- return true;
- default:
- PyErr_SetString(PyExc_ValueError,
- "Matrix.invert(ed): "
- "takes at most one argument");
- return false;
- }
+ switch (PyTuple_GET_SIZE(args)) {
+ case 0:
+ return true;
+ case 1:
+ if (check_type) {
+ const MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
+ if (!MatrixObject_Check(fallback)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix.invert: "
+ "expects a matrix argument or nothing");
+ return false;
+ }
+
+ if ((self->num_col != fallback->num_col) || (self->num_row != fallback->num_row)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Matrix.invert: "
+ "matrix argument has different dimensions");
+ return false;
+ }
+ }
+
+ return true;
+ default:
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.invert(ed): "
+ "takes at most one argument");
+ return false;
+ }
}
static void matrix_invert_raise_degenerate(void)
{
- PyErr_SetString(PyExc_ValueError,
- "Matrix.invert(ed): "
- "matrix does not have an inverse");
-}
-
-PyDoc_STRVAR(Matrix_invert_doc,
-".. method:: invert(fallback=None)\n"
-"\n"
-" Set the matrix to its inverse.\n"
-"\n"
-" :arg fallback: Set the matrix to this value when the inverse cannot be calculated\n"
-" (instead of raising a :exc:`ValueError` exception).\n"
-" :type fallback: :class:`Matrix`\n"
-"\n"
-" .. seealso:: `Inverse matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on Wikipedia.\n"
-);
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.invert(ed): "
+ "matrix does not have an inverse");
+}
+
+PyDoc_STRVAR(
+ Matrix_invert_doc,
+ ".. method:: invert(fallback=None)\n"
+ "\n"
+ " Set the matrix to its inverse.\n"
+ "\n"
+ " :arg fallback: Set the matrix to this value when the inverse cannot be calculated\n"
+ " (instead of raising a :exc:`ValueError` exception).\n"
+ " :type fallback: :class:`Matrix`\n"
+ "\n"
+ " .. seealso:: `Inverse matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on "
+ "Wikipedia.\n");
static PyObject *Matrix_invert(MatrixObject *self, PyObject *args)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (matrix_invert_is_compat(self) == false) {
- return NULL;
- }
+ if (matrix_invert_is_compat(self) == false) {
+ return NULL;
+ }
- if (matrix_invert_args_check(self, args, true) == false) {
- return NULL;
- }
+ if (matrix_invert_args_check(self, args, true) == false) {
+ return NULL;
+ }
- if (matrix_invert_internal(self, self->matrix)) {
- /* pass */
- }
- else {
- if (PyTuple_GET_SIZE(args) == 1) {
- MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
+ if (matrix_invert_internal(self, self->matrix)) {
+ /* pass */
+ }
+ else {
+ if (PyTuple_GET_SIZE(args) == 1) {
+ MatrixObject *fallback = (MatrixObject *)PyTuple_GET_ITEM(args, 0);
- if (BaseMath_ReadCallback(fallback) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(fallback) == -1) {
+ return NULL;
+ }
- if (self != fallback) {
- matrix_copy(self, fallback);
- }
- }
- else {
- matrix_invert_raise_degenerate();
- return NULL;
- }
- }
+ if (self != fallback) {
+ matrix_copy(self, fallback);
+ }
+ }
+ else {
+ matrix_invert_raise_degenerate();
+ return NULL;
+ }
+ }
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_inverted_doc,
-".. method:: inverted(fallback=None)\n"
-"\n"
-" Return an inverted copy of the matrix.\n"
-"\n"
-" :arg fallback: return this when the inverse can't be calculated\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: the inverted matrix or fallback when given.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: inverted(fallback=None)\n"
+ "\n"
+ " Return an inverted copy of the matrix.\n"
+ "\n"
+ " :arg fallback: return this when the inverse can't be calculated\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: the inverted matrix or fallback when given.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_inverted(MatrixObject *self, PyObject *args)
{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (matrix_invert_args_check(self, args, false) == false) {
- return NULL;
- }
+ if (matrix_invert_args_check(self, args, false) == false) {
+ return NULL;
+ }
- if (matrix_invert_is_compat(self) == false) {
- return NULL;
- }
+ if (matrix_invert_is_compat(self) == false) {
+ return NULL;
+ }
- if (matrix_invert_internal(self, mat)) {
- /* pass */
- }
- else {
- if (PyTuple_GET_SIZE(args) == 1) {
- PyObject *fallback = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- matrix_invert_raise_degenerate();
- return NULL;
- }
- }
+ if (matrix_invert_internal(self, mat)) {
+ /* pass */
+ }
+ else {
+ if (PyTuple_GET_SIZE(args) == 1) {
+ PyObject *fallback = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ matrix_invert_raise_degenerate();
+ return NULL;
+ }
+ }
- return Matrix_copy_notest(self, mat);
+ return Matrix_copy_notest(self, mat);
}
static PyObject *Matrix_inverted_noargs(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (matrix_invert_is_compat(self) == false) {
- return NULL;
- }
+ if (matrix_invert_is_compat(self) == false) {
+ return NULL;
+ }
- if (matrix_invert_internal(self, self->matrix)) {
- /* pass */
- }
- else {
- matrix_invert_raise_degenerate();
- return NULL;
- }
+ if (matrix_invert_internal(self, self->matrix)) {
+ /* pass */
+ }
+ else {
+ matrix_invert_raise_degenerate();
+ return NULL;
+ }
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_invert_safe_doc,
-".. method:: invert_safe()\n"
-"\n"
-" Set the matrix to its inverse, will never error.\n"
-" If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, to get an invertible one.\n"
-" If tweaked matrix is still degenerated, set to the identity matrix instead.\n"
-"\n"
-" .. seealso:: `Inverse Matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on Wikipedia.\n"
-);
+ ".. method:: invert_safe()\n"
+ "\n"
+ " Set the matrix to its inverse, will never error.\n"
+ " If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
+ "to get an invertible one.\n"
+ " If tweaked matrix is still degenerated, set to the identity matrix instead.\n"
+ "\n"
+ " .. seealso:: `Inverse Matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on "
+ "Wikipedia.\n");
static PyObject *Matrix_invert_safe(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (matrix_invert_is_compat(self) == false) {
- return NULL;
- }
+ if (matrix_invert_is_compat(self) == false) {
+ return NULL;
+ }
- matrix_invert_safe_internal(self, self->matrix);
+ matrix_invert_safe_internal(self, self->matrix);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_inverted_safe_doc,
-".. method:: inverted_safe()\n"
-"\n"
-" Return an inverted copy of the matrix, will never error.\n"
-" If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, to get an invertible one.\n"
-" If tweaked matrix is still degenerated, return the identity matrix instead.\n"
-"\n"
-" :return: the inverted matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: inverted_safe()\n"
+ "\n"
+ " Return an inverted copy of the matrix, will never error.\n"
+ " If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, "
+ "to get an invertible one.\n"
+ " If tweaked matrix is still degenerated, return the identity matrix instead.\n"
+ "\n"
+ " :return: the inverted matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_inverted_safe(MatrixObject *self)
{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (matrix_invert_is_compat(self) == false) {
- return NULL;
- }
+ if (matrix_invert_is_compat(self) == false) {
+ return NULL;
+ }
- matrix_invert_safe_internal(self, mat);
+ matrix_invert_safe_internal(self, mat);
- return Matrix_copy_notest(self, mat);
+ return Matrix_copy_notest(self, mat);
}
/*---------------------------matrix.adjugate() ---------------------*/
-PyDoc_STRVAR(Matrix_adjugate_doc,
-".. method:: adjugate()\n"
-"\n"
-" Set the matrix to its adjugate.\n"
-"\n"
-" .. note:: When the matrix cannot be adjugated a :exc:`ValueError` exception is raised.\n"
-"\n"
-" .. seealso:: `Adjugate matrix <https://en.wikipedia.org/wiki/Adjugate_matrix>` on Wikipedia.\n"
-);
+PyDoc_STRVAR(
+ Matrix_adjugate_doc,
+ ".. method:: adjugate()\n"
+ "\n"
+ " Set the matrix to its adjugate.\n"
+ "\n"
+ " .. note:: When the matrix cannot be adjugated a :exc:`ValueError` exception is raised.\n"
+ "\n"
+ " .. seealso:: `Adjugate matrix <https://en.wikipedia.org/wiki/Adjugate_matrix>` on "
+ "Wikipedia.\n");
static PyObject *Matrix_adjugate(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
-
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.adjugate(d): "
- "only square matrices are supported");
- return NULL;
- }
-
- /* calculate the classical adjoint */
- if (self->num_col <= 4) {
- adjoint_matrix_n(self->matrix, self->matrix, self->num_col);
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "Matrix adjugate(d): size (%d) unsupported",
- (int)self->num_col);
- return NULL;
- }
-
-
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
-}
-
-PyDoc_STRVAR(Matrix_adjugated_doc,
-".. method:: adjugated()\n"
-"\n"
-" Return an adjugated copy of the matrix.\n"
-"\n"
-" :return: the adjugated matrix.\n"
-" :rtype: :class:`Matrix`\n"
-"\n"
-" .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n"
-);
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
+
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.adjugate(d): "
+ "only square matrices are supported");
+ return NULL;
+ }
+
+ /* calculate the classical adjoint */
+ if (self->num_col <= 4) {
+ adjoint_matrix_n(self->matrix, self->matrix, self->num_col);
+ }
+ else {
+ PyErr_Format(
+ PyExc_ValueError, "Matrix adjugate(d): size (%d) unsupported", (int)self->num_col);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
+}
+
+PyDoc_STRVAR(
+ Matrix_adjugated_doc,
+ ".. method:: adjugated()\n"
+ "\n"
+ " Return an adjugated copy of the matrix.\n"
+ "\n"
+ " :return: the adjugated matrix.\n"
+ " :rtype: :class:`Matrix`\n"
+ "\n"
+ " .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n");
static PyObject *Matrix_adjugated(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_adjugate, self);
+ return matrix__apply_to_copy((PyNoArgsFunction)Matrix_adjugate, self);
}
-PyDoc_STRVAR(Matrix_rotate_doc,
-".. method:: rotate(other)\n"
-"\n"
-" Rotates the matrix by another mathutils value.\n"
-"\n"
-" :arg other: rotation component of mathutils value\n"
-" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
-"\n"
-" .. note:: If any of the columns are not unit length this may not have desired results.\n"
-);
+PyDoc_STRVAR(
+ Matrix_rotate_doc,
+ ".. method:: rotate(other)\n"
+ "\n"
+ " Rotates the matrix by another mathutils value.\n"
+ "\n"
+ " :arg other: rotation component of mathutils value\n"
+ " :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
+ "\n"
+ " .. note:: If any of the columns are not unit length this may not have desired results.\n");
static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
{
- float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
+ float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1) {
- return NULL;
- }
+ if (mathutils_any_to_rotmat(other_rmat, value, "matrix.rotate(value)") == -1) {
+ return NULL;
+ }
- if (self->num_row != 3 || self->num_col != 3) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.rotate(): "
- "must have 3x3 dimensions");
- return NULL;
- }
+ if (self->num_row != 3 || self->num_col != 3) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.rotate(): "
+ "must have 3x3 dimensions");
+ return NULL;
+ }
- matrix_as_3x3(self_rmat, self);
- mul_m3_m3m3(rmat, other_rmat, self_rmat);
+ matrix_as_3x3(self_rmat, self);
+ mul_m3_m3m3(rmat, other_rmat, self_rmat);
- copy_m3_m3((float (*)[3])(self->matrix), rmat);
+ copy_m3_m3((float(*)[3])(self->matrix), rmat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
/*---------------------------matrix.decompose() ---------------------*/
PyDoc_STRVAR(Matrix_decompose_doc,
-".. method:: decompose()\n"
-"\n"
-" Return the translation, rotation, and scale components of this matrix.\n"
-"\n"
-" :return: tuple of translation, rotation, and scale\n"
-" :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
-);
+ ".. method:: decompose()\n"
+ "\n"
+ " Return the translation, rotation, and scale components of this matrix.\n"
+ "\n"
+ " :return: tuple of translation, rotation, and scale\n"
+ " :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)");
static PyObject *Matrix_decompose(MatrixObject *self)
{
- PyObject *ret;
- float loc[3];
- float rot[3][3];
- float quat[4];
- float size[3];
+ PyObject *ret;
+ float loc[3];
+ float rot[3][3];
+ float quat[4];
+ float size[3];
- if (self->num_row != 4 || self->num_col != 4) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.decompose(): "
- "inappropriate matrix size - expects 4x4 matrix");
- return NULL;
- }
+ if (self->num_row != 4 || self->num_col != 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.decompose(): "
+ "inappropriate matrix size - expects 4x4 matrix");
+ return NULL;
+ }
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- mat4_to_loc_rot_size(loc, rot, size, (float (*)[4])self->matrix);
- mat3_to_quat(quat, rot);
+ mat4_to_loc_rot_size(loc, rot, size, (float(*)[4])self->matrix);
+ mat3_to_quat(quat, rot);
- ret = PyTuple_New(3);
- PyTuple_SET_ITEMS(ret,
- Vector_CreatePyObject(loc, 3, NULL),
- Quaternion_CreatePyObject(quat, NULL),
- Vector_CreatePyObject(size, 3, NULL));
- return ret;
+ ret = PyTuple_New(3);
+ PyTuple_SET_ITEMS(ret,
+ Vector_CreatePyObject(loc, 3, NULL),
+ Quaternion_CreatePyObject(quat, NULL),
+ Vector_CreatePyObject(size, 3, NULL));
+ return ret;
}
-
-
PyDoc_STRVAR(Matrix_lerp_doc,
-".. function:: lerp(other, factor)\n"
-"\n"
-" Returns the interpolation of two matrices. Uses polar decomposition, see"
-" \"Matrix Animation and Polar Decomposition\", Shoemake and Duff, 1992.\n"
-"\n"
-" :arg other: value to interpolate with.\n"
-" :type other: :class:`Matrix`\n"
-" :arg factor: The interpolation value in [0.0, 1.0].\n"
-" :type factor: float\n"
-" :return: The interpolated matrix.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. function:: lerp(other, factor)\n"
+ "\n"
+ " Returns the interpolation of two matrices. Uses polar decomposition, see"
+ " \"Matrix Animation and Polar Decomposition\", Shoemake and Duff, 1992.\n"
+ "\n"
+ " :arg other: value to interpolate with.\n"
+ " :type other: :class:`Matrix`\n"
+ " :arg factor: The interpolation value in [0.0, 1.0].\n"
+ " :type factor: float\n"
+ " :return: The interpolated matrix.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
{
- MatrixObject *mat2 = NULL;
- float fac, mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ MatrixObject *mat2 = NULL;
+ float fac, mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- if (!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O!f:lerp", &matrix_Type, &mat2, &fac)) {
+ return NULL;
+ }
- if (self->num_col != mat2->num_col || self->num_row != mat2->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.lerp(): "
- "expects both matrix objects of the same dimensions");
- return NULL;
- }
+ if (self->num_col != mat2->num_col || self->num_row != mat2->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.lerp(): "
+ "expects both matrix objects of the same dimensions");
+ return NULL;
+ }
- if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1 || BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
- /* TODO, different sized matrix */
- if (self->num_col == 4 && self->num_row == 4) {
+ /* TODO, different sized matrix */
+ if (self->num_col == 4 && self->num_row == 4) {
#ifdef MATH_STANDALONE
- blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->matrix, (float (*)[4])mat2->matrix, fac);
+ blend_m4_m4m4((float(*)[4])mat, (float(*)[4])self->matrix, (float(*)[4])mat2->matrix, fac);
#else
- interp_m4_m4m4((float (*)[4])mat, (float (*)[4])self->matrix, (float (*)[4])mat2->matrix, fac);
+ interp_m4_m4m4((float(*)[4])mat, (float(*)[4])self->matrix, (float(*)[4])mat2->matrix, fac);
#endif
- }
- else if (self->num_col == 3 && self->num_row == 3) {
+ }
+ else if (self->num_col == 3 && self->num_row == 3) {
#ifdef MATH_STANDALONE
- blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->matrix, (float (*)[3])mat2->matrix, fac);
+ blend_m3_m3m3((float(*)[3])mat, (float(*)[3])self->matrix, (float(*)[3])mat2->matrix, fac);
#else
- interp_m3_m3m3((float (*)[3])mat, (float (*)[3])self->matrix, (float (*)[3])mat2->matrix, fac);
+ interp_m3_m3m3((float(*)[3])mat, (float(*)[3])self->matrix, (float(*)[3])mat2->matrix, fac);
#endif
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.lerp(): "
- "only 3x3 and 4x4 matrices supported");
- return NULL;
- }
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.lerp(): "
+ "only 3x3 and 4x4 matrices supported");
+ return NULL;
+ }
- return Matrix_CreatePyObject(mat, self->num_col, self->num_row, Py_TYPE(self));
+ return Matrix_CreatePyObject(mat, self->num_col, self->num_row, Py_TYPE(self));
}
/*---------------------------matrix.determinant() ----------------*/
-PyDoc_STRVAR(Matrix_determinant_doc,
-".. method:: determinant()\n"
-"\n"
-" Return the determinant of a matrix.\n"
-"\n"
-" :return: Return the determinant of a matrix.\n"
-" :rtype: float\n"
-"\n"
-" .. seealso:: `Determinant <https://en.wikipedia.org/wiki/Determinant>` on Wikipedia.\n"
-);
+PyDoc_STRVAR(
+ Matrix_determinant_doc,
+ ".. method:: determinant()\n"
+ "\n"
+ " Return the determinant of a matrix.\n"
+ "\n"
+ " :return: Return the determinant of a matrix.\n"
+ " :rtype: float\n"
+ "\n"
+ " .. seealso:: `Determinant <https://en.wikipedia.org/wiki/Determinant>` on Wikipedia.\n");
static PyObject *Matrix_determinant(MatrixObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.determinant(): "
- "only square matrices are supported");
- return NULL;
- }
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.determinant(): "
+ "only square matrices are supported");
+ return NULL;
+ }
- return PyFloat_FromDouble((double)matrix_determinant_internal(self));
+ return PyFloat_FromDouble((double)matrix_determinant_internal(self));
}
/*---------------------------matrix.transpose() ------------------*/
-PyDoc_STRVAR(Matrix_transpose_doc,
-".. method:: transpose()\n"
-"\n"
-" Set the matrix to its transpose.\n"
-"\n"
-" .. seealso:: `Transpose <https://en.wikipedia.org/wiki/Transpose>` on Wikipedia.\n"
-);
+PyDoc_STRVAR(
+ Matrix_transpose_doc,
+ ".. method:: transpose()\n"
+ "\n"
+ " Set the matrix to its transpose.\n"
+ "\n"
+ " .. seealso:: `Transpose <https://en.wikipedia.org/wiki/Transpose>` on Wikipedia.\n");
static PyObject *Matrix_transpose(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
-
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.transpose(d): "
- "only square matrices are supported");
- return NULL;
- }
-
- if (self->num_col == 2) {
- const float t = MATRIX_ITEM(self, 1, 0);
- MATRIX_ITEM(self, 1, 0) = MATRIX_ITEM(self, 0, 1);
- MATRIX_ITEM(self, 0, 1) = t;
- }
- else if (self->num_col == 3) {
- transpose_m3((float (*)[3])self->matrix);
- }
- else {
- transpose_m4((float (*)[4])self->matrix);
- }
-
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
+
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.transpose(d): "
+ "only square matrices are supported");
+ return NULL;
+ }
+
+ if (self->num_col == 2) {
+ const float t = MATRIX_ITEM(self, 1, 0);
+ MATRIX_ITEM(self, 1, 0) = MATRIX_ITEM(self, 0, 1);
+ MATRIX_ITEM(self, 0, 1) = t;
+ }
+ else if (self->num_col == 3) {
+ transpose_m3((float(*)[3])self->matrix);
+ }
+ else {
+ transpose_m4((float(*)[4])self->matrix);
+ }
+
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_transposed_doc,
-".. method:: transposed()\n"
-"\n"
-" Return a new, transposed matrix.\n"
-"\n"
-" :return: a transposed matrix\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: transposed()\n"
+ "\n"
+ " Return a new, transposed matrix.\n"
+ "\n"
+ " :return: a transposed matrix\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_transposed(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
+ return matrix__apply_to_copy((PyNoArgsFunction)Matrix_transpose, self);
}
/*---------------------------matrix.normalize() ------------------*/
PyDoc_STRVAR(Matrix_normalize_doc,
-".. method:: normalize()\n"
-"\n"
-" Normalize each of the matrix columns.\n"
-);
+ ".. method:: normalize()\n"
+ "\n"
+ " Normalize each of the matrix columns.\n");
static PyObject *Matrix_normalize(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
-
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.normalize(): "
- "only square matrices are supported");
- return NULL;
- }
-
- if (self->num_col == 3) {
- normalize_m3((float (*)[3])self->matrix);
- }
- else if (self->num_col == 4) {
- normalize_m4((float (*)[4])self->matrix);
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.normalize(): "
- "can only use a 3x3 or 4x4 matrix");
- }
-
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
+
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.normalize(): "
+ "only square matrices are supported");
+ return NULL;
+ }
+
+ if (self->num_col == 3) {
+ normalize_m3((float(*)[3])self->matrix);
+ }
+ else if (self->num_col == 4) {
+ normalize_m4((float(*)[4])self->matrix);
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.normalize(): "
+ "can only use a 3x3 or 4x4 matrix");
+ }
+
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Matrix_normalized_doc,
-".. method:: normalized()\n"
-"\n"
-" Return a column normalized matrix\n"
-"\n"
-" :return: a column normalized matrix\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: normalized()\n"
+ "\n"
+ " Return a column normalized matrix\n"
+ "\n"
+ " :return: a column normalized matrix\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_normalized(MatrixObject *self)
{
- return matrix__apply_to_copy((PyNoArgsFunction)Matrix_normalize, self);
+ return matrix__apply_to_copy((PyNoArgsFunction)Matrix_normalize, self);
}
/*---------------------------matrix.zero() -----------------------*/
PyDoc_STRVAR(Matrix_zero_doc,
-".. method:: zero()\n"
-"\n"
-" Set all the matrix values to zero.\n"
-"\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: zero()\n"
+ "\n"
+ " Set all the matrix values to zero.\n"
+ "\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_zero(MatrixObject *self)
{
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return NULL;
- }
-
- copy_vn_fl(self->matrix, self->num_col * self->num_row, 0.0f);
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (BaseMath_WriteCallback(self) == -1) {
- return NULL;
- }
+ copy_vn_fl(self->matrix, self->num_col * self->num_row, 0.0f);
- Py_RETURN_NONE;
+ if (BaseMath_WriteCallback(self) == -1) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
/*---------------------------matrix.identity(() ------------------*/
static void matrix_identity_internal(MatrixObject *self)
{
- BLI_assert((self->num_col == self->num_row) && (self->num_row <= 4));
+ BLI_assert((self->num_col == self->num_row) && (self->num_row <= 4));
- if (self->num_col == 2) {
- unit_m2((float (*)[2])self->matrix);
- }
- else if (self->num_col == 3) {
- unit_m3((float (*)[3])self->matrix);
- }
- else {
- unit_m4((float (*)[4])self->matrix);
- }
+ if (self->num_col == 2) {
+ unit_m2((float(*)[2])self->matrix);
+ }
+ else if (self->num_col == 3) {
+ unit_m3((float(*)[3])self->matrix);
+ }
+ else {
+ unit_m4((float(*)[4])self->matrix);
+ }
}
PyDoc_STRVAR(Matrix_identity_doc,
-".. method:: identity()\n"
-"\n"
-" Set the matrix to the identity matrix.\n"
-"\n"
-" .. note:: An object with a location and rotation of zero, and a scale of one\n"
-" will have an identity matrix.\n"
-"\n"
-" .. seealso:: `Identity matrix <https://en.wikipedia.org/wiki/Identity_matrix>` on Wikipedia.\n"
-);
+ ".. method:: identity()\n"
+ "\n"
+ " Set the matrix to the identity matrix.\n"
+ "\n"
+ " .. note:: An object with a location and rotation of zero, and a scale of one\n"
+ " will have an identity matrix.\n"
+ "\n"
+ " .. seealso:: `Identity matrix <https://en.wikipedia.org/wiki/Identity_matrix>` "
+ "on Wikipedia.\n");
static PyObject *Matrix_identity(MatrixObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (self->num_col != self->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix.identity(): "
- "only square matrices are supported");
- return NULL;
- }
+ if (self->num_col != self->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix.identity(): "
+ "only square matrices are supported");
+ return NULL;
+ }
- matrix_identity_internal(self);
+ matrix_identity_internal(self);
- if (BaseMath_WriteCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/*---------------------------Matrix.copy() ------------------*/
static PyObject *Matrix_copy_notest(MatrixObject *self, const float *matrix)
{
- return Matrix_CreatePyObject((float *)matrix, self->num_col, self->num_row, Py_TYPE(self));
+ return Matrix_CreatePyObject((float *)matrix, self->num_col, self->num_row, Py_TYPE(self));
}
PyDoc_STRVAR(Matrix_copy_doc,
-".. method:: copy()\n"
-"\n"
-" Returns a copy of this matrix.\n"
-"\n"
-" :return: an instance of itself\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: copy()\n"
+ "\n"
+ " Returns a copy of this matrix.\n"
+ "\n"
+ " :return: an instance of itself\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Matrix_copy(MatrixObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Matrix_copy_notest(self, self->matrix);
+ return Matrix_copy_notest(self, self->matrix);
}
static PyObject *Matrix_deepcopy(MatrixObject *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return Matrix_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return Matrix_copy(self);
}
/*----------------------------print object (internal)-------------*/
/* print the object to screen */
static PyObject *Matrix_repr(MatrixObject *self)
{
- int col, row;
- PyObject *rows[MATRIX_MAX_DIM] = {NULL};
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- for (row = 0; row < self->num_row; row++) {
- rows[row] = PyTuple_New(self->num_col);
- for (col = 0; col < self->num_col; col++) {
- PyTuple_SET_ITEM(rows[row], col, PyFloat_FromDouble(MATRIX_ITEM(self, row, col)));
- }
- }
- switch (self->num_row) {
- case 2: return PyUnicode_FromFormat("Matrix((%R,\n"
- " %R))", rows[0], rows[1]);
-
- case 3: return PyUnicode_FromFormat("Matrix((%R,\n"
- " %R,\n"
- " %R))", rows[0], rows[1], rows[2]);
-
- case 4: return PyUnicode_FromFormat("Matrix((%R,\n"
- " %R,\n"
- " %R,\n"
- " %R))", rows[0], rows[1], rows[2], rows[3]);
- }
-
- Py_FatalError("Matrix(): invalid row size!");
- return NULL;
+ int col, row;
+ PyObject *rows[MATRIX_MAX_DIM] = {NULL};
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ for (row = 0; row < self->num_row; row++) {
+ rows[row] = PyTuple_New(self->num_col);
+ for (col = 0; col < self->num_col; col++) {
+ PyTuple_SET_ITEM(rows[row], col, PyFloat_FromDouble(MATRIX_ITEM(self, row, col)));
+ }
+ }
+ switch (self->num_row) {
+ case 2:
+ return PyUnicode_FromFormat(
+ "Matrix((%R,\n"
+ " %R))",
+ rows[0],
+ rows[1]);
+
+ case 3:
+ return PyUnicode_FromFormat(
+ "Matrix((%R,\n"
+ " %R,\n"
+ " %R))",
+ rows[0],
+ rows[1],
+ rows[2]);
+
+ case 4:
+ return PyUnicode_FromFormat(
+ "Matrix((%R,\n"
+ " %R,\n"
+ " %R,\n"
+ " %R))",
+ rows[0],
+ rows[1],
+ rows[2],
+ rows[3]);
+ }
+
+ Py_FatalError("Matrix(): invalid row size!");
+ return NULL;
}
#ifndef MATH_STANDALONE
static PyObject *Matrix_str(MatrixObject *self)
{
- DynStr *ds;
+ DynStr *ds;
- int maxsize[MATRIX_MAX_DIM];
- int row, col;
+ int maxsize[MATRIX_MAX_DIM];
+ int row, col;
- char dummy_buf[64];
+ char dummy_buf[64];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- ds = BLI_dynstr_new();
+ ds = BLI_dynstr_new();
- /* First determine the maximum width for each column */
- for (col = 0; col < self->num_col; col++) {
- maxsize[col] = 0;
- for (row = 0; row < self->num_row; row++) {
- int size = BLI_snprintf(dummy_buf, sizeof(dummy_buf), "%.4f", MATRIX_ITEM(self, row, col));
- maxsize[col] = max_ii(maxsize[col], size);
- }
- }
+ /* First determine the maximum width for each column */
+ for (col = 0; col < self->num_col; col++) {
+ maxsize[col] = 0;
+ for (row = 0; row < self->num_row; row++) {
+ int size = BLI_snprintf(dummy_buf, sizeof(dummy_buf), "%.4f", MATRIX_ITEM(self, row, col));
+ maxsize[col] = max_ii(maxsize[col], size);
+ }
+ }
- /* Now write the unicode string to be printed */
- BLI_dynstr_appendf(ds, "<Matrix %dx%d (", self->num_row, self->num_col);
- for (row = 0; row < self->num_row; row++) {
- for (col = 0; col < self->num_col; col++) {
- BLI_dynstr_appendf(ds, col ? ", %*.4f" : "%*.4f", maxsize[col], MATRIX_ITEM(self, row, col));
- }
- BLI_dynstr_append(ds, row + 1 != self->num_row ? ")\n (" : ")");
- }
- BLI_dynstr_append(ds, ">");
+ /* Now write the unicode string to be printed */
+ BLI_dynstr_appendf(ds, "<Matrix %dx%d (", self->num_row, self->num_col);
+ for (row = 0; row < self->num_row; row++) {
+ for (col = 0; col < self->num_col; col++) {
+ BLI_dynstr_appendf(ds, col ? ", %*.4f" : "%*.4f", maxsize[col], MATRIX_ITEM(self, row, col));
+ }
+ BLI_dynstr_append(ds, row + 1 != self->num_row ? ")\n (" : ")");
+ }
+ BLI_dynstr_append(ds, ">");
- return mathutils_dynstr_to_py(ds); /* frees ds */
+ return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
static PyObject *Matrix_richcmpr(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
-
- if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
- MatrixObject *matA = (MatrixObject *)a;
- MatrixObject *matB = (MatrixObject *)b;
-
- if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1) {
- return NULL;
- }
-
- ok = ((matA->num_row == matB->num_row) &&
- (matA->num_col == matB->num_col) &&
- EXPP_VectorsAreEqual(matA->matrix, matB->matrix, (matA->num_col * matA->num_row), 1)
- ) ? 0 : -1;
- }
-
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
-
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- return Py_INCREF_RET(res);
+ PyObject *res;
+ int ok = -1; /* zero is true */
+
+ if (MatrixObject_Check(a) && MatrixObject_Check(b)) {
+ MatrixObject *matA = (MatrixObject *)a;
+ MatrixObject *matB = (MatrixObject *)b;
+
+ if (BaseMath_ReadCallback(matA) == -1 || BaseMath_ReadCallback(matB) == -1) {
+ return NULL;
+ }
+
+ ok = ((matA->num_row == matB->num_row) && (matA->num_col == matB->num_col) &&
+ EXPP_VectorsAreEqual(matA->matrix, matB->matrix, (matA->num_col * matA->num_row), 1)) ?
+ 0 :
+ -1;
+ }
+
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
+
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ return Py_INCREF_RET(res);
}
static Py_hash_t Matrix_hash(MatrixObject *self)
{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- if (BaseMathObject_Prepare_ForHash(self) == -1) {
- return -1;
- }
+ if (BaseMathObject_Prepare_ForHash(self) == -1) {
+ return -1;
+ }
- matrix_transpose_internal(mat, self);
+ matrix_transpose_internal(mat, self);
- return mathutils_array_hash(mat, self->num_row * self->num_col);
+ return mathutils_array_hash(mat, self->num_row * self->num_col);
}
/*---------------------SEQUENCE PROTOCOLS------------------------
@@ -2150,39 +2190,41 @@ static Py_hash_t Matrix_hash(MatrixObject *self)
* sequence length */
static int Matrix_len(MatrixObject *self)
{
- return self->num_row;
+ return self->num_row;
}
/*----------------------------object[]---------------------------
* sequence accessor (get)
* the wrapped vector gives direct access to the matrix data */
static PyObject *Matrix_item_row(MatrixObject *self, int row)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (row < 0 || row >= self->num_row) {
- PyErr_SetString(PyExc_IndexError,
- "matrix[attribute]: "
- "array index out of range");
- return NULL;
- }
- return Vector_CreatePyObject_cb((PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, row);
+ if (row < 0 || row >= self->num_row) {
+ PyErr_SetString(PyExc_IndexError,
+ "matrix[attribute]: "
+ "array index out of range");
+ return NULL;
+ }
+ return Vector_CreatePyObject_cb(
+ (PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, row);
}
/* same but column access */
static PyObject *Matrix_item_col(MatrixObject *self, int col)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (col < 0 || col >= self->num_col) {
- PyErr_SetString(PyExc_IndexError,
- "matrix[attribute]: "
- "array index out of range");
- return NULL;
- }
- return Vector_CreatePyObject_cb((PyObject *)self, self->num_row, mathutils_matrix_col_cb_index, col);
+ if (col < 0 || col >= self->num_col) {
+ PyErr_SetString(PyExc_IndexError,
+ "matrix[attribute]: "
+ "array index out of range");
+ return NULL;
+ }
+ return Vector_CreatePyObject_cb(
+ (PyObject *)self, self->num_row, mathutils_matrix_col_cb_index, col);
}
/*----------------------------object[]-------------------------
@@ -2190,994 +2232,1031 @@ static PyObject *Matrix_item_col(MatrixObject *self, int col)
static int Matrix_ass_item_row(MatrixObject *self, int row, PyObject *value)
{
- int col;
- float vec[MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ int col;
+ float vec[MATRIX_MAX_DIM];
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- if (row >= self->num_row || row < 0) {
- PyErr_SetString(PyExc_IndexError,
- "matrix[attribute] = x: bad row");
- return -1;
- }
+ if (row >= self->num_row || row < 0) {
+ PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad row");
+ return -1;
+ }
- if (mathutils_array_parse(vec, self->num_col, self->num_col, value, "matrix[i] = value assignment") == -1) {
- return -1;
- }
+ if (mathutils_array_parse(
+ vec, self->num_col, self->num_col, value, "matrix[i] = value assignment") == -1) {
+ return -1;
+ }
- /* Since we are assigning a row we cannot memcpy */
- for (col = 0; col < self->num_col; col++) {
- MATRIX_ITEM(self, row, col) = vec[col];
- }
+ /* Since we are assigning a row we cannot memcpy */
+ for (col = 0; col < self->num_col; col++) {
+ MATRIX_ITEM(self, row, col) = vec[col];
+ }
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
static int Matrix_ass_item_col(MatrixObject *self, int col, PyObject *value)
{
- int row;
- float vec[MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ int row;
+ float vec[MATRIX_MAX_DIM];
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- if (col >= self->num_col || col < 0) {
- PyErr_SetString(PyExc_IndexError,
- "matrix[attribute] = x: bad col");
- return -1;
- }
+ if (col >= self->num_col || col < 0) {
+ PyErr_SetString(PyExc_IndexError, "matrix[attribute] = x: bad col");
+ return -1;
+ }
- if (mathutils_array_parse(vec, self->num_row, self->num_row, value, "matrix[i] = value assignment") == -1) {
- return -1;
- }
+ if (mathutils_array_parse(
+ vec, self->num_row, self->num_row, value, "matrix[i] = value assignment") == -1) {
+ return -1;
+ }
- /* Since we are assigning a row we cannot memcpy */
- for (row = 0; row < self->num_row; row++) {
- MATRIX_ITEM(self, row, col) = vec[row];
- }
+ /* Since we are assigning a row we cannot memcpy */
+ for (row = 0; row < self->num_row; row++) {
+ MATRIX_ITEM(self, row, col) = vec[row];
+ }
- (void)BaseMath_WriteCallback(self);
- return 0;
+ (void)BaseMath_WriteCallback(self);
+ return 0;
}
-
/*----------------------------object[z:y]------------------------
* sequence slice (get)*/
static PyObject *Matrix_slice(MatrixObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
+ PyObject *tuple;
+ int count;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- CLAMP(begin, 0, self->num_row);
- CLAMP(end, 0, self->num_row);
- begin = MIN2(begin, end);
+ CLAMP(begin, 0, self->num_row);
+ CLAMP(end, 0, self->num_row);
+ begin = MIN2(begin, end);
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin,
- Vector_CreatePyObject_cb((PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, count));
- }
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple,
+ count - begin,
+ Vector_CreatePyObject_cb(
+ (PyObject *)self, self->num_col, mathutils_matrix_row_cb_index, count));
+ }
- return tuple;
+ return tuple;
}
/*----------------------------object[z:y]------------------------
* sequence slice (set)*/
static int Matrix_ass_slice(MatrixObject *self, int begin, int end, PyObject *value)
{
- PyObject *value_fast;
-
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
-
- CLAMP(begin, 0, self->num_row);
- CLAMP(end, 0, self->num_row);
- begin = MIN2(begin, end);
-
- /* non list/tuple cases */
- if (!(value_fast = PySequence_Fast(value, "matrix[begin:end] = value"))) {
- /* PySequence_Fast sets the error */
- return -1;
- }
- else {
- PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
- const int size = end - begin;
- int row, col;
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- float vec[4];
-
- if (PySequence_Fast_GET_SIZE(value_fast) != size) {
- Py_DECREF(value_fast);
- PyErr_SetString(PyExc_ValueError,
- "matrix[begin:end] = []: "
- "size mismatch in slice assignment");
- return -1;
- }
-
- memcpy(mat, self->matrix, self->num_col * self->num_row * sizeof(float));
-
- /* parse sub items */
- for (row = begin; row < end; row++) {
- /* parse each sub sequence */
- PyObject *item = value_fast_items[row - begin];
-
- if (mathutils_array_parse(vec, self->num_col, self->num_col, item,
- "matrix[begin:end] = value assignment") == -1)
- {
- Py_DECREF(value_fast);
- return -1;
- }
-
- for (col = 0; col < self->num_col; col++) {
- mat[col * self->num_row + row] = vec[col];
- }
- }
-
- Py_DECREF(value_fast);
-
- /*parsed well - now set in matrix*/
- memcpy(self->matrix, mat, self->num_col * self->num_row * sizeof(float));
-
- (void)BaseMath_WriteCallback(self);
- return 0;
- }
+ PyObject *value_fast;
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ CLAMP(begin, 0, self->num_row);
+ CLAMP(end, 0, self->num_row);
+ begin = MIN2(begin, end);
+
+ /* non list/tuple cases */
+ if (!(value_fast = PySequence_Fast(value, "matrix[begin:end] = value"))) {
+ /* PySequence_Fast sets the error */
+ return -1;
+ }
+ else {
+ PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
+ const int size = end - begin;
+ int row, col;
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ float vec[4];
+
+ if (PySequence_Fast_GET_SIZE(value_fast) != size) {
+ Py_DECREF(value_fast);
+ PyErr_SetString(PyExc_ValueError,
+ "matrix[begin:end] = []: "
+ "size mismatch in slice assignment");
+ return -1;
+ }
+
+ memcpy(mat, self->matrix, self->num_col * self->num_row * sizeof(float));
+
+ /* parse sub items */
+ for (row = begin; row < end; row++) {
+ /* parse each sub sequence */
+ PyObject *item = value_fast_items[row - begin];
+
+ if (mathutils_array_parse(
+ vec, self->num_col, self->num_col, item, "matrix[begin:end] = value assignment") ==
+ -1) {
+ Py_DECREF(value_fast);
+ return -1;
+ }
+
+ for (col = 0; col < self->num_col; col++) {
+ mat[col * self->num_row + row] = vec[col];
+ }
+ }
+
+ Py_DECREF(value_fast);
+
+ /*parsed well - now set in matrix*/
+ memcpy(self->matrix, mat, self->num_col * self->num_row * sizeof(float));
+
+ (void)BaseMath_WriteCallback(self);
+ return 0;
+ }
}
/*------------------------NUMERIC PROTOCOLS----------------------
*------------------------obj + obj------------------------------*/
static PyObject *Matrix_add(PyObject *m1, PyObject *m2)
{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- MatrixObject *mat1 = NULL, *mat2 = NULL;
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
- mat1 = (MatrixObject *)m1;
- mat2 = (MatrixObject *)m2;
+ mat1 = (MatrixObject *)m1;
+ mat2 = (MatrixObject *)m2;
- if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
- PyErr_Format(PyExc_TypeError,
- "Matrix addition: (%s + %s) "
- "invalid type for this operation",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
- }
+ if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Matrix addition: (%s + %s) "
+ "invalid type for this operation",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
+ }
- if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
- if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix addition: "
- "matrices must have the same dimensions for this operation");
- return NULL;
- }
+ if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix addition: "
+ "matrices must have the same dimensions for this operation");
+ return NULL;
+ }
- add_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
+ add_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
- return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
+ return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
}
/*------------------------obj - obj------------------------------
* subtraction */
static PyObject *Matrix_sub(PyObject *m1, PyObject *m2)
{
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- MatrixObject *mat1 = NULL, *mat2 = NULL;
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
- mat1 = (MatrixObject *)m1;
- mat2 = (MatrixObject *)m2;
+ mat1 = (MatrixObject *)m1;
+ mat2 = (MatrixObject *)m2;
- if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
- PyErr_Format(PyExc_TypeError,
- "Matrix subtraction: (%s - %s) "
- "invalid type for this operation",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
- }
+ if (!MatrixObject_Check(m1) || !MatrixObject_Check(m2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Matrix subtraction: (%s - %s) "
+ "invalid type for this operation",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
+ }
- if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(mat1) == -1 || BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
- if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "Matrix addition: "
- "matrices must have the same dimensions for this operation");
- return NULL;
- }
+ if (mat1->num_col != mat2->num_col || mat1->num_row != mat2->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "Matrix addition: "
+ "matrices must have the same dimensions for this operation");
+ return NULL;
+ }
- sub_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
+ sub_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
- return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
+ return Matrix_CreatePyObject(mat, mat1->num_col, mat1->num_row, Py_TYPE(mat1));
}
/*------------------------obj * obj------------------------------
* element-wise multiplication */
static PyObject *matrix_mul_float(MatrixObject *mat, const float scalar)
{
- float tmat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- mul_vn_vn_fl(tmat, mat->matrix, mat->num_col * mat->num_row, scalar);
- return Matrix_CreatePyObject(tmat, mat->num_col, mat->num_row, Py_TYPE(mat));
+ float tmat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ mul_vn_vn_fl(tmat, mat->matrix, mat->num_col * mat->num_row, scalar);
+ return Matrix_CreatePyObject(tmat, mat->num_col, mat->num_row, Py_TYPE(mat));
}
static PyObject *Matrix_mul(PyObject *m1, PyObject *m2)
{
- float scalar;
+ float scalar;
- MatrixObject *mat1 = NULL, *mat2 = NULL;
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
- if (MatrixObject_Check(m1)) {
- mat1 = (MatrixObject *)m1;
- if (BaseMath_ReadCallback(mat1) == -1) {
- return NULL;
- }
- }
- if (MatrixObject_Check(m2)) {
- mat2 = (MatrixObject *)m2;
- if (BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
- }
+ if (MatrixObject_Check(m1)) {
+ mat1 = (MatrixObject *)m1;
+ if (BaseMath_ReadCallback(mat1) == -1) {
+ return NULL;
+ }
+ }
+ if (MatrixObject_Check(m2)) {
+ mat2 = (MatrixObject *)m2;
+ if (BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
+ }
- if (mat1 && mat2) {
+ if (mat1 && mat2) {
#ifdef USE_MATHUTILS_ELEM_MUL
- /* MATRIX * MATRIX */
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ /* MATRIX * MATRIX */
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
- PyErr_SetString(PyExc_ValueError,
- "matrix1 * matrix2: matrix1 number of rows/columns "
- "and the matrix2 number of rows/columns must be the same");
- return NULL;
- }
+ if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
+ PyErr_SetString(PyExc_ValueError,
+ "matrix1 * matrix2: matrix1 number of rows/columns "
+ "and the matrix2 number of rows/columns must be the same");
+ return NULL;
+ }
- mul_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
+ mul_vn_vnvn(mat, mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
- return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
+ return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
#endif
- }
- else if (mat2) {
- /*FLOAT/INT * MATRIX */
- if (((scalar = PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred()) == 0) {
- return matrix_mul_float(mat2, scalar);
- }
- }
- else if (mat1) {
- /* MATRIX * FLOAT/INT */
- if (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0) {
- return matrix_mul_float(mat1, scalar);
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
+ }
+ else if (mat2) {
+ /*FLOAT/INT * MATRIX */
+ if (((scalar = PyFloat_AsDouble(m1)) == -1.0f && PyErr_Occurred()) == 0) {
+ return matrix_mul_float(mat2, scalar);
+ }
+ }
+ else if (mat1) {
+ /* MATRIX * FLOAT/INT */
+ if (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0) {
+ return matrix_mul_float(mat1, scalar);
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
}
/*------------------------obj *= obj------------------------------
* Inplace element-wise multiplication */
static PyObject *Matrix_imul(PyObject *m1, PyObject *m2)
{
- float scalar;
+ float scalar;
- MatrixObject *mat1 = NULL, *mat2 = NULL;
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
- if (MatrixObject_Check(m1)) {
- mat1 = (MatrixObject *)m1;
- if (BaseMath_ReadCallback(mat1) == -1) {
- return NULL;
- }
- }
- if (MatrixObject_Check(m2)) {
- mat2 = (MatrixObject *)m2;
- if (BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
- }
+ if (MatrixObject_Check(m1)) {
+ mat1 = (MatrixObject *)m1;
+ if (BaseMath_ReadCallback(mat1) == -1) {
+ return NULL;
+ }
+ }
+ if (MatrixObject_Check(m2)) {
+ mat2 = (MatrixObject *)m2;
+ if (BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
+ }
- if (mat1 && mat2) {
+ if (mat1 && mat2) {
#ifdef USE_MATHUTILS_ELEM_MUL
- /* MATRIX *= MATRIX */
- if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
- PyErr_SetString(PyExc_ValueError,
- "matrix1 *= matrix2: matrix1 number of rows/columns "
- "and the matrix2 number of rows/columns must be the same");
- return NULL;
- }
-
- mul_vn_vn(mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
+ /* MATRIX *= MATRIX */
+ if ((mat1->num_row != mat2->num_row) || (mat1->num_col != mat2->num_col)) {
+ PyErr_SetString(PyExc_ValueError,
+ "matrix1 *= matrix2: matrix1 number of rows/columns "
+ "and the matrix2 number of rows/columns must be the same");
+ return NULL;
+ }
+
+ mul_vn_vn(mat1->matrix, mat2->matrix, mat1->num_col * mat1->num_row);
#else
- PyErr_Format(PyExc_TypeError,
- "Inplace element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "Inplace element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
#endif
- }
- else if (mat1 && (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0)) {
- /* MATRIX *= FLOAT/INT */
- mul_vn_fl(mat1->matrix, mat1->num_row * mat1->num_col, scalar);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Inplace element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(mat1);
- Py_INCREF(m1);
- return m1;
+ }
+ else if (mat1 && (((scalar = PyFloat_AsDouble(m2)) == -1.0f && PyErr_Occurred()) == 0)) {
+ /* MATRIX *= FLOAT/INT */
+ mul_vn_fl(mat1->matrix, mat1->num_row * mat1->num_col, scalar);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Inplace element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(mat1);
+ Py_INCREF(m1);
+ return m1;
}
/*------------------------obj @ obj------------------------------
* matrix multiplication */
static PyObject *Matrix_matmul(PyObject *m1, PyObject *m2)
{
- int vec_size;
-
- MatrixObject *mat1 = NULL, *mat2 = NULL;
-
- if (MatrixObject_Check(m1)) {
- mat1 = (MatrixObject *)m1;
- if (BaseMath_ReadCallback(mat1) == -1) {
- return NULL;
- }
- }
- if (MatrixObject_Check(m2)) {
- mat2 = (MatrixObject *)m2;
- if (BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
- }
-
- if (mat1 && mat2) {
- /* MATRIX @ MATRIX */
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
-
- int col, row, item;
-
- if (mat1->num_col != mat2->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "matrix1 * matrix2: matrix1 number of columns "
- "and the matrix2 number of rows must be the same");
- return NULL;
- }
-
- for (col = 0; col < mat2->num_col; col++) {
- for (row = 0; row < mat1->num_row; row++) {
- double dot = 0.0f;
- for (item = 0; item < mat1->num_col; item++) {
- dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
- }
- mat[(col * mat1->num_row) + row] = (float)dot;
- }
- }
-
- return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
- }
- else if (mat1) {
- /* MATRIX @ VECTOR */
- if (VectorObject_Check(m2)) {
- VectorObject *vec2 = (VectorObject *)m2;
- float tvec[MATRIX_MAX_DIM];
- if (BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
- if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
- return NULL;
- }
-
- if (mat1->num_col == 4 && vec2->size == 3) {
- vec_size = 3;
- }
- else {
- vec_size = mat1->num_row;
- }
-
- return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(m2));
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Matrix multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
+ int vec_size;
+
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
+
+ if (MatrixObject_Check(m1)) {
+ mat1 = (MatrixObject *)m1;
+ if (BaseMath_ReadCallback(mat1) == -1) {
+ return NULL;
+ }
+ }
+ if (MatrixObject_Check(m2)) {
+ mat2 = (MatrixObject *)m2;
+ if (BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (mat1 && mat2) {
+ /* MATRIX @ MATRIX */
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+
+ int col, row, item;
+
+ if (mat1->num_col != mat2->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "matrix1 * matrix2: matrix1 number of columns "
+ "and the matrix2 number of rows must be the same");
+ return NULL;
+ }
+
+ for (col = 0; col < mat2->num_col; col++) {
+ for (row = 0; row < mat1->num_row; row++) {
+ double dot = 0.0f;
+ for (item = 0; item < mat1->num_col; item++) {
+ dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
+ }
+ mat[(col * mat1->num_row) + row] = (float)dot;
+ }
+ }
+
+ return Matrix_CreatePyObject(mat, mat2->num_col, mat1->num_row, Py_TYPE(mat1));
+ }
+ else if (mat1) {
+ /* MATRIX @ VECTOR */
+ if (VectorObject_Check(m2)) {
+ VectorObject *vec2 = (VectorObject *)m2;
+ float tvec[MATRIX_MAX_DIM];
+ if (BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+ if (column_vector_multiplication(tvec, vec2, mat1) == -1) {
+ return NULL;
+ }
+
+ if (mat1->num_col == 4 && vec2->size == 3) {
+ vec_size = 3;
+ }
+ else {
+ vec_size = mat1->num_row;
+ }
+
+ return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(m2));
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Matrix multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
}
/*------------------------obj @= obj------------------------------
* inplace matrix multiplication */
static PyObject *Matrix_imatmul(PyObject *m1, PyObject *m2)
{
- MatrixObject *mat1 = NULL, *mat2 = NULL;
-
- if (MatrixObject_Check(m1)) {
- mat1 = (MatrixObject *)m1;
- if (BaseMath_ReadCallback(mat1) == -1) {
- return NULL;
- }
- }
- if (MatrixObject_Check(m2)) {
- mat2 = (MatrixObject *)m2;
- if (BaseMath_ReadCallback(mat2) == -1) {
- return NULL;
- }
- }
-
- if (mat1 && mat2) {
- /* MATRIX @= MATRIX */
- float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
- int col, row, item;
-
- if (mat1->num_col != mat2->num_row) {
- PyErr_SetString(PyExc_ValueError,
- "matrix1 * matrix2: matrix1 number of columns "
- "and the matrix2 number of rows must be the same");
- return NULL;
- }
-
- for (col = 0; col < mat2->num_col; col++) {
- for (row = 0; row < mat1->num_row; row++) {
- double dot = 0.0f;
- for (item = 0; item < mat1->num_col; item++) {
- dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
- }
- /* store in new matrix as overwriting original at this point will cause
- * subsequent iterations to use incorrect values */
- mat[(col * mat1->num_row) + row] = (float)dot;
- }
- }
-
- /* copy matrix back */
- memcpy(mat1->matrix, mat, (mat1->num_row * mat1->num_col) * sizeof(float));
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Inplace matrix multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(m1)->tp_name, Py_TYPE(m2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(mat1);
- Py_INCREF(m1);
- return m1;
+ MatrixObject *mat1 = NULL, *mat2 = NULL;
+
+ if (MatrixObject_Check(m1)) {
+ mat1 = (MatrixObject *)m1;
+ if (BaseMath_ReadCallback(mat1) == -1) {
+ return NULL;
+ }
+ }
+ if (MatrixObject_Check(m2)) {
+ mat2 = (MatrixObject *)m2;
+ if (BaseMath_ReadCallback(mat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (mat1 && mat2) {
+ /* MATRIX @= MATRIX */
+ float mat[MATRIX_MAX_DIM * MATRIX_MAX_DIM];
+ int col, row, item;
+
+ if (mat1->num_col != mat2->num_row) {
+ PyErr_SetString(PyExc_ValueError,
+ "matrix1 * matrix2: matrix1 number of columns "
+ "and the matrix2 number of rows must be the same");
+ return NULL;
+ }
+
+ for (col = 0; col < mat2->num_col; col++) {
+ for (row = 0; row < mat1->num_row; row++) {
+ double dot = 0.0f;
+ for (item = 0; item < mat1->num_col; item++) {
+ dot += (double)(MATRIX_ITEM(mat1, row, item) * MATRIX_ITEM(mat2, item, col));
+ }
+ /* store in new matrix as overwriting original at this point will cause
+ * subsequent iterations to use incorrect values */
+ mat[(col * mat1->num_row) + row] = (float)dot;
+ }
+ }
+
+ /* copy matrix back */
+ memcpy(mat1->matrix, mat, (mat1->num_row * mat1->num_col) * sizeof(float));
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Inplace matrix multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(m1)->tp_name,
+ Py_TYPE(m2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(mat1);
+ Py_INCREF(m1);
+ return m1;
}
/*-----------------PROTOCOL DECLARATIONS--------------------------*/
static PySequenceMethods Matrix_SeqMethods = {
- (lenfunc) Matrix_len, /* sq_length */
- (binaryfunc) NULL, /* sq_concat */
- (ssizeargfunc) NULL, /* sq_repeat */
- (ssizeargfunc) Matrix_item_row, /* sq_item */
- (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
- (ssizeobjargproc) Matrix_ass_item_row, /* sq_ass_item */
- (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
- (objobjproc) NULL, /* sq_contains */
- (binaryfunc) NULL, /* sq_inplace_concat */
- (ssizeargfunc) NULL, /* sq_inplace_repeat */
+ (lenfunc)Matrix_len, /* sq_length */
+ (binaryfunc)NULL, /* sq_concat */
+ (ssizeargfunc)NULL, /* sq_repeat */
+ (ssizeargfunc)Matrix_item_row, /* sq_item */
+ (ssizessizeargfunc)NULL, /* sq_slice, deprecated */
+ (ssizeobjargproc)Matrix_ass_item_row, /* sq_ass_item */
+ (ssizessizeobjargproc)NULL, /* sq_ass_slice, deprecated */
+ (objobjproc)NULL, /* sq_contains */
+ (binaryfunc)NULL, /* sq_inplace_concat */
+ (ssizeargfunc)NULL, /* sq_inplace_repeat */
};
-
static PyObject *Matrix_subscript(MatrixObject *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 += self->num_row;
- }
- return Matrix_item_row(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Matrix_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with matrices");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "matrix indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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 += self->num_row;
+ }
+ return Matrix_item_row(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Matrix_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrices");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static int Matrix_ass_subscript(MatrixObject *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 += self->num_row;
- }
- return Matrix_ass_item_row(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
- return -1;
- }
-
- if (step == 1) {
- return Matrix_ass_slice(self, start, stop, value);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with matrices");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "matrix indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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 += self->num_row;
+ }
+ return Matrix_ass_item_row(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->num_row, &start, &stop, &step, &slicelength) < 0) {
+ return -1;
+ }
+
+ if (step == 1) {
+ return Matrix_ass_slice(self, start, stop, value);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrices");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
static PyMappingMethods Matrix_AsMapping = {
- (lenfunc)Matrix_len,
- (binaryfunc)Matrix_subscript,
- (objobjargproc)Matrix_ass_subscript,
+ (lenfunc)Matrix_len,
+ (binaryfunc)Matrix_subscript,
+ (objobjargproc)Matrix_ass_subscript,
};
-
static PyNumberMethods Matrix_NumMethods = {
- (binaryfunc) Matrix_add, /*nb_add*/
- (binaryfunc) Matrix_sub, /*nb_subtract*/
- (binaryfunc) Matrix_mul, /*nb_multiply*/
- NULL, /*nb_remainder*/
- NULL, /*nb_divmod*/
- NULL, /*nb_power*/
- (unaryfunc) 0, /*nb_negative*/
- (unaryfunc) 0, /*tp_positive*/
- (unaryfunc) 0, /*tp_absolute*/
- (inquiry) 0, /*tp_bool*/
- (unaryfunc) Matrix_inverted_noargs, /*nb_invert*/
- NULL, /*nb_lshift*/
- (binaryfunc)0, /*nb_rshift*/
- NULL, /*nb_and*/
- NULL, /*nb_xor*/
- NULL, /*nb_or*/
- NULL, /*nb_int*/
- NULL, /*nb_reserved*/
- NULL, /*nb_float*/
- NULL, /* nb_inplace_add */
- NULL, /* nb_inplace_subtract */
- (binaryfunc) Matrix_imul, /* nb_inplace_multiply */
- NULL, /* nb_inplace_remainder */
- NULL, /* nb_inplace_power */
- NULL, /* nb_inplace_lshift */
- NULL, /* nb_inplace_rshift */
- NULL, /* nb_inplace_and */
- NULL, /* nb_inplace_xor */
- NULL, /* nb_inplace_or */
- NULL, /* nb_floor_divide */
- NULL, /* nb_true_divide */
- NULL, /* nb_inplace_floor_divide */
- NULL, /* nb_inplace_true_divide */
- NULL, /* nb_index */
- (binaryfunc) Matrix_matmul, /* nb_matrix_multiply */
- (binaryfunc) Matrix_imatmul, /* nb_inplace_matrix_multiply */
+ (binaryfunc)Matrix_add, /*nb_add*/
+ (binaryfunc)Matrix_sub, /*nb_subtract*/
+ (binaryfunc)Matrix_mul, /*nb_multiply*/
+ NULL, /*nb_remainder*/
+ NULL, /*nb_divmod*/
+ NULL, /*nb_power*/
+ (unaryfunc)0, /*nb_negative*/
+ (unaryfunc)0, /*tp_positive*/
+ (unaryfunc)0, /*tp_absolute*/
+ (inquiry)0, /*tp_bool*/
+ (unaryfunc)Matrix_inverted_noargs, /*nb_invert*/
+ NULL, /*nb_lshift*/
+ (binaryfunc)0, /*nb_rshift*/
+ NULL, /*nb_and*/
+ NULL, /*nb_xor*/
+ NULL, /*nb_or*/
+ NULL, /*nb_int*/
+ NULL, /*nb_reserved*/
+ NULL, /*nb_float*/
+ NULL, /* nb_inplace_add */
+ NULL, /* nb_inplace_subtract */
+ (binaryfunc)Matrix_imul, /* nb_inplace_multiply */
+ NULL, /* nb_inplace_remainder */
+ NULL, /* nb_inplace_power */
+ NULL, /* nb_inplace_lshift */
+ NULL, /* nb_inplace_rshift */
+ NULL, /* nb_inplace_and */
+ NULL, /* nb_inplace_xor */
+ NULL, /* nb_inplace_or */
+ NULL, /* nb_floor_divide */
+ NULL, /* nb_true_divide */
+ NULL, /* nb_inplace_floor_divide */
+ NULL, /* nb_inplace_true_divide */
+ NULL, /* nb_index */
+ (binaryfunc)Matrix_matmul, /* nb_matrix_multiply */
+ (binaryfunc)Matrix_imatmul, /* nb_inplace_matrix_multiply */
};
-PyDoc_STRVAR(Matrix_translation_doc,
-"The translation component of the matrix.\n\n:type: Vector"
-);
+PyDoc_STRVAR(Matrix_translation_doc, "The translation component of the matrix.\n\n:type: Vector");
static PyObject *Matrix_translation_get(MatrixObject *self, void *UNUSED(closure))
{
- PyObject *ret;
+ PyObject *ret;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- /*must be 4x4 square matrix*/
- if (self->num_row != 4 || self->num_col != 4) {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.translation: "
- "inappropriate matrix size, must be 4x4");
- return NULL;
- }
+ /*must be 4x4 square matrix*/
+ if (self->num_row != 4 || self->num_col != 4) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.translation: "
+ "inappropriate matrix size, must be 4x4");
+ return NULL;
+ }
- ret = (PyObject *)Vector_CreatePyObject_cb((PyObject *)self, 3, mathutils_matrix_translation_cb_index, 3);
+ ret = (PyObject *)Vector_CreatePyObject_cb(
+ (PyObject *)self, 3, mathutils_matrix_translation_cb_index, 3);
- return ret;
+ return ret;
}
static int Matrix_translation_set(MatrixObject *self, PyObject *value, void *UNUSED(closure))
{
- float tvec[3];
+ float tvec[3];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- /*must be 4x4 square matrix*/
- if (self->num_row != 4 || self->num_col != 4) {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.translation: "
- "inappropriate matrix size, must be 4x4");
- return -1;
- }
+ /*must be 4x4 square matrix*/
+ if (self->num_row != 4 || self->num_col != 4) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.translation: "
+ "inappropriate matrix size, must be 4x4");
+ return -1;
+ }
- if ((mathutils_array_parse(tvec, 3, 3, value, "Matrix.translation")) == -1) {
- return -1;
- }
+ if ((mathutils_array_parse(tvec, 3, 3, value, "Matrix.translation")) == -1) {
+ return -1;
+ }
- copy_v3_v3(((float (*)[4])self->matrix)[3], tvec);
+ copy_v3_v3(((float(*)[4])self->matrix)[3], tvec);
- (void)BaseMath_WriteCallback(self);
+ (void)BaseMath_WriteCallback(self);
- return 0;
+ return 0;
}
PyDoc_STRVAR(Matrix_row_doc,
-"Access the matrix by rows (default), (read-only).\n\n:type: Matrix Access"
-);
+ "Access the matrix by rows (default), (read-only).\n\n:type: Matrix Access");
static PyObject *Matrix_row_get(MatrixObject *self, void *UNUSED(closure))
{
- return MatrixAccess_CreatePyObject(self, MAT_ACCESS_ROW);
+ return MatrixAccess_CreatePyObject(self, MAT_ACCESS_ROW);
}
-PyDoc_STRVAR(Matrix_col_doc,
-"Access the matrix by columns, 3x3 and 4x4 only, (read-only).\n\n:type: Matrix Access"
-);
+PyDoc_STRVAR(
+ Matrix_col_doc,
+ "Access the matrix by columns, 3x3 and 4x4 only, (read-only).\n\n:type: Matrix Access");
static PyObject *Matrix_col_get(MatrixObject *self, void *UNUSED(closure))
{
- return MatrixAccess_CreatePyObject(self, MAT_ACCESS_COL);
+ return MatrixAccess_CreatePyObject(self, MAT_ACCESS_COL);
}
PyDoc_STRVAR(Matrix_median_scale_doc,
-"The average scale applied to each axis (read-only).\n\n:type: float"
-);
+ "The average scale applied to each axis (read-only).\n\n:type: float");
static PyObject *Matrix_median_scale_get(MatrixObject *self, void *UNUSED(closure))
{
- float mat[3][3];
+ float mat[3][3];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- /*must be 3-4 cols, 3-4 rows, square matrix*/
- if ((self->num_row < 3) || (self->num_col < 3)) {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.median_scale: "
- "inappropriate matrix size, 3x3 minimum");
- return NULL;
- }
+ /*must be 3-4 cols, 3-4 rows, square matrix*/
+ if ((self->num_row < 3) || (self->num_col < 3)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.median_scale: "
+ "inappropriate matrix size, 3x3 minimum");
+ return NULL;
+ }
- matrix_as_3x3(mat, self);
+ matrix_as_3x3(mat, self);
- return PyFloat_FromDouble(mat3_to_scale(mat));
+ return PyFloat_FromDouble(mat3_to_scale(mat));
}
PyDoc_STRVAR(Matrix_is_negative_doc,
-"True if this matrix results in a negative scale, 3x3 and 4x4 only, (read-only).\n\n:type: bool"
-);
+ "True if this matrix results in a negative scale, 3x3 and 4x4 only, "
+ "(read-only).\n\n:type: bool");
static PyObject *Matrix_is_negative_get(MatrixObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- /*must be 3-4 cols, 3-4 rows, square matrix*/
- if (self->num_row == 4 && self->num_col == 4) {
- return PyBool_FromLong(is_negative_m4((float (*)[4])self->matrix));
- }
- else if (self->num_row == 3 && self->num_col == 3) {
- return PyBool_FromLong(is_negative_m3((float (*)[3])self->matrix));
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.is_negative: "
- "inappropriate matrix size - expects 3x3 or 4x4 matrix");
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ /*must be 3-4 cols, 3-4 rows, square matrix*/
+ if (self->num_row == 4 && self->num_col == 4) {
+ return PyBool_FromLong(is_negative_m4((float(*)[4])self->matrix));
+ }
+ else if (self->num_row == 3 && self->num_col == 3) {
+ return PyBool_FromLong(is_negative_m3((float(*)[3])self->matrix));
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.is_negative: "
+ "inappropriate matrix size - expects 3x3 or 4x4 matrix");
+ return NULL;
+ }
}
PyDoc_STRVAR(Matrix_is_orthogonal_doc,
-"True if this matrix is orthogonal, 3x3 and 4x4 only, (read-only).\n\n:type: bool"
-);
+ "True if this matrix is orthogonal, 3x3 and 4x4 only, (read-only).\n\n:type: bool");
static PyObject *Matrix_is_orthogonal_get(MatrixObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- /*must be 3-4 cols, 3-4 rows, square matrix*/
- if (self->num_row == 4 && self->num_col == 4) {
- return PyBool_FromLong(is_orthonormal_m4((float (*)[4])self->matrix));
- }
- else if (self->num_row == 3 && self->num_col == 3) {
- return PyBool_FromLong(is_orthonormal_m3((float (*)[3])self->matrix));
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.is_orthogonal: "
- "inappropriate matrix size - expects 3x3 or 4x4 matrix");
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ /*must be 3-4 cols, 3-4 rows, square matrix*/
+ if (self->num_row == 4 && self->num_col == 4) {
+ return PyBool_FromLong(is_orthonormal_m4((float(*)[4])self->matrix));
+ }
+ else if (self->num_row == 3 && self->num_col == 3) {
+ return PyBool_FromLong(is_orthonormal_m3((float(*)[3])self->matrix));
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.is_orthogonal: "
+ "inappropriate matrix size - expects 3x3 or 4x4 matrix");
+ return NULL;
+ }
}
PyDoc_STRVAR(Matrix_is_orthogonal_axis_vectors_doc,
-"True if this matrix has got orthogonal axis vectors, 3x3 and 4x4 only, (read-only).\n\n:type: bool"
-);
+ "True if this matrix has got orthogonal axis vectors, 3x3 and 4x4 only, "
+ "(read-only).\n\n:type: bool");
static PyObject *Matrix_is_orthogonal_axis_vectors_get(MatrixObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- /*must be 3-4 cols, 3-4 rows, square matrix*/
- if (self->num_row == 4 && self->num_col == 4) {
- return PyBool_FromLong(is_orthogonal_m4((float (*)[4])self->matrix));
- }
- else if (self->num_row == 3 && self->num_col == 3) {
- return PyBool_FromLong(is_orthogonal_m3((float (*)[3])self->matrix));
- }
- else {
- PyErr_SetString(PyExc_AttributeError,
- "Matrix.is_orthogonal_axis_vectors: "
- "inappropriate matrix size - expects 3x3 or 4x4 matrix");
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ /*must be 3-4 cols, 3-4 rows, square matrix*/
+ if (self->num_row == 4 && self->num_col == 4) {
+ return PyBool_FromLong(is_orthogonal_m4((float(*)[4])self->matrix));
+ }
+ else if (self->num_row == 3 && self->num_col == 3) {
+ return PyBool_FromLong(is_orthogonal_m3((float(*)[3])self->matrix));
+ }
+ else {
+ PyErr_SetString(PyExc_AttributeError,
+ "Matrix.is_orthogonal_axis_vectors: "
+ "inappropriate matrix size - expects 3x3 or 4x4 matrix");
+ return NULL;
+ }
}
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Matrix_getseters[] = {
- {(char *)"median_scale", (getter)Matrix_median_scale_get, (setter)NULL, Matrix_median_scale_doc, NULL},
- {(char *)"translation", (getter)Matrix_translation_get, (setter)Matrix_translation_set, Matrix_translation_doc, NULL},
- {(char *)"row", (getter)Matrix_row_get, (setter)NULL, Matrix_row_doc, NULL},
- {(char *)"col", (getter)Matrix_col_get, (setter)NULL, Matrix_col_doc, NULL},
- {(char *)"is_negative", (getter)Matrix_is_negative_get, (setter)NULL, Matrix_is_negative_doc, NULL},
- {(char *)"is_orthogonal", (getter)Matrix_is_orthogonal_get, (setter)NULL, Matrix_is_orthogonal_doc, NULL},
- {(char *)"is_orthogonal_axis_vectors", (getter)Matrix_is_orthogonal_axis_vectors_get, (setter)NULL, Matrix_is_orthogonal_axis_vectors_doc, NULL},
- {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
- {(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
- {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"median_scale",
+ (getter)Matrix_median_scale_get,
+ (setter)NULL,
+ Matrix_median_scale_doc,
+ NULL},
+ {(char *)"translation",
+ (getter)Matrix_translation_get,
+ (setter)Matrix_translation_set,
+ Matrix_translation_doc,
+ NULL},
+ {(char *)"row", (getter)Matrix_row_get, (setter)NULL, Matrix_row_doc, NULL},
+ {(char *)"col", (getter)Matrix_col_get, (setter)NULL, Matrix_col_doc, NULL},
+ {(char *)"is_negative",
+ (getter)Matrix_is_negative_get,
+ (setter)NULL,
+ Matrix_is_negative_doc,
+ NULL},
+ {(char *)"is_orthogonal",
+ (getter)Matrix_is_orthogonal_get,
+ (setter)NULL,
+ Matrix_is_orthogonal_doc,
+ NULL},
+ {(char *)"is_orthogonal_axis_vectors",
+ (getter)Matrix_is_orthogonal_axis_vectors_get,
+ (setter)NULL,
+ Matrix_is_orthogonal_axis_vectors_doc,
+ NULL},
+ {(char *)"is_wrapped",
+ (getter)BaseMathObject_is_wrapped_get,
+ (setter)NULL,
+ BaseMathObject_is_wrapped_doc,
+ NULL},
+ {(char *)"is_frozen",
+ (getter)BaseMathObject_is_frozen_get,
+ (setter)NULL,
+ BaseMathObject_is_frozen_doc,
+ NULL},
+ {(char *)"owner",
+ (getter)BaseMathObject_owner_get,
+ (setter)NULL,
+ BaseMathObject_owner_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/*-----------------------METHOD DEFINITIONS ----------------------*/
static struct PyMethodDef Matrix_methods[] = {
- /* derived values */
- {"determinant", (PyCFunction) Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
- {"decompose", (PyCFunction) Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
-
- /* in place only */
- {"zero", (PyCFunction) Matrix_zero, METH_NOARGS, Matrix_zero_doc},
- {"identity", (PyCFunction) Matrix_identity, METH_NOARGS, Matrix_identity_doc},
-
- /* operate on original or copy */
- {"transpose", (PyCFunction) Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
- {"transposed", (PyCFunction) Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
- {"normalize", (PyCFunction) Matrix_normalize, METH_NOARGS, Matrix_normalize_doc},
- {"normalized", (PyCFunction) Matrix_normalized, METH_NOARGS, Matrix_normalized_doc},
- {"invert", (PyCFunction) Matrix_invert, METH_VARARGS, Matrix_invert_doc},
- {"inverted", (PyCFunction) Matrix_inverted, METH_VARARGS, Matrix_inverted_doc},
- {"invert_safe", (PyCFunction) Matrix_invert_safe, METH_NOARGS, Matrix_invert_safe_doc},
- {"inverted_safe", (PyCFunction) Matrix_inverted_safe, METH_NOARGS, Matrix_inverted_safe_doc},
- {"adjugate", (PyCFunction) Matrix_adjugate, METH_NOARGS, Matrix_adjugate_doc},
- {"adjugated", (PyCFunction) Matrix_adjugated, METH_NOARGS, Matrix_adjugated_doc},
- {"to_3x3", (PyCFunction) Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
- /* TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc}, */
- {"to_4x4", (PyCFunction) Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
- {"resize_4x4", (PyCFunction) Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
- {"rotate", (PyCFunction) Matrix_rotate, METH_O, Matrix_rotate_doc},
-
- /* return converted representation */
- {"to_euler", (PyCFunction) Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
- {"to_quaternion", (PyCFunction) Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
- {"to_scale", (PyCFunction) Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
- {"to_translation", (PyCFunction) Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
-
- /* operation between 2 or more types */
- {"lerp", (PyCFunction) Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
- {"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
- {"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
- {"__deepcopy__", (PyCFunction) Matrix_deepcopy, METH_VARARGS, Matrix_copy_doc},
-
- /* base-math methods */
- {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
-
- /* class methods */
- {"Identity", (PyCFunction) C_Matrix_Identity, METH_VARARGS | METH_CLASS, C_Matrix_Identity_doc},
- {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
- {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
- {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
- {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
- {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection, METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
- {NULL, NULL, 0, NULL},
+ /* derived values */
+ {"determinant", (PyCFunction)Matrix_determinant, METH_NOARGS, Matrix_determinant_doc},
+ {"decompose", (PyCFunction)Matrix_decompose, METH_NOARGS, Matrix_decompose_doc},
+
+ /* in place only */
+ {"zero", (PyCFunction)Matrix_zero, METH_NOARGS, Matrix_zero_doc},
+ {"identity", (PyCFunction)Matrix_identity, METH_NOARGS, Matrix_identity_doc},
+
+ /* operate on original or copy */
+ {"transpose", (PyCFunction)Matrix_transpose, METH_NOARGS, Matrix_transpose_doc},
+ {"transposed", (PyCFunction)Matrix_transposed, METH_NOARGS, Matrix_transposed_doc},
+ {"normalize", (PyCFunction)Matrix_normalize, METH_NOARGS, Matrix_normalize_doc},
+ {"normalized", (PyCFunction)Matrix_normalized, METH_NOARGS, Matrix_normalized_doc},
+ {"invert", (PyCFunction)Matrix_invert, METH_VARARGS, Matrix_invert_doc},
+ {"inverted", (PyCFunction)Matrix_inverted, METH_VARARGS, Matrix_inverted_doc},
+ {"invert_safe", (PyCFunction)Matrix_invert_safe, METH_NOARGS, Matrix_invert_safe_doc},
+ {"inverted_safe", (PyCFunction)Matrix_inverted_safe, METH_NOARGS, Matrix_inverted_safe_doc},
+ {"adjugate", (PyCFunction)Matrix_adjugate, METH_NOARGS, Matrix_adjugate_doc},
+ {"adjugated", (PyCFunction)Matrix_adjugated, METH_NOARGS, Matrix_adjugated_doc},
+ {"to_3x3", (PyCFunction)Matrix_to_3x3, METH_NOARGS, Matrix_to_3x3_doc},
+ /* TODO. {"resize_3x3", (PyCFunction) Matrix_resize3x3, METH_NOARGS, Matrix_resize3x3_doc}, */
+ {"to_4x4", (PyCFunction)Matrix_to_4x4, METH_NOARGS, Matrix_to_4x4_doc},
+ {"resize_4x4", (PyCFunction)Matrix_resize_4x4, METH_NOARGS, Matrix_resize_4x4_doc},
+ {"rotate", (PyCFunction)Matrix_rotate, METH_O, Matrix_rotate_doc},
+
+ /* return converted representation */
+ {"to_euler", (PyCFunction)Matrix_to_euler, METH_VARARGS, Matrix_to_euler_doc},
+ {"to_quaternion", (PyCFunction)Matrix_to_quaternion, METH_NOARGS, Matrix_to_quaternion_doc},
+ {"to_scale", (PyCFunction)Matrix_to_scale, METH_NOARGS, Matrix_to_scale_doc},
+ {"to_translation", (PyCFunction)Matrix_to_translation, METH_NOARGS, Matrix_to_translation_doc},
+
+ /* operation between 2 or more types */
+ {"lerp", (PyCFunction)Matrix_lerp, METH_VARARGS, Matrix_lerp_doc},
+ {"copy", (PyCFunction)Matrix_copy, METH_NOARGS, Matrix_copy_doc},
+ {"__copy__", (PyCFunction)Matrix_copy, METH_NOARGS, Matrix_copy_doc},
+ {"__deepcopy__", (PyCFunction)Matrix_deepcopy, METH_VARARGS, Matrix_copy_doc},
+
+ /* base-math methods */
+ {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
+
+ /* class methods */
+ {"Identity", (PyCFunction)C_Matrix_Identity, METH_VARARGS | METH_CLASS, C_Matrix_Identity_doc},
+ {"Rotation", (PyCFunction)C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
+ {"Scale", (PyCFunction)C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
+ {"Shear", (PyCFunction)C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
+ {"Translation",
+ (PyCFunction)C_Matrix_Translation,
+ METH_O | METH_CLASS,
+ C_Matrix_Translation_doc},
+ {"OrthoProjection",
+ (PyCFunction)C_Matrix_OrthoProjection,
+ METH_VARARGS | METH_CLASS,
+ C_Matrix_OrthoProjection_doc},
+ {NULL, NULL, 0, NULL},
};
/*------------------PY_OBECT DEFINITION--------------------------*/
-PyDoc_STRVAR(matrix_doc,
-".. class:: Matrix([rows])\n"
-"\n"
-" This object gives access to Matrices in Blender, supporting square and rectangular\n"
-" matrices from 2x2 up to 4x4.\n"
-"\n"
-" :param rows: Sequence of rows.\n"
-" When omitted, a 4x4 identity matrix is constructed.\n"
-" :type rows: 2d number sequence\n"
-);
+PyDoc_STRVAR(
+ matrix_doc,
+ ".. class:: Matrix([rows])\n"
+ "\n"
+ " This object gives access to Matrices in Blender, supporting square and rectangular\n"
+ " matrices from 2x2 up to 4x4.\n"
+ "\n"
+ " :param rows: Sequence of rows.\n"
+ " When omitted, a 4x4 identity matrix is constructed.\n"
+ " :type rows: 2d number sequence\n");
PyTypeObject matrix_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Matrix", /*tp_name*/
- sizeof(MatrixObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BaseMathObject_dealloc, /*tp_dealloc*/
- NULL, /*tp_print*/
- NULL, /*tp_getattr*/
- NULL, /*tp_setattr*/
- NULL, /*tp_compare*/
- (reprfunc) Matrix_repr, /*tp_repr*/
- &Matrix_NumMethods, /*tp_as_number*/
- &Matrix_SeqMethods, /*tp_as_sequence*/
- &Matrix_AsMapping, /*tp_as_mapping*/
- (hashfunc)Matrix_hash, /*tp_hash*/
- NULL, /*tp_call*/
+ PyVarObject_HEAD_INIT(NULL, 0) "Matrix", /*tp_name*/
+ sizeof(MatrixObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BaseMathObject_dealloc, /*tp_dealloc*/
+ NULL, /*tp_print*/
+ NULL, /*tp_getattr*/
+ NULL, /*tp_setattr*/
+ NULL, /*tp_compare*/
+ (reprfunc)Matrix_repr, /*tp_repr*/
+ &Matrix_NumMethods, /*tp_as_number*/
+ &Matrix_SeqMethods, /*tp_as_sequence*/
+ &Matrix_AsMapping, /*tp_as_mapping*/
+ (hashfunc)Matrix_hash, /*tp_hash*/
+ NULL, /*tp_call*/
#ifndef MATH_STANDALONE
- (reprfunc) Matrix_str, /*tp_str*/
+ (reprfunc)Matrix_str, /*tp_str*/
#else
- NULL, /*tp_str*/
+ NULL, /*tp_str*/
#endif
- NULL, /*tp_getattro*/
- NULL, /*tp_setattro*/
- NULL, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- matrix_doc, /*tp_doc*/
- (traverseproc)BaseMathObject_traverse, /* tp_traverse */
- (inquiry)BaseMathObject_clear, /*tp_clear*/
- (richcmpfunc)Matrix_richcmpr, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- NULL, /*tp_iter*/
- NULL, /*tp_iternext*/
- Matrix_methods, /*tp_methods*/
- NULL, /*tp_members*/
- Matrix_getseters, /*tp_getset*/
- NULL, /*tp_base*/
- NULL, /*tp_dict*/
- NULL, /*tp_descr_get*/
- NULL, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- NULL, /*tp_init*/
- NULL, /*tp_alloc*/
- Matrix_new, /*tp_new*/
- NULL, /*tp_free*/
- NULL, /*tp_is_gc*/
- NULL, /*tp_bases*/
- NULL, /*tp_mro*/
- NULL, /*tp_cache*/
- NULL, /*tp_subclasses*/
- NULL, /*tp_weaklist*/
- NULL, /*tp_del*/
+ NULL, /*tp_getattro*/
+ NULL, /*tp_setattro*/
+ NULL, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ matrix_doc, /*tp_doc*/
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /*tp_clear*/
+ (richcmpfunc)Matrix_richcmpr, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ NULL, /*tp_iter*/
+ NULL, /*tp_iternext*/
+ Matrix_methods, /*tp_methods*/
+ NULL, /*tp_members*/
+ Matrix_getseters, /*tp_getset*/
+ NULL, /*tp_base*/
+ NULL, /*tp_dict*/
+ NULL, /*tp_descr_get*/
+ NULL, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ NULL, /*tp_init*/
+ NULL, /*tp_alloc*/
+ Matrix_new, /*tp_new*/
+ NULL, /*tp_free*/
+ NULL, /*tp_is_gc*/
+ NULL, /*tp_bases*/
+ NULL, /*tp_mro*/
+ NULL, /*tp_cache*/
+ NULL, /*tp_subclasses*/
+ NULL, /*tp_weaklist*/
+ NULL, /*tp_del*/
};
-PyObject *Matrix_CreatePyObject(
- const float *mat,
- const unsigned short num_col, const unsigned short num_row,
- PyTypeObject *base_type)
-{
- MatrixObject *self;
- float *mat_alloc;
-
- /* matrix objects can be any 2-4row x 2-4col matrix */
- if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
- PyErr_SetString(PyExc_RuntimeError,
- "Matrix(): "
- "row and column sizes must be between 2 and 4");
- return NULL;
- }
-
- mat_alloc = PyMem_Malloc(num_col * num_row * sizeof(float));
- if (UNLIKELY(mat_alloc == NULL)) {
- PyErr_SetString(PyExc_MemoryError,
- "Matrix(): "
- "problem allocating data");
- return NULL;
- }
-
- self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
- if (self) {
- self->matrix = mat_alloc;
- self->num_col = num_col;
- self->num_row = num_row;
-
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- if (mat) { /*if a float array passed*/
- memcpy(self->matrix, mat, num_col * num_row * sizeof(float));
- }
- else if (num_col == num_row) {
- /* or if no arguments are passed return identity matrix for square matrices */
- matrix_identity_internal(self);
- }
- else {
- /* otherwise zero everything */
- memset(self->matrix, 0, num_col * num_row * sizeof(float));
- }
- self->flag = BASE_MATH_FLAG_DEFAULT;
- }
- else {
- PyMem_Free(mat_alloc);
- }
-
- return (PyObject *)self;
-}
-
-PyObject *Matrix_CreatePyObject_wrap(
- float *mat,
- const unsigned short num_col, const unsigned short num_row,
- PyTypeObject *base_type)
-{
- MatrixObject *self;
-
- /* matrix objects can be any 2-4row x 2-4col matrix */
- if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
- PyErr_SetString(PyExc_RuntimeError,
- "Matrix(): "
- "row and column sizes must be between 2 and 4");
- return NULL;
- }
-
- self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
- if (self) {
- self->num_col = num_col;
- self->num_row = num_row;
-
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- self->matrix = mat;
- self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
- }
- return (PyObject *) self;
+PyObject *Matrix_CreatePyObject(const float *mat,
+ const unsigned short num_col,
+ const unsigned short num_row,
+ PyTypeObject *base_type)
+{
+ MatrixObject *self;
+ float *mat_alloc;
+
+ /* matrix objects can be any 2-4row x 2-4col matrix */
+ if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Matrix(): "
+ "row and column sizes must be between 2 and 4");
+ return NULL;
+ }
+
+ mat_alloc = PyMem_Malloc(num_col * num_row * sizeof(float));
+ if (UNLIKELY(mat_alloc == NULL)) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Matrix(): "
+ "problem allocating data");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
+ if (self) {
+ self->matrix = mat_alloc;
+ self->num_col = num_col;
+ self->num_row = num_row;
+
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ if (mat) { /*if a float array passed*/
+ memcpy(self->matrix, mat, num_col * num_row * sizeof(float));
+ }
+ else if (num_col == num_row) {
+ /* or if no arguments are passed return identity matrix for square matrices */
+ matrix_identity_internal(self);
+ }
+ else {
+ /* otherwise zero everything */
+ memset(self->matrix, 0, num_col * num_row * sizeof(float));
+ }
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ }
+ else {
+ PyMem_Free(mat_alloc);
+ }
+
+ return (PyObject *)self;
+}
+
+PyObject *Matrix_CreatePyObject_wrap(float *mat,
+ const unsigned short num_col,
+ const unsigned short num_row,
+ PyTypeObject *base_type)
+{
+ MatrixObject *self;
+
+ /* matrix objects can be any 2-4row x 2-4col matrix */
+ if (num_col < 2 || num_col > 4 || num_row < 2 || num_row > 4) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Matrix(): "
+ "row and column sizes must be between 2 and 4");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(MatrixObject, matrix_Type, base_type);
+ if (self) {
+ self->num_col = num_col;
+ self->num_row = num_row;
+
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ self->matrix = mat;
+ self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
+ }
+ return (PyObject *)self;
}
PyObject *Matrix_CreatePyObject_cb(PyObject *cb_user,
- const unsigned short num_col, const unsigned short num_row,
- unsigned char cb_type, unsigned char cb_subtype)
-{
- MatrixObject *self = (MatrixObject *)Matrix_CreatePyObject(NULL, num_col, num_row, NULL);
- if (self) {
- Py_INCREF(cb_user);
- self->cb_user = cb_user;
- self->cb_type = cb_type;
- self->cb_subtype = cb_subtype;
- PyObject_GC_Track(self);
- }
- return (PyObject *) self;
+ const unsigned short num_col,
+ const unsigned short num_row,
+ unsigned char cb_type,
+ unsigned char cb_subtype)
+{
+ MatrixObject *self = (MatrixObject *)Matrix_CreatePyObject(NULL, num_col, num_row, NULL);
+ if (self) {
+ Py_INCREF(cb_user);
+ self->cb_user = cb_user;
+ self->cb_type = cb_type;
+ self->cb_subtype = cb_subtype;
+ PyObject_GC_Track(self);
+ }
+ return (PyObject *)self;
}
/**
@@ -3185,288 +3264,278 @@ PyObject *Matrix_CreatePyObject_cb(PyObject *cb_user,
*/
static bool Matrix_ParseCheck(MatrixObject *pymat)
{
- if (!MatrixObject_Check(pymat)) {
- PyErr_Format(PyExc_TypeError,
- "expected a mathutils.Matrix, not a %.200s",
- Py_TYPE(pymat)->tp_name);
- return 0;
- }
- /* sets error */
- if (BaseMath_ReadCallback(pymat) == -1) {
- return 0;
- }
- return 1;
+ if (!MatrixObject_Check(pymat)) {
+ PyErr_Format(
+ PyExc_TypeError, "expected a mathutils.Matrix, not a %.200s", Py_TYPE(pymat)->tp_name);
+ return 0;
+ }
+ /* sets error */
+ if (BaseMath_ReadCallback(pymat) == -1) {
+ return 0;
+ }
+ return 1;
}
int Matrix_ParseAny(PyObject *o, void *p)
{
- MatrixObject **pymat_p = p;
- MatrixObject *pymat = (MatrixObject *)o;
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
- if (!Matrix_ParseCheck(pymat)) {
- return 0;
- }
- *pymat_p = pymat;
- return 1;
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ *pymat_p = pymat;
+ return 1;
}
int Matrix_Parse3x3(PyObject *o, void *p)
{
- MatrixObject **pymat_p = p;
- MatrixObject *pymat = (MatrixObject *)o;
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
- if (!Matrix_ParseCheck(pymat)) {
- return 0;
- }
- if ((pymat->num_col != 3) ||
- (pymat->num_row != 3))
- {
- PyErr_SetString(PyExc_ValueError, "matrix must be 3x3");
- return 0;
- }
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ if ((pymat->num_col != 3) || (pymat->num_row != 3)) {
+ PyErr_SetString(PyExc_ValueError, "matrix must be 3x3");
+ return 0;
+ }
- *pymat_p = pymat;
- return 1;
+ *pymat_p = pymat;
+ return 1;
}
int Matrix_Parse4x4(PyObject *o, void *p)
{
- MatrixObject **pymat_p = p;
- MatrixObject *pymat = (MatrixObject *)o;
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
- if (!Matrix_ParseCheck(pymat)) {
- return 0;
- }
- if ((pymat->num_col != 4) ||
- (pymat->num_row != 4))
- {
- PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
- return 0;
- }
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ if ((pymat->num_col != 4) || (pymat->num_row != 4)) {
+ PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
+ return 0;
+ }
- *pymat_p = pymat;
- return 1;
+ *pymat_p = pymat;
+ return 1;
}
/* ----------------------------------------------------------------------------
* special type for alternate access */
typedef struct {
- PyObject_HEAD /* required python macro */
- MatrixObject *matrix_user;
- eMatrixAccess_t type;
+ PyObject_HEAD /* required python macro */
+ MatrixObject *matrix_user;
+ eMatrixAccess_t type;
} MatrixAccessObject;
static int MatrixAccess_traverse(MatrixAccessObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->matrix_user);
- return 0;
+ Py_VISIT(self->matrix_user);
+ return 0;
}
static int MatrixAccess_clear(MatrixAccessObject *self)
{
- Py_CLEAR(self->matrix_user);
- return 0;
+ Py_CLEAR(self->matrix_user);
+ return 0;
}
static void MatrixAccess_dealloc(MatrixAccessObject *self)
{
- if (self->matrix_user) {
- PyObject_GC_UnTrack(self);
- MatrixAccess_clear(self);
- }
+ if (self->matrix_user) {
+ PyObject_GC_UnTrack(self);
+ MatrixAccess_clear(self);
+ }
- Py_TYPE(self)->tp_free(self);
+ Py_TYPE(self)->tp_free(self);
}
/* sequence access */
static int MatrixAccess_len(MatrixAccessObject *self)
{
- return (self->type == MAT_ACCESS_ROW) ?
- self->matrix_user->num_row :
- self->matrix_user->num_col;
+ return (self->type == MAT_ACCESS_ROW) ? self->matrix_user->num_row : self->matrix_user->num_col;
}
static PyObject *MatrixAccess_slice(MatrixAccessObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
+ PyObject *tuple;
+ int count;
- /* row/col access */
- MatrixObject *matrix_user = self->matrix_user;
- int matrix_access_len;
- PyObject *(*Matrix_item_new)(MatrixObject *, int);
+ /* row/col access */
+ MatrixObject *matrix_user = self->matrix_user;
+ int matrix_access_len;
+ PyObject *(*Matrix_item_new)(MatrixObject *, int);
- if (self->type == MAT_ACCESS_ROW) {
- matrix_access_len = matrix_user->num_row;
- Matrix_item_new = Matrix_item_row;
- }
- else { /* MAT_ACCESS_ROW */
- matrix_access_len = matrix_user->num_col;
- Matrix_item_new = Matrix_item_col;
- }
+ if (self->type == MAT_ACCESS_ROW) {
+ matrix_access_len = matrix_user->num_row;
+ Matrix_item_new = Matrix_item_row;
+ }
+ else { /* MAT_ACCESS_ROW */
+ matrix_access_len = matrix_user->num_col;
+ Matrix_item_new = Matrix_item_col;
+ }
- CLAMP(begin, 0, matrix_access_len);
- if (end < 0) {
- end = (matrix_access_len + 1) + end;
- }
- CLAMP(end, 0, matrix_access_len);
- begin = MIN2(begin, end);
+ CLAMP(begin, 0, matrix_access_len);
+ if (end < 0) {
+ end = (matrix_access_len + 1) + end;
+ }
+ CLAMP(end, 0, matrix_access_len);
+ begin = MIN2(begin, end);
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, Matrix_item_new(matrix_user, count));
- }
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, Matrix_item_new(matrix_user, count));
+ }
- return tuple;
+ return tuple;
}
static PyObject *MatrixAccess_subscript(MatrixAccessObject *self, PyObject *item)
{
- MatrixObject *matrix_user = self->matrix_user;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i;
- i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return NULL;
- }
- if (self->type == MAT_ACCESS_ROW) {
- if (i < 0) {
- i += matrix_user->num_row;
- }
- return Matrix_item_row(matrix_user, i);
- }
- else { /* MAT_ACCESS_ROW */
- if (i < 0) {
- i += matrix_user->num_col;
- }
- return Matrix_item_col(matrix_user, i);
- }
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, MatrixAccess_len(self), &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return MatrixAccess_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with matrix accessors");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "matrix indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ MatrixObject *matrix_user = self->matrix_user;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i;
+ i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ if (self->type == MAT_ACCESS_ROW) {
+ if (i < 0) {
+ i += matrix_user->num_row;
+ }
+ return Matrix_item_row(matrix_user, i);
+ }
+ else { /* MAT_ACCESS_ROW */
+ if (i < 0) {
+ i += matrix_user->num_col;
+ }
+ return Matrix_item_col(matrix_user, i);
+ }
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, MatrixAccess_len(self), &start, &stop, &step, &slicelength) <
+ 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return MatrixAccess_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with matrix accessors");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static int MatrixAccess_ass_subscript(MatrixAccessObject *self, PyObject *item, PyObject *value)
{
- MatrixObject *matrix_user = self->matrix_user;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred()) {
- return -1;
- }
-
- if (self->type == MAT_ACCESS_ROW) {
- if (i < 0) {
- i += matrix_user->num_row;
- }
- return Matrix_ass_item_row(matrix_user, i, value);
- }
- else { /* MAT_ACCESS_ROW */
- if (i < 0) {
- i += matrix_user->num_col;
- }
- return Matrix_ass_item_col(matrix_user, i, value);
- }
-
- }
- /* TODO, slice */
- else {
- PyErr_Format(PyExc_TypeError,
- "matrix indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ MatrixObject *matrix_user = self->matrix_user;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred()) {
+ return -1;
+ }
+
+ if (self->type == MAT_ACCESS_ROW) {
+ if (i < 0) {
+ i += matrix_user->num_row;
+ }
+ return Matrix_ass_item_row(matrix_user, i, value);
+ }
+ else { /* MAT_ACCESS_ROW */
+ if (i < 0) {
+ i += matrix_user->num_col;
+ }
+ return Matrix_ass_item_col(matrix_user, i, value);
+ }
+ }
+ /* TODO, slice */
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "matrix indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
static PyObject *MatrixAccess_iter(MatrixAccessObject *self)
{
- /* Try get values from a collection */
- PyObject *ret;
- PyObject *iter = NULL;
- ret = MatrixAccess_slice(self, 0, MATRIX_MAX_DIM);
+ /* Try get values from a collection */
+ PyObject *ret;
+ PyObject *iter = NULL;
+ ret = MatrixAccess_slice(self, 0, MATRIX_MAX_DIM);
- /* we know this is a tuple so no need to PyIter_Check
- * otherwise it could be NULL (unlikely) if conversion failed */
- if (ret) {
- iter = PyObject_GetIter(ret);
- Py_DECREF(ret);
- }
+ /* we know this is a tuple so no need to PyIter_Check
+ * otherwise it could be NULL (unlikely) if conversion failed */
+ if (ret) {
+ iter = PyObject_GetIter(ret);
+ Py_DECREF(ret);
+ }
- return iter;
+ return iter;
}
static PyMappingMethods MatrixAccess_AsMapping = {
- (lenfunc)MatrixAccess_len,
- (binaryfunc)MatrixAccess_subscript,
- (objobjargproc) MatrixAccess_ass_subscript,
+ (lenfunc)MatrixAccess_len,
+ (binaryfunc)MatrixAccess_subscript,
+ (objobjargproc)MatrixAccess_ass_subscript,
};
PyTypeObject matrix_access_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MatrixAccess", /*tp_name*/
- sizeof(MatrixAccessObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)MatrixAccess_dealloc, /*tp_dealloc*/
- NULL, /*tp_print*/
- NULL, /*tp_getattr*/
- NULL, /*tp_setattr*/
- NULL, /*tp_compare*/
- NULL, /*tp_repr*/
- NULL, /*tp_as_number*/
- NULL /*&MatrixAccess_SeqMethods*/ /* TODO */, /*tp_as_sequence*/
- &MatrixAccess_AsMapping, /*tp_as_mapping*/
- NULL, /*tp_hash*/
- NULL, /*tp_call*/
- NULL, /*tp_str*/
- NULL, /*tp_getattro*/
- NULL, /*tp_setattro*/
- NULL, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- NULL, /*tp_doc*/
- (traverseproc)MatrixAccess_traverse,/*tp_traverse*/
- (inquiry)MatrixAccess_clear, /*tp_clear*/
- NULL /* (richcmpfunc)MatrixAccess_richcmpr */ /* TODO*/, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- (getiterfunc)MatrixAccess_iter, /* getiterfunc tp_iter; */
+ PyVarObject_HEAD_INIT(NULL, 0) "MatrixAccess", /*tp_name*/
+ sizeof(MatrixAccessObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)MatrixAccess_dealloc, /*tp_dealloc*/
+ NULL, /*tp_print*/
+ NULL, /*tp_getattr*/
+ NULL, /*tp_setattr*/
+ NULL, /*tp_compare*/
+ NULL, /*tp_repr*/
+ NULL, /*tp_as_number*/
+ NULL /*&MatrixAccess_SeqMethods*/ /* TODO */, /*tp_as_sequence*/
+ &MatrixAccess_AsMapping, /*tp_as_mapping*/
+ NULL, /*tp_hash*/
+ NULL, /*tp_call*/
+ NULL, /*tp_str*/
+ NULL, /*tp_getattro*/
+ NULL, /*tp_setattro*/
+ NULL, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ NULL, /*tp_doc*/
+ (traverseproc)MatrixAccess_traverse, /*tp_traverse*/
+ (inquiry)MatrixAccess_clear, /*tp_clear*/
+ NULL /* (richcmpfunc)MatrixAccess_richcmpr */ /* TODO*/, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ (getiterfunc)MatrixAccess_iter, /* getiterfunc tp_iter; */
};
static PyObject *MatrixAccess_CreatePyObject(MatrixObject *matrix, const eMatrixAccess_t type)
{
- MatrixAccessObject *matrix_access = (MatrixAccessObject *)PyObject_GC_New(MatrixObject, &matrix_access_Type);
+ MatrixAccessObject *matrix_access = (MatrixAccessObject *)PyObject_GC_New(MatrixObject,
+ &matrix_access_Type);
- matrix_access->matrix_user = matrix;
- Py_INCREF(matrix);
+ matrix_access->matrix_user = matrix;
+ Py_INCREF(matrix);
- matrix_access->type = type;
+ matrix_access->type = type;
- return (PyObject *)matrix_access;
+ return (PyObject *)matrix_access;
}
/* end special access
diff --git a/source/blender/python/mathutils/mathutils_Matrix.h b/source/blender/python/mathutils/mathutils_Matrix.h
index 0f47472c8fd..3b42e22a787 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.h
+++ b/source/blender/python/mathutils/mathutils_Matrix.h
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#ifndef __MATHUTILS_MATRIX_H__
#define __MATHUTILS_MATRIX_H__
@@ -33,23 +32,25 @@ extern PyTypeObject matrix_access_Type;
/* matrix[row][col] == MATRIX_ITEM_INDEX(matrix, row, col) */
#ifdef DEBUG
-# define MATRIX_ITEM_ASSERT(_mat, _row, _col) (BLI_assert(_row < (_mat)->num_row && _col < (_mat)->num_col))
+# define MATRIX_ITEM_ASSERT(_mat, _row, _col) \
+ (BLI_assert(_row < (_mat)->num_row && _col < (_mat)->num_col))
#else
# define MATRIX_ITEM_ASSERT(_mat, _row, _col) (void)0
#endif
#define MATRIX_ITEM_INDEX_NUMROW(_totrow, _row, _col) (((_totrow) * (_col)) + (_row))
-#define MATRIX_ITEM_INDEX(_mat, _row, _col) (MATRIX_ITEM_ASSERT(_mat, _row, _col),(((_mat)->num_row * (_col)) + (_row)))
-#define MATRIX_ITEM_PTR( _mat, _row, _col) ((_mat)->matrix + MATRIX_ITEM_INDEX(_mat, _row, _col))
-#define MATRIX_ITEM( _mat, _row, _col) ((_mat)->matrix [MATRIX_ITEM_INDEX(_mat, _row, _col)])
+#define MATRIX_ITEM_INDEX(_mat, _row, _col) \
+ (MATRIX_ITEM_ASSERT(_mat, _row, _col), (((_mat)->num_row * (_col)) + (_row)))
+#define MATRIX_ITEM_PTR(_mat, _row, _col) ((_mat)->matrix + MATRIX_ITEM_INDEX(_mat, _row, _col))
+#define MATRIX_ITEM(_mat, _row, _col) ((_mat)->matrix[MATRIX_ITEM_INDEX(_mat, _row, _col)])
#define MATRIX_COL_INDEX(_mat, _col) (MATRIX_ITEM_INDEX(_mat, 0, _col))
-#define MATRIX_COL_PTR( _mat, _col) ((_mat)->matrix + MATRIX_COL_INDEX(_mat, _col))
+#define MATRIX_COL_PTR(_mat, _col) ((_mat)->matrix + MATRIX_COL_INDEX(_mat, _col))
typedef struct {
- BASE_MATH_MEMBERS(matrix);
- unsigned short num_col;
- unsigned short num_row;
+ BASE_MATH_MEMBERS(matrix);
+ unsigned short num_col;
+ unsigned short num_row;
} MatrixObject;
/* struct data contains a pointer to the actual data that the
@@ -58,21 +59,20 @@ typedef struct {
* blender (stored in blend_data). This is an either/or struct not both */
/* prototypes */
-PyObject *Matrix_CreatePyObject(
- const float *mat,
- const unsigned short num_col, const unsigned short num_row,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Matrix_CreatePyObject_wrap(
- float *mat,
- const unsigned short num_col, const unsigned short num_row,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-PyObject *Matrix_CreatePyObject_cb(
- PyObject *user,
- const unsigned short num_col, const unsigned short num_row,
- unsigned char cb_type, unsigned char cb_subtype
- ) ATTR_WARN_UNUSED_RESULT;
+PyObject *Matrix_CreatePyObject(const float *mat,
+ const unsigned short num_col,
+ const unsigned short num_row,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT;
+PyObject *Matrix_CreatePyObject_wrap(float *mat,
+ const unsigned short num_col,
+ const unsigned short num_row,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+PyObject *Matrix_CreatePyObject_cb(PyObject *user,
+ const unsigned short num_col,
+ const unsigned short num_row,
+ unsigned char cb_type,
+ unsigned char cb_subtype) ATTR_WARN_UNUSED_RESULT;
/* PyArg_ParseTuple's "O&" formatting helpers. */
int Matrix_ParseAny(PyObject *o, void *p);
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c
index 422a1ff28fa..86da4511a2e 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.c
+++ b/source/blender/python/mathutils/mathutils_Quaternion.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -36,7 +35,7 @@
#define QUAT_SIZE 4
static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self);
-static void quat__axis_angle_sanitize(float axis[3], float *angle);
+static void quat__axis_angle_sanitize(float axis[3], float *angle);
static PyObject *Quaternion_copy(QuaternionObject *self);
static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args);
@@ -45,569 +44,556 @@ static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args);
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Quaternion_to_tuple_ext(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;
+ 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;
}
PyDoc_STRVAR(Quaternion_to_euler_doc,
-".. method:: to_euler(order, euler_compat)\n"
-"\n"
-" Return Euler representation of the quaternion.\n"
-"\n"
-" :arg order: Optional rotation order argument in\n"
-" ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
-" :type order: string\n"
-" :arg euler_compat: Optional euler argument the new euler will be made\n"
-" compatible with (no axis flipping between them).\n"
-" Useful for converting a series of matrices to animation curves.\n"
-" :type euler_compat: :class:`Euler`\n"
-" :return: Euler representation of the quaternion.\n"
-" :rtype: :class:`Euler`\n"
-);
+ ".. method:: to_euler(order, euler_compat)\n"
+ "\n"
+ " Return Euler representation of the quaternion.\n"
+ "\n"
+ " :arg order: Optional rotation order argument in\n"
+ " ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX'].\n"
+ " :type order: string\n"
+ " :arg euler_compat: Optional euler argument the new euler will be made\n"
+ " compatible with (no axis flipping between them).\n"
+ " Useful for converting a series of matrices to animation curves.\n"
+ " :type euler_compat: :class:`Euler`\n"
+ " :return: Euler representation of the quaternion.\n"
+ " :rtype: :class:`Euler`\n");
static PyObject *Quaternion_to_euler(QuaternionObject *self, PyObject *args)
{
- float tquat[4];
- float eul[3];
- const char *order_str = NULL;
- short order = EULER_ORDER_XYZ;
- EulerObject *eul_compat = NULL;
-
- if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
- return NULL;
- }
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (order_str) {
- order = euler_order_from_string(order_str, "Matrix.to_euler()");
-
- if (order == -1) {
- return NULL;
- }
- }
-
- normalize_qt_qt(tquat, self->quat);
-
- if (eul_compat) {
- if (BaseMath_ReadCallback(eul_compat) == -1) {
- return NULL;
- }
-
- if (order == EULER_ORDER_XYZ) {
- quat_to_compatible_eul(eul, eul_compat->eul, tquat);
- }
- else {
- quat_to_compatible_eulO(eul, eul_compat->eul, order, tquat);
- }
- }
- else {
- if (order == EULER_ORDER_XYZ) {
- quat_to_eul(eul, tquat);
- }
- else {
- quat_to_eulO(eul, order, tquat);
- }
- }
-
- return Euler_CreatePyObject(eul, order, NULL);
+ float tquat[4];
+ float eul[3];
+ const char *order_str = NULL;
+ short order = EULER_ORDER_XYZ;
+ EulerObject *eul_compat = NULL;
+
+ if (!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat)) {
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (order_str) {
+ order = euler_order_from_string(order_str, "Matrix.to_euler()");
+
+ if (order == -1) {
+ return NULL;
+ }
+ }
+
+ normalize_qt_qt(tquat, self->quat);
+
+ if (eul_compat) {
+ if (BaseMath_ReadCallback(eul_compat) == -1) {
+ return NULL;
+ }
+
+ if (order == EULER_ORDER_XYZ) {
+ quat_to_compatible_eul(eul, eul_compat->eul, tquat);
+ }
+ else {
+ quat_to_compatible_eulO(eul, eul_compat->eul, order, tquat);
+ }
+ }
+ else {
+ if (order == EULER_ORDER_XYZ) {
+ quat_to_eul(eul, tquat);
+ }
+ else {
+ quat_to_eulO(eul, order, tquat);
+ }
+ }
+
+ return Euler_CreatePyObject(eul, order, NULL);
}
PyDoc_STRVAR(Quaternion_to_matrix_doc,
-".. method:: to_matrix()\n"
-"\n"
-" Return a matrix representation of the quaternion.\n"
-"\n"
-" :return: A 3x3 rotation matrix representation of the quaternion.\n"
-" :rtype: :class:`Matrix`\n"
-);
+ ".. method:: to_matrix()\n"
+ "\n"
+ " Return a matrix representation of the quaternion.\n"
+ "\n"
+ " :return: A 3x3 rotation matrix representation of the quaternion.\n"
+ " :rtype: :class:`Matrix`\n");
static PyObject *Quaternion_to_matrix(QuaternionObject *self)
{
- float mat[9]; /* all values are set */
+ float mat[9]; /* all values are set */
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- quat_to_mat3((float (*)[3])mat, self->quat);
- return Matrix_CreatePyObject(mat, 3, 3, NULL);
+ quat_to_mat3((float(*)[3])mat, self->quat);
+ return Matrix_CreatePyObject(mat, 3, 3, NULL);
}
PyDoc_STRVAR(Quaternion_to_axis_angle_doc,
-".. method:: to_axis_angle()\n"
-"\n"
-" Return the axis, angle representation of the quaternion.\n"
-"\n"
-" :return: axis, angle.\n"
-" :rtype: (:class:`Vector`, float) pair\n"
-);
+ ".. method:: to_axis_angle()\n"
+ "\n"
+ " Return the axis, angle representation of the quaternion.\n"
+ "\n"
+ " :return: axis, angle.\n"
+ " :rtype: (:class:`Vector`, float) pair\n");
static PyObject *Quaternion_to_axis_angle(QuaternionObject *self)
{
- PyObject *ret;
+ PyObject *ret;
- float tquat[4];
+ float tquat[4];
- float axis[3];
- float angle;
+ float axis[3];
+ float angle;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- normalize_qt_qt(tquat, self->quat);
- quat_to_axis_angle(axis, &angle, tquat);
+ normalize_qt_qt(tquat, self->quat);
+ quat_to_axis_angle(axis, &angle, tquat);
- quat__axis_angle_sanitize(axis, &angle);
+ quat__axis_angle_sanitize(axis, &angle);
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- Vector_CreatePyObject(axis, 3, NULL),
- PyFloat_FromDouble(angle));
- return ret;
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, Vector_CreatePyObject(axis, 3, NULL), PyFloat_FromDouble(angle));
+ return ret;
}
-PyDoc_STRVAR(Quaternion_to_exponential_map_doc,
-".. method:: to_exponential_map()\n"
-"\n"
-" Return the exponential map representation of the quaternion.\n"
-"\n"
-" This representation consist of the rotation axis multiplied by the rotation angle."
-" Such a representation is useful for interpolation between multiple orientations.\n"
-"\n"
-" :return: exponential map.\n"
-" :rtype: :class:`Vector` of size 3\n"
-"\n"
-" To convert back to a quaternion, pass it to the :class:`Quaternion` constructor.\n"
-);
+PyDoc_STRVAR(
+ Quaternion_to_exponential_map_doc,
+ ".. method:: to_exponential_map()\n"
+ "\n"
+ " Return the exponential map representation of the quaternion.\n"
+ "\n"
+ " This representation consist of the rotation axis multiplied by the rotation angle."
+ " Such a representation is useful for interpolation between multiple orientations.\n"
+ "\n"
+ " :return: exponential map.\n"
+ " :rtype: :class:`Vector` of size 3\n"
+ "\n"
+ " To convert back to a quaternion, pass it to the :class:`Quaternion` constructor.\n");
static PyObject *Quaternion_to_exponential_map(QuaternionObject *self)
{
- float expmap[3];
+ float expmap[3];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- quat_to_expmap(expmap, self->quat);
- return Vector_CreatePyObject(expmap, 3, NULL);
+ quat_to_expmap(expmap, self->quat);
+ return Vector_CreatePyObject(expmap, 3, NULL);
}
PyDoc_STRVAR(Quaternion_cross_doc,
-".. method:: cross(other)\n"
-"\n"
-" Return the cross product of this quaternion and another.\n"
-"\n"
-" :arg other: The other quaternion to perform the cross product with.\n"
-" :type other: :class:`Quaternion`\n"
-" :return: The cross product.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. method:: cross(other)\n"
+ "\n"
+ " Return the cross product of this quaternion and another.\n"
+ "\n"
+ " :arg other: The other quaternion to perform the cross product with.\n"
+ " :type other: :class:`Quaternion`\n"
+ " :return: The cross product.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_cross(QuaternionObject *self, PyObject *value)
{
- float quat[QUAT_SIZE], tquat[QUAT_SIZE];
+ float quat[QUAT_SIZE], tquat[QUAT_SIZE];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
- "Quaternion.cross(other), invalid 'other' arg") == -1)
- {
- return NULL;
- }
+ if (mathutils_array_parse(
+ tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.cross(other), invalid 'other' arg") ==
+ -1) {
+ return NULL;
+ }
- mul_qt_qtqt(quat, self->quat, tquat);
- return Quaternion_CreatePyObject(quat, Py_TYPE(self));
+ mul_qt_qtqt(quat, self->quat, tquat);
+ return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_dot_doc,
-".. method:: dot(other)\n"
-"\n"
-" Return the dot product of this quaternion and another.\n"
-"\n"
-" :arg other: The other quaternion to perform the dot product with.\n"
-" :type other: :class:`Quaternion`\n"
-" :return: The dot product.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. method:: dot(other)\n"
+ "\n"
+ " Return the dot product of this quaternion and another.\n"
+ "\n"
+ " :arg other: The other quaternion to perform the dot product with.\n"
+ " :type other: :class:`Quaternion`\n"
+ " :return: The dot product.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_dot(QuaternionObject *self, PyObject *value)
{
- float tquat[QUAT_SIZE];
+ float tquat[QUAT_SIZE];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
- "Quaternion.dot(other), invalid 'other' arg") == -1)
- {
- return NULL;
- }
+ if (mathutils_array_parse(
+ tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.dot(other), invalid 'other' arg") ==
+ -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(dot_qtqt(self->quat, tquat));
+ return PyFloat_FromDouble(dot_qtqt(self->quat, tquat));
}
PyDoc_STRVAR(Quaternion_rotation_difference_doc,
-".. function:: rotation_difference(other)\n"
-"\n"
-" Returns a quaternion representing the rotational difference.\n"
-"\n"
-" :arg other: second quaternion.\n"
-" :type other: :class:`Quaternion`\n"
-" :return: the rotational difference between the two quat rotations.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: rotation_difference(other)\n"
+ "\n"
+ " Returns a quaternion representing the rotational difference.\n"
+ "\n"
+ " :arg other: second quaternion.\n"
+ " :type other: :class:`Quaternion`\n"
+ " :return: the rotational difference between the two quat rotations.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_rotation_difference(QuaternionObject *self, PyObject *value)
{
- float tquat[QUAT_SIZE], quat[QUAT_SIZE];
+ float tquat[QUAT_SIZE], quat[QUAT_SIZE];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
- "Quaternion.difference(other), invalid 'other' arg") == -1)
- {
- return NULL;
- }
+ if (mathutils_array_parse(tquat,
+ QUAT_SIZE,
+ QUAT_SIZE,
+ value,
+ "Quaternion.difference(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
- rotation_between_quats_to_quat(quat, self->quat, tquat);
+ rotation_between_quats_to_quat(quat, self->quat, tquat);
- return Quaternion_CreatePyObject(quat, Py_TYPE(self));
+ return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_slerp_doc,
-".. function:: slerp(other, factor)\n"
-"\n"
-" Returns the interpolation of two quaternions.\n"
-"\n"
-" :arg other: value to interpolate with.\n"
-" :type other: :class:`Quaternion`\n"
-" :arg factor: The interpolation value in [0.0, 1.0].\n"
-" :type factor: float\n"
-" :return: The interpolated rotation.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: slerp(other, factor)\n"
+ "\n"
+ " Returns the interpolation of two quaternions.\n"
+ "\n"
+ " :arg other: value to interpolate with.\n"
+ " :type other: :class:`Quaternion`\n"
+ " :arg factor: The interpolation value in [0.0, 1.0].\n"
+ " :type factor: float\n"
+ " :return: The interpolated rotation.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_slerp(QuaternionObject *self, PyObject *args)
{
- PyObject *value;
- float tquat[QUAT_SIZE], quat[QUAT_SIZE], fac;
-
- if (!PyArg_ParseTuple(args, "Of:slerp", &value, &fac)) {
- PyErr_SetString(PyExc_TypeError,
- "quat.slerp(): "
- "expected Quaternion types and float");
- return NULL;
- }
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (mathutils_array_parse(tquat, QUAT_SIZE, QUAT_SIZE, value,
- "Quaternion.slerp(other), invalid 'other' arg") == -1)
- {
- return NULL;
- }
-
- if (fac > 1.0f || fac < 0.0f) {
- PyErr_SetString(PyExc_ValueError,
- "quat.slerp(): "
- "interpolation factor must be between 0.0 and 1.0");
- return NULL;
- }
-
- interp_qt_qtqt(quat, self->quat, tquat, fac);
-
- return Quaternion_CreatePyObject(quat, Py_TYPE(self));
+ PyObject *value;
+ float tquat[QUAT_SIZE], quat[QUAT_SIZE], fac;
+
+ if (!PyArg_ParseTuple(args, "Of:slerp", &value, &fac)) {
+ PyErr_SetString(PyExc_TypeError,
+ "quat.slerp(): "
+ "expected Quaternion types and float");
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(
+ tquat, QUAT_SIZE, QUAT_SIZE, value, "Quaternion.slerp(other), invalid 'other' arg") ==
+ -1) {
+ return NULL;
+ }
+
+ if (fac > 1.0f || fac < 0.0f) {
+ PyErr_SetString(PyExc_ValueError,
+ "quat.slerp(): "
+ "interpolation factor must be between 0.0 and 1.0");
+ return NULL;
+ }
+
+ interp_qt_qtqt(quat, self->quat, tquat, fac);
+
+ return Quaternion_CreatePyObject(quat, Py_TYPE(self));
}
PyDoc_STRVAR(Quaternion_rotate_doc,
-".. method:: rotate(other)\n"
-"\n"
-" Rotates the quaternion by another mathutils value.\n"
-"\n"
-" :arg other: rotation component of mathutils value\n"
-" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
-);
+ ".. method:: rotate(other)\n"
+ "\n"
+ " Rotates the quaternion by another mathutils value.\n"
+ "\n"
+ " :arg other: rotation component of mathutils value\n"
+ " :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n");
static PyObject *Quaternion_rotate(QuaternionObject *self, PyObject *value)
{
- float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
- float tquat[4], length;
+ float self_rmat[3][3], other_rmat[3][3], rmat[3][3];
+ float tquat[4], length;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (mathutils_any_to_rotmat(other_rmat, value, "Quaternion.rotate(value)") == -1) {
- return NULL;
- }
+ if (mathutils_any_to_rotmat(other_rmat, value, "Quaternion.rotate(value)") == -1) {
+ return NULL;
+ }
- length = normalize_qt_qt(tquat, self->quat);
- quat_to_mat3(self_rmat, tquat);
- mul_m3_m3m3(rmat, other_rmat, self_rmat);
+ length = normalize_qt_qt(tquat, self->quat);
+ quat_to_mat3(self_rmat, tquat);
+ mul_m3_m3m3(rmat, other_rmat, self_rmat);
- mat3_to_quat(self->quat, rmat);
- mul_qt_fl(self->quat, length); /* maintain length after rotating */
+ mat3_to_quat(self->quat, rmat);
+ mul_qt_fl(self->quat, length); /* maintain length after rotating */
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
/* ----------------------------Quaternion.normalize()---------------- */
/* Normalize the quaternion. This may change the angle as well as the
* rotation axis, as all of (w, x, y, z) are scaled. */
PyDoc_STRVAR(Quaternion_normalize_doc,
-".. function:: normalize()\n"
-"\n"
-" Normalize the quaternion.\n"
-);
+ ".. function:: normalize()\n"
+ "\n"
+ " Normalize the quaternion.\n");
static PyObject *Quaternion_normalize(QuaternionObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- normalize_qt(self->quat);
+ normalize_qt(self->quat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_normalized_doc,
-".. function:: normalized()\n"
-"\n"
-" Return a new normalized quaternion.\n"
-"\n"
-" :return: a normalized copy.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: normalized()\n"
+ "\n"
+ " Return a new normalized quaternion.\n"
+ "\n"
+ " :return: a normalized copy.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_normalized(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
+ return quat__apply_to_copy((PyNoArgsFunction)Quaternion_normalize, self);
}
PyDoc_STRVAR(Quaternion_invert_doc,
-".. function:: invert()\n"
-"\n"
-" Set the quaternion to its inverse.\n"
-);
+ ".. function:: invert()\n"
+ "\n"
+ " Set the quaternion to its inverse.\n");
static PyObject *Quaternion_invert(QuaternionObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- invert_qt(self->quat);
+ invert_qt(self->quat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_inverted_doc,
-".. function:: inverted()\n"
-"\n"
-" Return a new, inverted quaternion.\n"
-"\n"
-" :return: the inverted value.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: inverted()\n"
+ "\n"
+ " Return a new, inverted quaternion.\n"
+ "\n"
+ " :return: the inverted value.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_inverted(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
+ return quat__apply_to_copy((PyNoArgsFunction)Quaternion_invert, self);
}
PyDoc_STRVAR(Quaternion_identity_doc,
-".. function:: identity()\n"
-"\n"
-" Set the quaternion to an identity quaternion.\n"
-"\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: identity()\n"
+ "\n"
+ " Set the quaternion to an identity quaternion.\n"
+ "\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_identity(QuaternionObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- unit_qt(self->quat);
+ unit_qt(self->quat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_negate_doc,
-".. function:: negate()\n"
-"\n"
-" Set the quaternion to its negative.\n"
-"\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: negate()\n"
+ "\n"
+ " Set the quaternion to its negative.\n"
+ "\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_negate(QuaternionObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- mul_qt_fl(self->quat, -1.0f);
+ mul_qt_fl(self->quat, -1.0f);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_conjugate_doc,
-".. function:: conjugate()\n"
-"\n"
-" Set the quaternion to its conjugate (negate x, y, z).\n"
-);
+ ".. function:: conjugate()\n"
+ "\n"
+ " Set the quaternion to its conjugate (negate x, y, z).\n");
static PyObject *Quaternion_conjugate(QuaternionObject *self)
{
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- conjugate_qt(self->quat);
+ conjugate_qt(self->quat);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Quaternion_conjugated_doc,
-".. function:: conjugated()\n"
-"\n"
-" Return a new conjugated quaternion.\n"
-"\n"
-" :return: a new quaternion.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. function:: conjugated()\n"
+ "\n"
+ " Return a new conjugated quaternion.\n"
+ "\n"
+ " :return: a new quaternion.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Quaternion_conjugated(QuaternionObject *self)
{
- return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
+ return quat__apply_to_copy((PyNoArgsFunction)Quaternion_conjugate, self);
}
PyDoc_STRVAR(Quaternion_copy_doc,
-".. function:: copy()\n"
-"\n"
-" Returns a copy of this quaternion.\n"
-"\n"
-" :return: A copy of the quaternion.\n"
-" :rtype: :class:`Quaternion`\n"
-"\n"
-" .. note:: use this to get a copy of a wrapped quaternion with\n"
-" no reference to the original data.\n"
-);
+ ".. function:: copy()\n"
+ "\n"
+ " Returns a copy of this quaternion.\n"
+ "\n"
+ " :return: A copy of the quaternion.\n"
+ " :rtype: :class:`Quaternion`\n"
+ "\n"
+ " .. note:: use this to get a copy of a wrapped quaternion with\n"
+ " no reference to the original data.\n");
static PyObject *Quaternion_copy(QuaternionObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Quaternion_CreatePyObject(self->quat, Py_TYPE(self));
+ return Quaternion_CreatePyObject(self->quat, Py_TYPE(self));
}
static PyObject *Quaternion_deepcopy(QuaternionObject *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return Quaternion_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return Quaternion_copy(self);
}
/* print the object to screen */
static PyObject *Quaternion_repr(QuaternionObject *self)
{
- PyObject *ret, *tuple;
+ PyObject *ret, *tuple;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- tuple = Quaternion_to_tuple_ext(self, -1);
+ tuple = Quaternion_to_tuple_ext(self, -1);
- ret = PyUnicode_FromFormat("Quaternion(%R)", tuple);
+ ret = PyUnicode_FromFormat("Quaternion(%R)", tuple);
- Py_DECREF(tuple);
- return ret;
+ Py_DECREF(tuple);
+ return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Quaternion_str(QuaternionObject *self)
{
- DynStr *ds;
+ DynStr *ds;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- ds = BLI_dynstr_new();
+ ds = BLI_dynstr_new();
- BLI_dynstr_appendf(ds, "<Quaternion (w=%.4f, x=%.4f, y=%.4f, z=%.4f)>",
- self->quat[0], self->quat[1], self->quat[2], self->quat[3]);
+ BLI_dynstr_appendf(ds,
+ "<Quaternion (w=%.4f, x=%.4f, y=%.4f, z=%.4f)>",
+ self->quat[0],
+ self->quat[1],
+ self->quat[2],
+ self->quat[3]);
- return mathutils_dynstr_to_py(ds); /* frees ds */
+ return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
static PyObject *Quaternion_richcmpr(PyObject *a, PyObject *b, int op)
{
- PyObject *res;
- int ok = -1; /* zero is true */
-
- if (QuaternionObject_Check(a) && QuaternionObject_Check(b)) {
- QuaternionObject *quatA = (QuaternionObject *)a;
- QuaternionObject *quatB = (QuaternionObject *)b;
-
- if (BaseMath_ReadCallback(quatA) == -1 || BaseMath_ReadCallback(quatB) == -1) {
- return NULL;
- }
-
- ok = (EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1)) ? 0 : -1;
- }
-
- switch (op) {
- case Py_NE:
- ok = !ok;
- ATTR_FALLTHROUGH;
- case Py_EQ:
- res = ok ? Py_False : Py_True;
- break;
-
- case Py_LT:
- case Py_LE:
- case Py_GT:
- case Py_GE:
- res = Py_NotImplemented;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- return Py_INCREF_RET(res);
+ PyObject *res;
+ int ok = -1; /* zero is true */
+
+ if (QuaternionObject_Check(a) && QuaternionObject_Check(b)) {
+ QuaternionObject *quatA = (QuaternionObject *)a;
+ QuaternionObject *quatB = (QuaternionObject *)b;
+
+ if (BaseMath_ReadCallback(quatA) == -1 || BaseMath_ReadCallback(quatB) == -1) {
+ return NULL;
+ }
+
+ ok = (EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1)) ? 0 : -1;
+ }
+
+ switch (op) {
+ case Py_NE:
+ ok = !ok;
+ ATTR_FALLTHROUGH;
+ case Py_EQ:
+ res = ok ? Py_False : Py_True;
+ break;
+
+ case Py_LT:
+ case Py_LE:
+ case Py_GT:
+ case Py_GE:
+ res = Py_NotImplemented;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ return Py_INCREF_RET(res);
}
static Py_hash_t Quaternion_hash(QuaternionObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- if (BaseMathObject_Prepare_ForHash(self) == -1) {
- return -1;
- }
+ if (BaseMathObject_Prepare_ForHash(self) == -1) {
+ return -1;
+ }
- return mathutils_array_hash(self->quat, QUAT_SIZE);
+ return mathutils_array_hash(self->quat, QUAT_SIZE);
}
/* ---------------------SEQUENCE PROTOCOLS------------------------ */
@@ -615,206 +601,202 @@ static Py_hash_t Quaternion_hash(QuaternionObject *self)
/* sequence length */
static int Quaternion_len(QuaternionObject *UNUSED(self))
{
- return QUAT_SIZE;
+ return QUAT_SIZE;
}
/* ----------------------------object[]--------------------------- */
/* sequence accessor (get) */
static PyObject *Quaternion_item(QuaternionObject *self, int i)
{
- if (i < 0) {
- i = QUAT_SIZE - i;
- }
-
- if (i < 0 || i >= QUAT_SIZE) {
- PyErr_SetString(PyExc_IndexError,
- "quaternion[attribute]: "
- "array index out of range");
- return NULL;
- }
-
- if (BaseMath_ReadIndexCallback(self, i) == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(self->quat[i]);
-
+ if (i < 0) {
+ i = QUAT_SIZE - i;
+ }
+
+ if (i < 0 || i >= QUAT_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "quaternion[attribute]: "
+ "array index out of range");
+ return NULL;
+ }
+
+ if (BaseMath_ReadIndexCallback(self, i) == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(self->quat[i]);
}
/* ----------------------------object[]------------------------- */
/* sequence accessor (set) */
static int Quaternion_ass_item(QuaternionObject *self, int i, PyObject *ob)
{
- float f;
-
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
-
- f = (float)PyFloat_AsDouble(ob);
-
- if (f == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError,
- "quaternion[index] = x: "
- "assigned value not a number");
- return -1;
- }
-
- if (i < 0) {
- i = QUAT_SIZE - i;
- }
-
- if (i < 0 || i >= QUAT_SIZE) {
- PyErr_SetString(PyExc_IndexError,
- "quaternion[attribute] = x: "
- "array assignment index out of range");
- return -1;
- }
- self->quat[i] = f;
-
- if (BaseMath_WriteIndexCallback(self, i) == -1) {
- return -1;
- }
-
- return 0;
+ float f;
+
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ f = (float)PyFloat_AsDouble(ob);
+
+ if (f == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError,
+ "quaternion[index] = x: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ if (i < 0) {
+ i = QUAT_SIZE - i;
+ }
+
+ if (i < 0 || i >= QUAT_SIZE) {
+ PyErr_SetString(PyExc_IndexError,
+ "quaternion[attribute] = x: "
+ "array assignment index out of range");
+ return -1;
+ }
+ self->quat[i] = f;
+
+ if (BaseMath_WriteIndexCallback(self, i) == -1) {
+ return -1;
+ }
+
+ return 0;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (get) */
static PyObject *Quaternion_slice(QuaternionObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- CLAMP(begin, 0, QUAT_SIZE);
- if (end < 0) {
- end = (QUAT_SIZE + 1) + end;
- }
- CLAMP(end, 0, QUAT_SIZE);
- begin = MIN2(begin, end);
-
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->quat[count]));
- }
-
- return tuple;
+ PyObject *tuple;
+ int count;
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ CLAMP(begin, 0, QUAT_SIZE);
+ if (end < 0) {
+ end = (QUAT_SIZE + 1) + end;
+ }
+ CLAMP(end, 0, QUAT_SIZE);
+ begin = MIN2(begin, end);
+
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->quat[count]));
+ }
+
+ return tuple;
}
/* ----------------------------object[z:y]------------------------ */
/* sequence slice (set) */
static int Quaternion_ass_slice(QuaternionObject *self, int begin, int end, PyObject *seq)
{
- int i, size;
- float quat[QUAT_SIZE];
-
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
-
- CLAMP(begin, 0, QUAT_SIZE);
- if (end < 0) {
- end = (QUAT_SIZE + 1) + end;
- }
- CLAMP(end, 0, QUAT_SIZE);
- begin = MIN2(begin, end);
-
- if ((size = mathutils_array_parse(quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1) {
- return -1;
- }
-
- if (size != (end - begin)) {
- PyErr_SetString(PyExc_ValueError,
- "quaternion[begin:end] = []: "
- "size mismatch in slice assignment");
- return -1;
- }
-
- /* parsed well - now set in vector */
- for (i = 0; i < size; i++) {
- self->quat[begin + i] = quat[i];
- }
-
- (void)BaseMath_WriteCallback(self);
- return 0;
+ int i, size;
+ float quat[QUAT_SIZE];
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ CLAMP(begin, 0, QUAT_SIZE);
+ if (end < 0) {
+ end = (QUAT_SIZE + 1) + end;
+ }
+ CLAMP(end, 0, QUAT_SIZE);
+ begin = MIN2(begin, end);
+
+ if ((size = mathutils_array_parse(
+ quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1) {
+ return -1;
+ }
+
+ if (size != (end - begin)) {
+ PyErr_SetString(PyExc_ValueError,
+ "quaternion[begin:end] = []: "
+ "size mismatch in slice assignment");
+ return -1;
+ }
+
+ /* parsed well - now set in vector */
+ for (i = 0; i < size; i++) {
+ self->quat[begin + i] = quat[i];
+ }
+
+ (void)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(item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Quaternion_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with quaternions");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "quaternion indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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(item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Quaternion_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with quaternions");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "quaternion indices must be integers, not %.200s",
+ Py_TYPE(item)->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(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_IndexError,
- "slice steps not supported with quaternion");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "quaternion indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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(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_IndexError, "slice steps not supported with quaternion");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "quaternion indices must be integers, not %.200s",
+ Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
/* ------------------------NUMERIC PROTOCOLS---------------------- */
@@ -822,757 +804,793 @@ static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyOb
/* addition */
static PyObject *Quaternion_add(PyObject *q1, PyObject *q2)
{
- float quat[QUAT_SIZE];
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
- PyErr_Format(PyExc_TypeError,
- "Quaternion addition: (%s + %s) "
- "invalid type for this operation",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
- }
- quat1 = (QuaternionObject *)q1;
- quat2 = (QuaternionObject *)q2;
-
- if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
-
- add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
- return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
+ float quat[QUAT_SIZE];
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Quaternion addition: (%s + %s) "
+ "invalid type for this operation",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
+ }
+ quat1 = (QuaternionObject *)q1;
+ quat2 = (QuaternionObject *)q2;
+
+ if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+
+ add_qt_qtqt(quat, quat1->quat, quat2->quat, 1.0f);
+ return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
}
/* ------------------------obj - obj------------------------------ */
/* subtraction */
static PyObject *Quaternion_sub(PyObject *q1, PyObject *q2)
{
- int x;
- float quat[QUAT_SIZE];
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
- PyErr_Format(PyExc_TypeError,
- "Quaternion subtraction: (%s - %s) "
- "invalid type for this operation",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
- }
-
- quat1 = (QuaternionObject *)q1;
- quat2 = (QuaternionObject *)q2;
-
- if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
-
- for (x = 0; x < QUAT_SIZE; x++) {
- quat[x] = quat1->quat[x] - quat2->quat[x];
- }
-
- return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
+ int x;
+ float quat[QUAT_SIZE];
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
+ PyErr_Format(PyExc_TypeError,
+ "Quaternion subtraction: (%s - %s) "
+ "invalid type for this operation",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
+ }
+
+ quat1 = (QuaternionObject *)q1;
+ quat2 = (QuaternionObject *)q2;
+
+ if (BaseMath_ReadCallback(quat1) == -1 || BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+
+ for (x = 0; x < QUAT_SIZE; x++) {
+ quat[x] = quat1->quat[x] - quat2->quat[x];
+ }
+
+ return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
}
static PyObject *quat_mul_float(QuaternionObject *quat, const float scalar)
{
- float tquat[4];
- copy_qt_qt(tquat, quat->quat);
- mul_qt_fl(tquat, scalar);
- return Quaternion_CreatePyObject(tquat, Py_TYPE(quat));
+ float tquat[4];
+ copy_qt_qt(tquat, quat->quat);
+ mul_qt_fl(tquat, scalar);
+ return Quaternion_CreatePyObject(tquat, Py_TYPE(quat));
}
/*------------------------obj * obj------------------------------
* multiplication */
static PyObject *Quaternion_mul(PyObject *q1, PyObject *q2)
{
- float scalar;
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (QuaternionObject_Check(q1)) {
- quat1 = (QuaternionObject *)q1;
- if (BaseMath_ReadCallback(quat1) == -1) {
- return NULL;
- }
- }
- if (QuaternionObject_Check(q2)) {
- quat2 = (QuaternionObject *)q2;
- if (BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
- }
-
- if (quat1 && quat2) { /* QUAT * QUAT (element-wise product) */
+ float scalar;
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (QuaternionObject_Check(q1)) {
+ quat1 = (QuaternionObject *)q1;
+ if (BaseMath_ReadCallback(quat1) == -1) {
+ return NULL;
+ }
+ }
+ if (QuaternionObject_Check(q2)) {
+ quat2 = (QuaternionObject *)q2;
+ if (BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (quat1 && quat2) { /* QUAT * QUAT (element-wise product) */
#ifdef USE_MATHUTILS_ELEM_MUL
- float quat[QUAT_SIZE];
- mul_vn_vnvn(quat, quat1->quat, quat2->quat, QUAT_SIZE);
- return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
+ float quat[QUAT_SIZE];
+ mul_vn_vnvn(quat, quat1->quat, quat2->quat, QUAT_SIZE);
+ return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
#endif
- }
- /* the only case this can happen (for a supported type is "FLOAT * QUAT") */
- else if (quat2) { /* FLOAT * QUAT */
- if (((scalar = PyFloat_AsDouble(q1)) == -1.0f && PyErr_Occurred()) == 0) {
- return quat_mul_float(quat2, scalar);
- }
- }
- else if (quat1) { /* QUAT * FLOAT */
- if ((((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
- return quat_mul_float(quat1, scalar);
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
+ }
+ /* the only case this can happen (for a supported type is "FLOAT * QUAT") */
+ else if (quat2) { /* FLOAT * QUAT */
+ if (((scalar = PyFloat_AsDouble(q1)) == -1.0f && PyErr_Occurred()) == 0) {
+ return quat_mul_float(quat2, scalar);
+ }
+ }
+ else if (quat1) { /* QUAT * FLOAT */
+ if ((((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
+ return quat_mul_float(quat1, scalar);
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
}
/*------------------------obj *= obj------------------------------
* inplace multiplication */
static PyObject *Quaternion_imul(PyObject *q1, PyObject *q2)
{
- float scalar;
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (QuaternionObject_Check(q1)) {
- quat1 = (QuaternionObject *)q1;
- if (BaseMath_ReadCallback(quat1) == -1) {
- return NULL;
- }
- }
- if (QuaternionObject_Check(q2)) {
- quat2 = (QuaternionObject *)q2;
- if (BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
- }
-
- if (quat1 && quat2) { /* QUAT *= QUAT (inplace element-wise product) */
+ float scalar;
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (QuaternionObject_Check(q1)) {
+ quat1 = (QuaternionObject *)q1;
+ if (BaseMath_ReadCallback(quat1) == -1) {
+ return NULL;
+ }
+ }
+ if (QuaternionObject_Check(q2)) {
+ quat2 = (QuaternionObject *)q2;
+ if (BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (quat1 && quat2) { /* QUAT *= QUAT (inplace element-wise product) */
#ifdef USE_MATHUTILS_ELEM_MUL
- mul_vn_vn(quat1->quat, quat2->quat, QUAT_SIZE);
+ mul_vn_vn(quat1->quat, quat2->quat, QUAT_SIZE);
#else
- PyErr_Format(PyExc_TypeError,
- "Inplace element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "Inplace element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
#endif
- }
- else if (quat1 && (((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
- /* QUAT *= FLOAT */
- mul_qt_fl(quat1->quat, scalar);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(quat1);
- Py_INCREF(q1);
- return q1;
+ }
+ else if (quat1 && (((scalar = PyFloat_AsDouble(q2)) == -1.0f && PyErr_Occurred()) == 0)) {
+ /* QUAT *= FLOAT */
+ mul_qt_fl(quat1->quat, scalar);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(quat1);
+ Py_INCREF(q1);
+ return q1;
}
/*------------------------obj @ obj------------------------------
* quaternion multiplication */
static PyObject *Quaternion_matmul(PyObject *q1, PyObject *q2)
{
- float quat[QUAT_SIZE];
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (QuaternionObject_Check(q1)) {
- quat1 = (QuaternionObject *)q1;
- if (BaseMath_ReadCallback(quat1) == -1) {
- return NULL;
- }
- }
- if (QuaternionObject_Check(q2)) {
- quat2 = (QuaternionObject *)q2;
- if (BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
- }
-
- if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
- mul_qt_qtqt(quat, quat1->quat, quat2->quat);
- return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
- }
- else if (quat1) {
- /* QUAT @ VEC */
- if (VectorObject_Check(q2)) {
- VectorObject *vec2 = (VectorObject *)q2;
- float tvec[3];
-
- if (vec2->size != 3) {
- PyErr_SetString(PyExc_ValueError,
- "Vector multiplication: "
- "only 3D vector rotations (with quats) "
- "currently supported");
- return NULL;
- }
- if (BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
-
- copy_v3_v3(tvec, vec2->vec);
- mul_qt_v3(quat1->quat, tvec);
-
- return Vector_CreatePyObject(tvec, 3, Py_TYPE(vec2));
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Quaternion multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
+ float quat[QUAT_SIZE];
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (QuaternionObject_Check(q1)) {
+ quat1 = (QuaternionObject *)q1;
+ if (BaseMath_ReadCallback(quat1) == -1) {
+ return NULL;
+ }
+ }
+ if (QuaternionObject_Check(q2)) {
+ quat2 = (QuaternionObject *)q2;
+ if (BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
+ mul_qt_qtqt(quat, quat1->quat, quat2->quat);
+ return Quaternion_CreatePyObject(quat, Py_TYPE(q1));
+ }
+ else if (quat1) {
+ /* QUAT @ VEC */
+ if (VectorObject_Check(q2)) {
+ VectorObject *vec2 = (VectorObject *)q2;
+ float tvec[3];
+
+ if (vec2->size != 3) {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector multiplication: "
+ "only 3D vector rotations (with quats) "
+ "currently supported");
+ return NULL;
+ }
+ if (BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+
+ copy_v3_v3(tvec, vec2->vec);
+ mul_qt_v3(quat1->quat, tvec);
+
+ return Vector_CreatePyObject(tvec, 3, Py_TYPE(vec2));
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Quaternion multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
}
/*------------------------obj @= obj------------------------------
* inplace quaternion multiplication */
static PyObject *Quaternion_imatmul(PyObject *q1, PyObject *q2)
{
- float quat[QUAT_SIZE];
- QuaternionObject *quat1 = NULL, *quat2 = NULL;
-
- if (QuaternionObject_Check(q1)) {
- quat1 = (QuaternionObject *)q1;
- if (BaseMath_ReadCallback(quat1) == -1) {
- return NULL;
- }
- }
- if (QuaternionObject_Check(q2)) {
- quat2 = (QuaternionObject *)q2;
- if (BaseMath_ReadCallback(quat2) == -1) {
- return NULL;
- }
- }
-
- if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
- mul_qt_qtqt(quat, quat1->quat, quat2->quat);
- copy_qt_qt(quat1->quat, quat);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Inplace quaternion multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(q1)->tp_name, Py_TYPE(q2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(quat1);
- Py_INCREF(q1);
- return q1;
+ float quat[QUAT_SIZE];
+ QuaternionObject *quat1 = NULL, *quat2 = NULL;
+
+ if (QuaternionObject_Check(q1)) {
+ quat1 = (QuaternionObject *)q1;
+ if (BaseMath_ReadCallback(quat1) == -1) {
+ return NULL;
+ }
+ }
+ if (QuaternionObject_Check(q2)) {
+ quat2 = (QuaternionObject *)q2;
+ if (BaseMath_ReadCallback(quat2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (quat1 && quat2) { /* QUAT @ QUAT (cross product) */
+ mul_qt_qtqt(quat, quat1->quat, quat2->quat);
+ copy_qt_qt(quat1->quat, quat);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Inplace quaternion multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(q1)->tp_name,
+ Py_TYPE(q2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(quat1);
+ Py_INCREF(q1);
+ return q1;
}
/* -obj
* returns the negative of this object*/
static PyObject *Quaternion_neg(QuaternionObject *self)
{
- float tquat[QUAT_SIZE];
+ float tquat[QUAT_SIZE];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- negate_v4_v4(tquat, self->quat);
- return Quaternion_CreatePyObject(tquat, Py_TYPE(self));
+ negate_v4_v4(tquat, self->quat);
+ return Quaternion_CreatePyObject(tquat, Py_TYPE(self));
}
-
/* -----------------PROTOCOL DECLARATIONS-------------------------- */
static PySequenceMethods Quaternion_SeqMethods = {
- (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 */
+ (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,
+ (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*/
- NULL, /*nb_remainder*/
- NULL, /*nb_divmod*/
- NULL, /*nb_power*/
- (unaryfunc) Quaternion_neg, /*nb_negative*/
- (unaryfunc) Quaternion_copy,/*tp_positive*/
- (unaryfunc) 0, /*tp_absolute*/
- (inquiry) 0, /*tp_bool*/
- (unaryfunc) 0, /*nb_invert*/
- NULL, /*nb_lshift*/
- (binaryfunc)0, /*nb_rshift*/
- NULL, /*nb_and*/
- NULL, /*nb_xor*/
- NULL, /*nb_or*/
- NULL, /*nb_int*/
- NULL, /*nb_reserved*/
- NULL, /*nb_float*/
- NULL, /* nb_inplace_add */
- NULL, /* nb_inplace_subtract */
- (binaryfunc) Quaternion_imul, /* nb_inplace_multiply */
- NULL, /* nb_inplace_remainder */
- NULL, /* nb_inplace_power */
- NULL, /* nb_inplace_lshift */
- NULL, /* nb_inplace_rshift */
- NULL, /* nb_inplace_and */
- NULL, /* nb_inplace_xor */
- NULL, /* nb_inplace_or */
- NULL, /* nb_floor_divide */
- NULL, /* nb_true_divide */
- NULL, /* nb_inplace_floor_divide */
- NULL, /* nb_inplace_true_divide */
- NULL, /* nb_index */
- (binaryfunc) Quaternion_matmul, /* nb_matrix_multiply */
- (binaryfunc) Quaternion_imatmul, /* nb_inplace_matrix_multiply */
+ (binaryfunc)Quaternion_add, /*nb_add*/
+ (binaryfunc)Quaternion_sub, /*nb_subtract*/
+ (binaryfunc)Quaternion_mul, /*nb_multiply*/
+ NULL, /*nb_remainder*/
+ NULL, /*nb_divmod*/
+ NULL, /*nb_power*/
+ (unaryfunc)Quaternion_neg, /*nb_negative*/
+ (unaryfunc)Quaternion_copy, /*tp_positive*/
+ (unaryfunc)0, /*tp_absolute*/
+ (inquiry)0, /*tp_bool*/
+ (unaryfunc)0, /*nb_invert*/
+ NULL, /*nb_lshift*/
+ (binaryfunc)0, /*nb_rshift*/
+ NULL, /*nb_and*/
+ NULL, /*nb_xor*/
+ NULL, /*nb_or*/
+ NULL, /*nb_int*/
+ NULL, /*nb_reserved*/
+ NULL, /*nb_float*/
+ NULL, /* nb_inplace_add */
+ NULL, /* nb_inplace_subtract */
+ (binaryfunc)Quaternion_imul, /* nb_inplace_multiply */
+ NULL, /* nb_inplace_remainder */
+ NULL, /* nb_inplace_power */
+ NULL, /* nb_inplace_lshift */
+ NULL, /* nb_inplace_rshift */
+ NULL, /* nb_inplace_and */
+ NULL, /* nb_inplace_xor */
+ NULL, /* nb_inplace_or */
+ NULL, /* nb_floor_divide */
+ NULL, /* nb_true_divide */
+ NULL, /* nb_inplace_floor_divide */
+ NULL, /* nb_inplace_true_divide */
+ NULL, /* nb_index */
+ (binaryfunc)Quaternion_matmul, /* nb_matrix_multiply */
+ (binaryfunc)Quaternion_imatmul, /* nb_inplace_matrix_multiply */
};
-PyDoc_STRVAR(Quaternion_axis_doc,
-"Quaternion axis value.\n\n:type: float"
-);
+PyDoc_STRVAR(Quaternion_axis_doc, "Quaternion axis value.\n\n:type: float");
static PyObject *Quaternion_axis_get(QuaternionObject *self, void *type)
{
- return Quaternion_item(self, POINTER_AS_INT(type));
+ return Quaternion_item(self, POINTER_AS_INT(type));
}
static int Quaternion_axis_set(QuaternionObject *self, PyObject *value, void *type)
{
- return Quaternion_ass_item(self, POINTER_AS_INT(type), value);
+ return Quaternion_ass_item(self, POINTER_AS_INT(type), value);
}
-PyDoc_STRVAR(Quaternion_magnitude_doc,
-"Size of the quaternion (read-only).\n\n:type: float"
-);
+PyDoc_STRVAR(Quaternion_magnitude_doc, "Size of the quaternion (read-only).\n\n:type: float");
static PyObject *Quaternion_magnitude_get(QuaternionObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(sqrtf(dot_qtqt(self->quat, self->quat)));
+ return PyFloat_FromDouble(sqrtf(dot_qtqt(self->quat, self->quat)));
}
-PyDoc_STRVAR(Quaternion_angle_doc,
-"Angle of the quaternion.\n\n:type: float"
-);
+PyDoc_STRVAR(Quaternion_angle_doc, "Angle of the quaternion.\n\n:type: float");
static PyObject *Quaternion_angle_get(QuaternionObject *self, void *UNUSED(closure))
{
- float tquat[4];
- float angle;
+ float tquat[4];
+ float angle;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- normalize_qt_qt(tquat, self->quat);
+ normalize_qt_qt(tquat, self->quat);
- angle = 2.0f * saacos(tquat[0]);
+ angle = 2.0f * saacos(tquat[0]);
- quat__axis_angle_sanitize(NULL, &angle);
+ quat__axis_angle_sanitize(NULL, &angle);
- return PyFloat_FromDouble(angle);
+ return PyFloat_FromDouble(angle);
}
static int Quaternion_angle_set(QuaternionObject *self, PyObject *value, void *UNUSED(closure))
{
- float tquat[4];
- float len;
+ float tquat[4];
+ float len;
- float axis[3], angle_dummy;
- float angle;
+ float axis[3], angle_dummy;
+ float angle;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- len = normalize_qt_qt(tquat, self->quat);
- quat_to_axis_angle(axis, &angle_dummy, tquat);
+ len = normalize_qt_qt(tquat, self->quat);
+ quat_to_axis_angle(axis, &angle_dummy, tquat);
- angle = PyFloat_AsDouble(value);
+ angle = PyFloat_AsDouble(value);
- if (angle == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError,
- "Quaternion.angle = value: float expected");
- return -1;
- }
+ if (angle == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError, "Quaternion.angle = value: float expected");
+ return -1;
+ }
- angle = angle_wrap_rad(angle);
+ angle = angle_wrap_rad(angle);
- quat__axis_angle_sanitize(axis, &angle);
+ quat__axis_angle_sanitize(axis, &angle);
- axis_angle_to_quat(self->quat, axis, angle);
- mul_qt_fl(self->quat, len);
+ axis_angle_to_quat(self->quat, axis, angle);
+ mul_qt_fl(self->quat, len);
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
- return 0;
+ return 0;
}
-PyDoc_STRVAR(Quaternion_axis_vector_doc,
-"Quaternion axis as a vector.\n\n:type: :class:`Vector`"
-);
+PyDoc_STRVAR(Quaternion_axis_vector_doc, "Quaternion axis as a vector.\n\n:type: :class:`Vector`");
static PyObject *Quaternion_axis_vector_get(QuaternionObject *self, void *UNUSED(closure))
{
- float tquat[4];
+ float tquat[4];
- float axis[3];
- float angle_dummy;
+ float axis[3];
+ float angle_dummy;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- normalize_qt_qt(tquat, self->quat);
- quat_to_axis_angle(axis, &angle_dummy, tquat);
+ normalize_qt_qt(tquat, self->quat);
+ quat_to_axis_angle(axis, &angle_dummy, tquat);
- quat__axis_angle_sanitize(axis, NULL);
+ quat__axis_angle_sanitize(axis, NULL);
- return Vector_CreatePyObject(axis, 3, NULL);
+ return Vector_CreatePyObject(axis, 3, NULL);
}
-static int Quaternion_axis_vector_set(QuaternionObject *self, PyObject *value, void *UNUSED(closure))
+static int Quaternion_axis_vector_set(QuaternionObject *self,
+ PyObject *value,
+ void *UNUSED(closure))
{
- float tquat[4];
- float len;
+ float tquat[4];
+ float len;
- float axis[3];
- float angle;
+ float axis[3];
+ float angle;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- len = normalize_qt_qt(tquat, self->quat);
- quat_to_axis_angle(axis, &angle, tquat); /* axis value is unused */
+ len = normalize_qt_qt(tquat, self->quat);
+ quat_to_axis_angle(axis, &angle, tquat); /* axis value is unused */
- if (mathutils_array_parse(axis, 3, 3, value, "quat.axis = other") == -1) {
- return -1;
- }
+ if (mathutils_array_parse(axis, 3, 3, value, "quat.axis = other") == -1) {
+ return -1;
+ }
- quat__axis_angle_sanitize(axis, &angle);
+ quat__axis_angle_sanitize(axis, &angle);
- axis_angle_to_quat(self->quat, axis, angle);
- mul_qt_fl(self->quat, len);
+ axis_angle_to_quat(self->quat, axis, angle);
+ mul_qt_fl(self->quat, len);
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
- return 0;
+ return 0;
}
/* ----------------------------------mathutils.Quaternion() -------------- */
static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq = NULL;
- double angle = 0.0f;
- float quat[QUAT_SIZE];
- unit_qt(quat);
-
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "mathutils.Quaternion(): "
- "takes no keyword args");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "|Od:mathutils.Quaternion", &seq, &angle)) {
- return NULL;
- }
-
- switch (PyTuple_GET_SIZE(args)) {
- case 0:
- break;
- case 1:
- {
- int size;
-
- if ((size = mathutils_array_parse(quat, 3, QUAT_SIZE, seq, "mathutils.Quaternion()")) == -1) {
- return NULL;
- }
-
- if (size == 4) {
- /* 4d: Quaternion (common case) */
- }
- else {
- /* 3d: Interpret as exponential map */
- BLI_assert(size == 3);
- expmap_to_quat(quat, quat);
- }
-
- break;
- }
- case 2:
- {
- float axis[3];
- if (mathutils_array_parse(axis, 3, 3, seq, "mathutils.Quaternion()") == -1) {
- return NULL;
- }
- angle = angle_wrap_rad(angle); /* clamp because of precision issues */
- axis_angle_to_quat(quat, axis, angle);
- break;
- /* PyArg_ParseTuple assures no more than 2 */
- }
- }
- return Quaternion_CreatePyObject(quat, type);
+ PyObject *seq = NULL;
+ double angle = 0.0f;
+ float quat[QUAT_SIZE];
+ unit_qt(quat);
+
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError,
+ "mathutils.Quaternion(): "
+ "takes no keyword args");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "|Od:mathutils.Quaternion", &seq, &angle)) {
+ return NULL;
+ }
+
+ switch (PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 1: {
+ int size;
+
+ if ((size = mathutils_array_parse(quat, 3, QUAT_SIZE, seq, "mathutils.Quaternion()")) ==
+ -1) {
+ return NULL;
+ }
+
+ if (size == 4) {
+ /* 4d: Quaternion (common case) */
+ }
+ else {
+ /* 3d: Interpret as exponential map */
+ BLI_assert(size == 3);
+ expmap_to_quat(quat, quat);
+ }
+
+ break;
+ }
+ case 2: {
+ float axis[3];
+ if (mathutils_array_parse(axis, 3, 3, seq, "mathutils.Quaternion()") == -1) {
+ return NULL;
+ }
+ angle = angle_wrap_rad(angle); /* clamp because of precision issues */
+ axis_angle_to_quat(quat, axis, angle);
+ break;
+ /* PyArg_ParseTuple assures no more than 2 */
+ }
+ }
+ return Quaternion_CreatePyObject(quat, type);
}
static PyObject *quat__apply_to_copy(PyNoArgsFunction quat_func, QuaternionObject *self)
{
- PyObject *ret = Quaternion_copy(self);
- PyObject *ret_dummy = quat_func(ret);
- if (ret_dummy) {
- Py_DECREF(ret_dummy);
- return ret;
- }
- else { /* error */
- Py_DECREF(ret);
- return NULL;
- }
+ PyObject *ret = Quaternion_copy(self);
+ PyObject *ret_dummy = quat_func(ret);
+ if (ret_dummy) {
+ Py_DECREF(ret_dummy);
+ return ret;
+ }
+ else { /* error */
+ Py_DECREF(ret);
+ return NULL;
+ }
}
/* axis vector suffers from precision errors, use this function to ensure */
static void quat__axis_angle_sanitize(float axis[3], float *angle)
{
- if (axis) {
- if (is_zero_v3(axis) ||
- !isfinite(axis[0]) ||
- !isfinite(axis[1]) ||
- !isfinite(axis[2]))
- {
- axis[0] = 1.0f;
- axis[1] = 0.0f;
- axis[2] = 0.0f;
- }
- else if (EXPP_FloatsAreEqual(axis[0], 0.0f, 10) &&
- EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
- EXPP_FloatsAreEqual(axis[2], 0.0f, 10))
- {
- axis[0] = 1.0f;
- }
- }
-
- if (angle) {
- if (!isfinite(*angle)) {
- *angle = 0.0f;
- }
- }
+ if (axis) {
+ if (is_zero_v3(axis) || !isfinite(axis[0]) || !isfinite(axis[1]) || !isfinite(axis[2])) {
+ axis[0] = 1.0f;
+ axis[1] = 0.0f;
+ axis[2] = 0.0f;
+ }
+ else if (EXPP_FloatsAreEqual(axis[0], 0.0f, 10) && EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
+ EXPP_FloatsAreEqual(axis[2], 0.0f, 10)) {
+ axis[0] = 1.0f;
+ }
+ }
+
+ if (angle) {
+ if (!isfinite(*angle)) {
+ *angle = 0.0f;
+ }
+ }
}
/* -----------------------METHOD DEFINITIONS ---------------------- */
static struct PyMethodDef Quaternion_methods[] = {
- /* in place only */
- {"identity", (PyCFunction) Quaternion_identity, METH_NOARGS, Quaternion_identity_doc},
- {"negate", (PyCFunction) Quaternion_negate, METH_NOARGS, Quaternion_negate_doc},
-
- /* operate on original or copy */
- {"conjugate", (PyCFunction) Quaternion_conjugate, METH_NOARGS, Quaternion_conjugate_doc},
- {"conjugated", (PyCFunction) Quaternion_conjugated, METH_NOARGS, Quaternion_conjugated_doc},
-
- {"invert", (PyCFunction) Quaternion_invert, METH_NOARGS, Quaternion_invert_doc},
- {"inverted", (PyCFunction) Quaternion_inverted, METH_NOARGS, Quaternion_inverted_doc},
-
- {"normalize", (PyCFunction) Quaternion_normalize, METH_NOARGS, Quaternion_normalize_doc},
- {"normalized", (PyCFunction) Quaternion_normalized, METH_NOARGS, Quaternion_normalized_doc},
-
- /* return converted representation */
- {"to_euler", (PyCFunction) Quaternion_to_euler, METH_VARARGS, Quaternion_to_euler_doc},
- {"to_matrix", (PyCFunction) Quaternion_to_matrix, METH_NOARGS, Quaternion_to_matrix_doc},
- {"to_axis_angle", (PyCFunction) Quaternion_to_axis_angle, METH_NOARGS, Quaternion_to_axis_angle_doc},
- {"to_exponential_map", (PyCFunction) Quaternion_to_exponential_map, METH_NOARGS, Quaternion_to_exponential_map_doc},
-
- /* operation between 2 or more types */
- {"cross", (PyCFunction) Quaternion_cross, METH_O, Quaternion_cross_doc},
- {"dot", (PyCFunction) Quaternion_dot, METH_O, Quaternion_dot_doc},
- {"rotation_difference", (PyCFunction) Quaternion_rotation_difference, METH_O, Quaternion_rotation_difference_doc},
- {"slerp", (PyCFunction) Quaternion_slerp, METH_VARARGS, Quaternion_slerp_doc},
- {"rotate", (PyCFunction) Quaternion_rotate, METH_O, Quaternion_rotate_doc},
-
- /* base-math methods */
- {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
-
- {"copy", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
- {"__copy__", (PyCFunction) Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
- {"__deepcopy__", (PyCFunction) Quaternion_deepcopy, METH_VARARGS, Quaternion_copy_doc},
- {NULL, NULL, 0, NULL},
+ /* in place only */
+ {"identity", (PyCFunction)Quaternion_identity, METH_NOARGS, Quaternion_identity_doc},
+ {"negate", (PyCFunction)Quaternion_negate, METH_NOARGS, Quaternion_negate_doc},
+
+ /* operate on original or copy */
+ {"conjugate", (PyCFunction)Quaternion_conjugate, METH_NOARGS, Quaternion_conjugate_doc},
+ {"conjugated", (PyCFunction)Quaternion_conjugated, METH_NOARGS, Quaternion_conjugated_doc},
+
+ {"invert", (PyCFunction)Quaternion_invert, METH_NOARGS, Quaternion_invert_doc},
+ {"inverted", (PyCFunction)Quaternion_inverted, METH_NOARGS, Quaternion_inverted_doc},
+
+ {"normalize", (PyCFunction)Quaternion_normalize, METH_NOARGS, Quaternion_normalize_doc},
+ {"normalized", (PyCFunction)Quaternion_normalized, METH_NOARGS, Quaternion_normalized_doc},
+
+ /* return converted representation */
+ {"to_euler", (PyCFunction)Quaternion_to_euler, METH_VARARGS, Quaternion_to_euler_doc},
+ {"to_matrix", (PyCFunction)Quaternion_to_matrix, METH_NOARGS, Quaternion_to_matrix_doc},
+ {"to_axis_angle",
+ (PyCFunction)Quaternion_to_axis_angle,
+ METH_NOARGS,
+ Quaternion_to_axis_angle_doc},
+ {"to_exponential_map",
+ (PyCFunction)Quaternion_to_exponential_map,
+ METH_NOARGS,
+ Quaternion_to_exponential_map_doc},
+
+ /* operation between 2 or more types */
+ {"cross", (PyCFunction)Quaternion_cross, METH_O, Quaternion_cross_doc},
+ {"dot", (PyCFunction)Quaternion_dot, METH_O, Quaternion_dot_doc},
+ {"rotation_difference",
+ (PyCFunction)Quaternion_rotation_difference,
+ METH_O,
+ Quaternion_rotation_difference_doc},
+ {"slerp", (PyCFunction)Quaternion_slerp, METH_VARARGS, Quaternion_slerp_doc},
+ {"rotate", (PyCFunction)Quaternion_rotate, METH_O, Quaternion_rotate_doc},
+
+ /* base-math methods */
+ {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
+
+ {"copy", (PyCFunction)Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
+ {"__copy__", (PyCFunction)Quaternion_copy, METH_NOARGS, Quaternion_copy_doc},
+ {"__deepcopy__", (PyCFunction)Quaternion_deepcopy, METH_VARARGS, Quaternion_copy_doc},
+ {NULL, NULL, 0, NULL},
};
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Quaternion_getseters[] = {
- {(char *)"w", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)0},
- {(char *)"x", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)1},
- {(char *)"y", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)2},
- {(char *)"z", (getter)Quaternion_axis_get, (setter)Quaternion_axis_set, Quaternion_axis_doc, (void *)3},
- {(char *)"magnitude", (getter)Quaternion_magnitude_get, (setter)NULL, Quaternion_magnitude_doc, NULL},
- {(char *)"angle", (getter)Quaternion_angle_get, (setter)Quaternion_angle_set, Quaternion_angle_doc, NULL},
- {(char *)"axis", (getter)Quaternion_axis_vector_get, (setter)Quaternion_axis_vector_set, Quaternion_axis_vector_doc, NULL},
- {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
- {(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
- {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {(char *)"w",
+ (getter)Quaternion_axis_get,
+ (setter)Quaternion_axis_set,
+ Quaternion_axis_doc,
+ (void *)0},
+ {(char *)"x",
+ (getter)Quaternion_axis_get,
+ (setter)Quaternion_axis_set,
+ Quaternion_axis_doc,
+ (void *)1},
+ {(char *)"y",
+ (getter)Quaternion_axis_get,
+ (setter)Quaternion_axis_set,
+ Quaternion_axis_doc,
+ (void *)2},
+ {(char *)"z",
+ (getter)Quaternion_axis_get,
+ (setter)Quaternion_axis_set,
+ Quaternion_axis_doc,
+ (void *)3},
+ {(char *)"magnitude",
+ (getter)Quaternion_magnitude_get,
+ (setter)NULL,
+ Quaternion_magnitude_doc,
+ NULL},
+ {(char *)"angle",
+ (getter)Quaternion_angle_get,
+ (setter)Quaternion_angle_set,
+ Quaternion_angle_doc,
+ NULL},
+ {(char *)"axis",
+ (getter)Quaternion_axis_vector_get,
+ (setter)Quaternion_axis_vector_set,
+ Quaternion_axis_vector_doc,
+ NULL},
+ {(char *)"is_wrapped",
+ (getter)BaseMathObject_is_wrapped_get,
+ (setter)NULL,
+ BaseMathObject_is_wrapped_doc,
+ NULL},
+ {(char *)"is_frozen",
+ (getter)BaseMathObject_is_frozen_get,
+ (setter)NULL,
+ BaseMathObject_is_frozen_doc,
+ NULL},
+ {(char *)"owner",
+ (getter)BaseMathObject_owner_get,
+ (setter)NULL,
+ BaseMathObject_owner_doc,
+ NULL},
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/* ------------------PY_OBECT DEFINITION-------------------------- */
PyDoc_STRVAR(quaternion_doc,
-".. class:: Quaternion([seq, [angle]])\n"
-"\n"
-" This object gives access to Quaternions in Blender.\n"
-"\n"
-" :param seq: size 3 or 4\n"
-" :type seq: :class:`Vector`\n"
-" :param angle: rotation angle, in radians\n"
-" :type angle: float\n"
-"\n"
-" The constructor takes arguments in various forms:\n"
-"\n"
-" (), *no args*\n"
-" Create an identity quaternion\n"
-" (*wxyz*)\n"
-" Create a quaternion from a ``(w, x, y, z)`` vector.\n"
-" (*exponential_map*)\n"
-" Create a quaternion from a 3d exponential map vector.\n"
-"\n"
-" .. seealso:: :meth:`to_exponential_map`\n"
-" (*axis, angle*)\n"
-" Create a quaternion representing a rotation of *angle* radians over *axis*.\n"
-"\n"
-" .. seealso:: :meth:`to_axis_angle`\n"
-);
+ ".. class:: Quaternion([seq, [angle]])\n"
+ "\n"
+ " This object gives access to Quaternions in Blender.\n"
+ "\n"
+ " :param seq: size 3 or 4\n"
+ " :type seq: :class:`Vector`\n"
+ " :param angle: rotation angle, in radians\n"
+ " :type angle: float\n"
+ "\n"
+ " The constructor takes arguments in various forms:\n"
+ "\n"
+ " (), *no args*\n"
+ " Create an identity quaternion\n"
+ " (*wxyz*)\n"
+ " Create a quaternion from a ``(w, x, y, z)`` vector.\n"
+ " (*exponential_map*)\n"
+ " Create a quaternion from a 3d exponential map vector.\n"
+ "\n"
+ " .. seealso:: :meth:`to_exponential_map`\n"
+ " (*axis, angle*)\n"
+ " Create a quaternion representing a rotation of *angle* radians over *axis*.\n"
+ "\n"
+ " .. seealso:: :meth:`to_axis_angle`\n");
PyTypeObject quaternion_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Quaternion", /* tp_name */
- sizeof(QuaternionObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)BaseMathObject_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- (reprfunc) Quaternion_repr, /* tp_repr */
- &Quaternion_NumMethods, /* tp_as_number */
- &Quaternion_SeqMethods, /* tp_as_sequence */
- &Quaternion_AsMapping, /* tp_as_mapping */
- (hashfunc)Quaternion_hash, /* tp_hash */
- NULL, /* tp_call */
+ PyVarObject_HEAD_INIT(NULL, 0) "Quaternion", /* tp_name */
+ sizeof(QuaternionObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)BaseMathObject_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ (reprfunc)Quaternion_repr, /* tp_repr */
+ &Quaternion_NumMethods, /* tp_as_number */
+ &Quaternion_SeqMethods, /* tp_as_sequence */
+ &Quaternion_AsMapping, /* tp_as_mapping */
+ (hashfunc)Quaternion_hash, /* tp_hash */
+ NULL, /* tp_call */
#ifndef MATH_STANDALONE
- (reprfunc) Quaternion_str, /* tp_str */
+ (reprfunc)Quaternion_str, /* tp_str */
#else
- NULL, /* tp_str */
+ NULL, /* tp_str */
#endif
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- quaternion_doc, /* tp_doc */
- (traverseproc)BaseMathObject_traverse, /* tp_traverse */
- (inquiry)BaseMathObject_clear, /* tp_clear */
- (richcmpfunc)Quaternion_richcmpr, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- Quaternion_methods, /* tp_methods */
- NULL, /* tp_members */
- Quaternion_getseters, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- NULL, /* tp_init */
- NULL, /* tp_alloc */
- Quaternion_new, /* tp_new */
- NULL, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- NULL, /* tp_del */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ quaternion_doc, /* tp_doc */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+ (richcmpfunc)Quaternion_richcmpr, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ Quaternion_methods, /* tp_methods */
+ NULL, /* tp_members */
+ Quaternion_getseters, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ NULL, /* tp_alloc */
+ Quaternion_new, /* tp_new */
+ NULL, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ NULL, /* tp_del */
};
-PyObject *Quaternion_CreatePyObject(
- const float quat[4],
- PyTypeObject *base_type)
+PyObject *Quaternion_CreatePyObject(const float quat[4], PyTypeObject *base_type)
{
- QuaternionObject *self;
- float *quat_alloc;
-
- quat_alloc = PyMem_Malloc(QUAT_SIZE * sizeof(float));
- if (UNLIKELY(quat_alloc == NULL)) {
- PyErr_SetString(PyExc_MemoryError,
- "Quaternion(): "
- "problem allocating data");
- return NULL;
- }
-
- self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
- if (self) {
- self->quat = quat_alloc;
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- /* NEW */
- if (!quat) { /* new empty */
- unit_qt(self->quat);
- }
- else {
- copy_qt_qt(self->quat, quat);
- }
- self->flag = BASE_MATH_FLAG_DEFAULT;
- }
- else {
- PyMem_Free(quat_alloc);
- }
-
- return (PyObject *)self;
+ QuaternionObject *self;
+ float *quat_alloc;
+
+ quat_alloc = PyMem_Malloc(QUAT_SIZE * sizeof(float));
+ if (UNLIKELY(quat_alloc == NULL)) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Quaternion(): "
+ "problem allocating data");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
+ if (self) {
+ self->quat = quat_alloc;
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ /* NEW */
+ if (!quat) { /* new empty */
+ unit_qt(self->quat);
+ }
+ else {
+ copy_qt_qt(self->quat, quat);
+ }
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ }
+ else {
+ PyMem_Free(quat_alloc);
+ }
+
+ return (PyObject *)self;
}
-PyObject *Quaternion_CreatePyObject_wrap(
- float quat[4],
- PyTypeObject *base_type)
+PyObject *Quaternion_CreatePyObject_wrap(float quat[4], PyTypeObject *base_type)
{
- QuaternionObject *self;
-
- self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
- if (self) {
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- /* WRAP */
- self->quat = quat;
- self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
- }
- return (PyObject *) self;
+ QuaternionObject *self;
+
+ self = BASE_MATH_NEW(QuaternionObject, quaternion_Type, base_type);
+ if (self) {
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ /* WRAP */
+ self->quat = quat;
+ self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
+ }
+ return (PyObject *)self;
}
PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user,
- unsigned char cb_type, unsigned char cb_subtype)
+ unsigned char cb_type,
+ unsigned char cb_subtype)
{
- QuaternionObject *self = (QuaternionObject *)Quaternion_CreatePyObject(NULL, NULL);
- if (self) {
- Py_INCREF(cb_user);
- self->cb_user = cb_user;
- self->cb_type = cb_type;
- self->cb_subtype = cb_subtype;
- PyObject_GC_Track(self);
- }
-
- return (PyObject *)self;
+ QuaternionObject *self = (QuaternionObject *)Quaternion_CreatePyObject(NULL, NULL);
+ if (self) {
+ Py_INCREF(cb_user);
+ self->cb_user = cb_user;
+ self->cb_type = cb_type;
+ self->cb_subtype = cb_subtype;
+ PyObject_GC_Track(self);
+ }
+
+ return (PyObject *)self;
}
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.h b/source/blender/python/mathutils/mathutils_Quaternion.h
index a4c55fffccc..bc6bd307ece 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.h
+++ b/source/blender/python/mathutils/mathutils_Quaternion.h
@@ -27,7 +27,7 @@ extern PyTypeObject quaternion_Type;
#define QuaternionObject_CheckExact(v) (Py_TYPE(v) == &quaternion_Type)
typedef struct {
- BASE_MATH_MEMBERS(quat);
+ BASE_MATH_MEMBERS(quat);
} QuaternionObject;
/* struct data contains a pointer to the actual data that the
@@ -36,17 +36,13 @@ typedef struct {
* blender (stored in blend_data). This is an either/or struct not both */
/* prototypes */
-PyObject *Quaternion_CreatePyObject(
- const float quat[4],
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Quaternion_CreatePyObject_wrap(
- float quat[4],
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-PyObject *Quaternion_CreatePyObject_cb(
- PyObject *cb_user,
- unsigned char cb_type, unsigned char cb_subtype
- ) ATTR_WARN_UNUSED_RESULT;
+PyObject *Quaternion_CreatePyObject(const float quat[4],
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT;
+PyObject *Quaternion_CreatePyObject_wrap(float quat[4],
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user,
+ unsigned char cb_type,
+ unsigned char cb_subtype) ATTR_WARN_UNUSED_RESULT;
#endif /* __MATHUTILS_QUATERNION_H__ */
diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c
index 1dd578096f9..7d73f165c1e 100644
--- a/source/blender/python/mathutils/mathutils_Vector.c
+++ b/source/blender/python/mathutils/mathutils_Vector.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -44,12 +43,14 @@
* used as a sentinel: if it is unset, the axis is not valid. */
#define SWIZZLE_BITS_PER_AXIS 3
#define SWIZZLE_VALID_AXIS 0x4
-#define SWIZZLE_AXIS 0x3
+#define SWIZZLE_AXIS 0x3
static PyObject *Vector_copy(VectorObject *self);
static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args);
static PyObject *Vector_to_tuple_ext(VectorObject *self, int ndigits);
-static int row_vector_multiplication(float rvec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat);
+static int row_vector_multiplication(float rvec[MAX_DIMENSIONS],
+ VectorObject *vec,
+ MatrixObject *mat);
/**
* Supports 2D, 3D, and 4D vector objects both int and float values
@@ -57,803 +58,780 @@ static int row_vector_multiplication(float rvec[MAX_DIMENSIONS], VectorObject *v
*/
static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- float *vec = NULL;
- int size = 3; /* default to a 3D vector */
-
- if (kwds && PyDict_Size(kwds)) {
- PyErr_SetString(PyExc_TypeError,
- "Vector(): "
- "takes no keyword args");
- return NULL;
- }
-
- switch (PyTuple_GET_SIZE(args)) {
- case 0:
- vec = PyMem_Malloc(size * sizeof(float));
-
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- copy_vn_fl(vec, size, 0.0f);
- break;
- case 1:
- if ((size = mathutils_array_parse_alloc(&vec, 2, PyTuple_GET_ITEM(args, 0), "mathutils.Vector()")) == -1) {
- return NULL;
- }
- break;
- default:
- PyErr_SetString(PyExc_TypeError,
- "mathutils.Vector(): "
- "more than a single arg given");
- return NULL;
- }
- return Vector_CreatePyObject_alloc(vec, size, type);
+ float *vec = NULL;
+ int size = 3; /* default to a 3D vector */
+
+ if (kwds && PyDict_Size(kwds)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector(): "
+ "takes no keyword args");
+ return NULL;
+ }
+
+ switch (PyTuple_GET_SIZE(args)) {
+ case 0:
+ vec = PyMem_Malloc(size * sizeof(float));
+
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ copy_vn_fl(vec, size, 0.0f);
+ break;
+ case 1:
+ if ((size = mathutils_array_parse_alloc(
+ &vec, 2, PyTuple_GET_ITEM(args, 0), "mathutils.Vector()")) == -1) {
+ return NULL;
+ }
+ break;
+ default:
+ PyErr_SetString(PyExc_TypeError,
+ "mathutils.Vector(): "
+ "more than a single arg given");
+ return NULL;
+ }
+ return Vector_CreatePyObject_alloc(vec, size, type);
}
static PyObject *vec__apply_to_copy(PyNoArgsFunction vec_func, VectorObject *self)
{
- PyObject *ret = Vector_copy(self);
- PyObject *ret_dummy = vec_func(ret);
- if (ret_dummy) {
- Py_DECREF(ret_dummy);
- return (PyObject *)ret;
- }
- else { /* error */
- Py_DECREF(ret);
- return NULL;
- }
+ PyObject *ret = Vector_copy(self);
+ PyObject *ret_dummy = vec_func(ret);
+ if (ret_dummy) {
+ Py_DECREF(ret_dummy);
+ return (PyObject *)ret;
+ }
+ else { /* error */
+ Py_DECREF(ret);
+ return NULL;
+ }
}
/*-----------------------CLASS-METHODS----------------------------*/
PyDoc_STRVAR(C_Vector_Fill_doc,
-".. classmethod:: Fill(size, fill=0.0)\n"
-"\n"
-" Create a vector of length size with all values set to fill.\n"
-"\n"
-" :arg size: The length of the vector to be created.\n"
-" :type size: int\n"
-" :arg fill: The value used to fill the vector.\n"
-" :type fill: float\n"
-);
+ ".. classmethod:: Fill(size, fill=0.0)\n"
+ "\n"
+ " Create a vector of length size with all values set to fill.\n"
+ "\n"
+ " :arg size: The length of the vector to be created.\n"
+ " :type size: int\n"
+ " :arg fill: The value used to fill the vector.\n"
+ " :type fill: float\n");
static PyObject *C_Vector_Fill(PyObject *cls, PyObject *args)
{
- float *vec;
- int size;
- float fill = 0.0f;
+ float *vec;
+ int size;
+ float fill = 0.0f;
- if (!PyArg_ParseTuple(args, "i|f:Vector.Fill", &size, &fill)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "i|f:Vector.Fill", &size, &fill)) {
+ return NULL;
+ }
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
+ return NULL;
+ }
- vec = PyMem_Malloc(size * sizeof(float));
+ vec = PyMem_Malloc(size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.Fill(): "
- "problem allocating pointer space");
- return NULL;
- }
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.Fill(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- copy_vn_fl(vec, size, fill);
+ copy_vn_fl(vec, size, fill);
- return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
+ return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Vector_Range_doc,
-".. classmethod:: Range(start=0, stop, step=1)\n"
-"\n"
-" Create a filled with a range of values.\n"
-"\n"
-" :arg start: The start of the range used to fill the vector.\n"
-" :type start: int\n"
-" :arg stop: The end of the range used to fill the vector.\n"
-" :type stop: int\n"
-" :arg step: The step between successive values in the vector.\n"
-" :type step: int\n"
-);
+ ".. classmethod:: Range(start=0, stop, step=1)\n"
+ "\n"
+ " Create a filled with a range of values.\n"
+ "\n"
+ " :arg start: The start of the range used to fill the vector.\n"
+ " :type start: int\n"
+ " :arg stop: The end of the range used to fill the vector.\n"
+ " :type stop: int\n"
+ " :arg step: The step between successive values in the vector.\n"
+ " :type step: int\n");
static PyObject *C_Vector_Range(PyObject *cls, PyObject *args)
{
- float *vec;
- int stop, size;
- int start = 0;
- int step = 1;
-
- if (!PyArg_ParseTuple(args, "i|ii:Vector.Range", &start, &stop, &step)) {
- return NULL;
- }
-
- switch (PyTuple_GET_SIZE(args)) {
- case 1:
- size = start;
- start = 0;
- break;
- case 2:
- if (start >= stop) {
- PyErr_SetString(PyExc_RuntimeError,
- "Start value is larger "
- "than the stop value");
- return NULL;
- }
-
- size = stop - start;
- break;
- default:
- if (start >= stop) {
- PyErr_SetString(PyExc_RuntimeError,
- "Start value is larger "
- "than the stop value");
- return NULL;
- }
-
- size = (stop - start);
-
- if ((size % step) != 0) {
- size += step;
- }
-
- size /= step;
-
- break;
- }
-
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector(): invalid size");
- return NULL;
- }
-
- vec = PyMem_Malloc(size * sizeof(float));
-
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.Range(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- range_vn_fl(vec, size, (float)start, (float)step);
-
- return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
+ float *vec;
+ int stop, size;
+ int start = 0;
+ int step = 1;
+
+ if (!PyArg_ParseTuple(args, "i|ii:Vector.Range", &start, &stop, &step)) {
+ return NULL;
+ }
+
+ switch (PyTuple_GET_SIZE(args)) {
+ case 1:
+ size = start;
+ start = 0;
+ break;
+ case 2:
+ if (start >= stop) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Start value is larger "
+ "than the stop value");
+ return NULL;
+ }
+
+ size = stop - start;
+ break;
+ default:
+ if (start >= stop) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Start value is larger "
+ "than the stop value");
+ return NULL;
+ }
+
+ size = (stop - start);
+
+ if ((size % step) != 0) {
+ size += step;
+ }
+
+ size /= step;
+
+ break;
+ }
+
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
+ return NULL;
+ }
+
+ vec = PyMem_Malloc(size * sizeof(float));
+
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.Range(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ range_vn_fl(vec, size, (float)start, (float)step);
+
+ return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
PyDoc_STRVAR(C_Vector_Linspace_doc,
-".. classmethod:: Linspace(start, stop, size)\n"
-"\n"
-" Create a vector of the specified size which is filled with linearly spaced values between start and stop values.\n"
-"\n"
-" :arg start: The start of the range used to fill the vector.\n"
-" :type start: int\n"
-" :arg stop: The end of the range used to fill the vector.\n"
-" :type stop: int\n"
-" :arg size: The size of the vector to be created.\n"
-" :type size: int\n"
-);
+ ".. classmethod:: Linspace(start, stop, size)\n"
+ "\n"
+ " Create a vector of the specified size which is filled with linearly spaced "
+ "values between start and stop values.\n"
+ "\n"
+ " :arg start: The start of the range used to fill the vector.\n"
+ " :type start: int\n"
+ " :arg stop: The end of the range used to fill the vector.\n"
+ " :type stop: int\n"
+ " :arg size: The size of the vector to be created.\n"
+ " :type size: int\n");
static PyObject *C_Vector_Linspace(PyObject *cls, PyObject *args)
{
- float *vec;
- int size;
- float start, end, step;
+ float *vec;
+ int size;
+ float start, end, step;
- if (!PyArg_ParseTuple(args, "ffi:Vector.Linspace", &start, &end, &size)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "ffi:Vector.Linspace", &start, &end, &size)) {
+ return NULL;
+ }
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector.Linspace(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector.Linspace(): invalid size");
+ return NULL;
+ }
- step = (end - start) / (float)(size - 1);
+ step = (end - start) / (float)(size - 1);
- vec = PyMem_Malloc(size * sizeof(float));
+ vec = PyMem_Malloc(size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.Linspace(): "
- "problem allocating pointer space");
- return NULL;
- }
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.Linspace(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- range_vn_fl(vec, size, start, step);
+ range_vn_fl(vec, size, start, step);
- return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
+ return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
-PyDoc_STRVAR(C_Vector_Repeat_doc,
-".. classmethod:: Repeat(vector, size)\n"
-"\n"
-" Create a vector by repeating the values in vector until the required size is reached.\n"
-"\n"
-" :arg tuple: The vector to draw values from.\n"
-" :type tuple: :class:`mathutils.Vector`\n"
-" :arg size: The size of the vector to be created.\n"
-" :type size: int\n"
-);
+PyDoc_STRVAR(
+ C_Vector_Repeat_doc,
+ ".. classmethod:: Repeat(vector, size)\n"
+ "\n"
+ " Create a vector by repeating the values in vector until the required size is reached.\n"
+ "\n"
+ " :arg tuple: The vector to draw values from.\n"
+ " :type tuple: :class:`mathutils.Vector`\n"
+ " :arg size: The size of the vector to be created.\n"
+ " :type size: int\n");
static PyObject *C_Vector_Repeat(PyObject *cls, PyObject *args)
{
- float *vec;
- float *iter_vec = NULL;
- int i, size, value_size;
- PyObject *value;
+ float *vec;
+ float *iter_vec = NULL;
+ int i, size, value_size;
+ PyObject *value;
- if (!PyArg_ParseTuple(args, "Oi:Vector.Repeat", &value, &size)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "Oi:Vector.Repeat", &value, &size)) {
+ return NULL;
+ }
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector.Repeat(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector.Repeat(): invalid size");
+ return NULL;
+ }
- if ((value_size = mathutils_array_parse_alloc(&iter_vec, 2, value,
- "Vector.Repeat(vector, size), invalid 'vector' arg")) == -1)
- {
- return NULL;
- }
+ if ((value_size = mathutils_array_parse_alloc(
+ &iter_vec, 2, value, "Vector.Repeat(vector, size), invalid 'vector' arg")) == -1) {
+ return NULL;
+ }
- if (iter_vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.Repeat(): "
- "problem allocating pointer space");
- return NULL;
- }
+ if (iter_vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.Repeat(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- vec = PyMem_Malloc(size * sizeof(float));
+ vec = PyMem_Malloc(size * sizeof(float));
- if (vec == NULL) {
- PyMem_Free(iter_vec);
- PyErr_SetString(PyExc_MemoryError,
- "Vector.Repeat(): "
- "problem allocating pointer space");
- return NULL;
- }
+ if (vec == NULL) {
+ PyMem_Free(iter_vec);
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.Repeat(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- i = 0;
- while (i < size) {
- vec[i] = iter_vec[i % value_size];
- i++;
- }
+ i = 0;
+ while (i < size) {
+ vec[i] = iter_vec[i % value_size];
+ i++;
+ }
- PyMem_Free(iter_vec);
+ PyMem_Free(iter_vec);
- return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
+ return Vector_CreatePyObject_alloc(vec, size, (PyTypeObject *)cls);
}
/*-----------------------------METHODS---------------------------- */
PyDoc_STRVAR(Vector_zero_doc,
-".. method:: zero()\n"
-"\n"
-" Set all values to zero.\n"
-);
+ ".. method:: zero()\n"
+ "\n"
+ " Set all values to zero.\n");
static PyObject *Vector_zero(VectorObject *self)
{
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return NULL;
+ }
- copy_vn_fl(self->vec, self->size, 0.0f);
+ copy_vn_fl(self->vec, self->size, 0.0f);
- if (BaseMath_WriteCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return NULL;
+ }
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_normalize_doc,
-".. method:: normalize()\n"
-"\n"
-" Normalize the vector, making the length of the vector always 1.0.\n"
-"\n"
-" .. warning:: Normalizing a vector where all values are zero has no effect.\n"
-"\n"
-" .. note:: Normalize works for vectors of all sizes,\n"
-" however 4D Vectors w axis is left untouched.\n"
-);
+ ".. method:: normalize()\n"
+ "\n"
+ " Normalize the vector, making the length of the vector always 1.0.\n"
+ "\n"
+ " .. warning:: Normalizing a vector where all values are zero has no effect.\n"
+ "\n"
+ " .. note:: Normalize works for vectors of all sizes,\n"
+ " however 4D Vectors w axis is left untouched.\n");
static PyObject *Vector_normalize(VectorObject *self)
{
- int size = (self->size == 4 ? 3 : self->size);
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ int size = (self->size == 4 ? 3 : self->size);
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- normalize_vn(self->vec, size);
+ normalize_vn(self->vec, size);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_normalized_doc,
-".. method:: normalized()\n"
-"\n"
-" Return a new, normalized vector.\n"
-"\n"
-" :return: a normalized copy of the vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: normalized()\n"
+ "\n"
+ " Return a new, normalized vector.\n"
+ "\n"
+ " :return: a normalized copy of the vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_normalized(VectorObject *self)
{
- return vec__apply_to_copy((PyNoArgsFunction)Vector_normalize, self);
+ return vec__apply_to_copy((PyNoArgsFunction)Vector_normalize, self);
}
PyDoc_STRVAR(Vector_resize_doc,
-".. method:: resize(size=3)\n"
-"\n"
-" Resize the vector to have size number of elements.\n"
-);
+ ".. method:: resize(size=3)\n"
+ "\n"
+ " Resize the vector to have size number of elements.\n");
static PyObject *Vector_resize(VectorObject *self, PyObject *value)
{
- int size;
-
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize(): "
- "cannot resize wrapped data - only python vectors");
- return NULL;
- }
- if (self->cb_user) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize(): "
- "cannot resize a vector that has an owner");
- return NULL;
- }
-
- if ((size = PyC_Long_AsI32(value)) == -1) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize(size): "
- "expected size argument to be an integer");
- return NULL;
- }
-
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector.resize(): invalid size");
- return NULL;
- }
-
- self->vec = PyMem_Realloc(self->vec, (size * sizeof(float)));
- if (self->vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.resize(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- /* If the vector has increased in length, set all new elements to 0.0f */
- if (size > self->size) {
- copy_vn_fl(self->vec + self->size, size - self->size, 0.0f);
- }
-
- self->size = size;
- Py_RETURN_NONE;
+ int size;
+
+ if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize(): "
+ "cannot resize wrapped data - only python vectors");
+ return NULL;
+ }
+ if (self->cb_user) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize(): "
+ "cannot resize a vector that has an owner");
+ return NULL;
+ }
+
+ if ((size = PyC_Long_AsI32(value)) == -1) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize(size): "
+ "expected size argument to be an integer");
+ return NULL;
+ }
+
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector.resize(): invalid size");
+ return NULL;
+ }
+
+ self->vec = PyMem_Realloc(self->vec, (size * sizeof(float)));
+ if (self->vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.resize(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ /* If the vector has increased in length, set all new elements to 0.0f */
+ if (size > self->size) {
+ copy_vn_fl(self->vec + self->size, size - self->size, 0.0f);
+ }
+
+ self->size = size;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resized_doc,
-".. method:: resized(size=3)\n"
-"\n"
-" Return a resized copy of the vector with size number of elements.\n"
-"\n"
-" :return: a new vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: resized(size=3)\n"
+ "\n"
+ " Return a resized copy of the vector with size number of elements.\n"
+ "\n"
+ " :return: a new vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_resized(VectorObject *self, PyObject *value)
{
- int size;
- float *vec;
+ int size;
+ float *vec;
- if ((size = PyLong_AsLong(value)) == -1) {
- return NULL;
- }
+ if ((size = PyLong_AsLong(value)) == -1) {
+ return NULL;
+ }
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector.resized(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector.resized(): invalid size");
+ return NULL;
+ }
- vec = PyMem_Malloc(size * sizeof(float));
+ vec = PyMem_Malloc(size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.resized(): "
- "problem allocating pointer space");
- return NULL;
- }
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.resized(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- copy_vn_fl(vec, size, 0.0f);
- memcpy(vec, self->vec, self->size * sizeof(float));
+ copy_vn_fl(vec, size, 0.0f);
+ memcpy(vec, self->vec, self->size * sizeof(float));
- return Vector_CreatePyObject_alloc(vec, size, NULL);
+ return Vector_CreatePyObject_alloc(vec, size, NULL);
}
PyDoc_STRVAR(Vector_resize_2d_doc,
-".. method:: resize_2d()\n"
-"\n"
-" Resize the vector to 2D (x, y).\n"
-);
+ ".. method:: resize_2d()\n"
+ "\n"
+ " Resize the vector to 2D (x, y).\n");
static PyObject *Vector_resize_2d(VectorObject *self)
{
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_2d(): "
- "cannot resize wrapped data - only python vectors");
- return NULL;
- }
- if (self->cb_user) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_2d(): "
- "cannot resize a vector that has an owner");
- return NULL;
- }
-
- self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 2));
- if (self->vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.resize_2d(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- self->size = 2;
- Py_RETURN_NONE;
+ if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_2d(): "
+ "cannot resize wrapped data - only python vectors");
+ return NULL;
+ }
+ if (self->cb_user) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_2d(): "
+ "cannot resize a vector that has an owner");
+ return NULL;
+ }
+
+ self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 2));
+ if (self->vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.resize_2d(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ self->size = 2;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resize_3d_doc,
-".. method:: resize_3d()\n"
-"\n"
-" Resize the vector to 3D (x, y, z).\n"
-);
+ ".. method:: resize_3d()\n"
+ "\n"
+ " Resize the vector to 3D (x, y, z).\n");
static PyObject *Vector_resize_3d(VectorObject *self)
{
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_3d(): "
- "cannot resize wrapped data - only python vectors");
- return NULL;
- }
- if (self->cb_user) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_3d(): "
- "cannot resize a vector that has an owner");
- return NULL;
- }
-
- self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 3));
- if (self->vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.resize_3d(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- if (self->size == 2) {
- self->vec[2] = 0.0f;
- }
-
- self->size = 3;
- Py_RETURN_NONE;
+ if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_3d(): "
+ "cannot resize wrapped data - only python vectors");
+ return NULL;
+ }
+ if (self->cb_user) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_3d(): "
+ "cannot resize a vector that has an owner");
+ return NULL;
+ }
+
+ self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 3));
+ if (self->vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.resize_3d(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ if (self->size == 2) {
+ self->vec[2] = 0.0f;
+ }
+
+ self->size = 3;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_resize_4d_doc,
-".. method:: resize_4d()\n"
-"\n"
-" Resize the vector to 4D (x, y, z, w).\n"
-);
+ ".. method:: resize_4d()\n"
+ "\n"
+ " Resize the vector to 4D (x, y, z, w).\n");
static PyObject *Vector_resize_4d(VectorObject *self)
{
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_4d(): "
- "cannot resize wrapped data - only python vectors");
- return NULL;
- }
- if (self->cb_user) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.resize_4d(): "
- "cannot resize a vector that has an owner");
- return NULL;
- }
-
- self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 4));
- if (self->vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector.resize_4d(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- if (self->size == 2) {
- self->vec[2] = 0.0f;
- self->vec[3] = 1.0f;
- }
- else if (self->size == 3) {
- self->vec[3] = 1.0f;
- }
- self->size = 4;
- Py_RETURN_NONE;
+ if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_4d(): "
+ "cannot resize wrapped data - only python vectors");
+ return NULL;
+ }
+ if (self->cb_user) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.resize_4d(): "
+ "cannot resize a vector that has an owner");
+ return NULL;
+ }
+
+ self->vec = PyMem_Realloc(self->vec, (sizeof(float) * 4));
+ if (self->vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector.resize_4d(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ if (self->size == 2) {
+ self->vec[2] = 0.0f;
+ self->vec[3] = 1.0f;
+ }
+ else if (self->size == 3) {
+ self->vec[3] = 1.0f;
+ }
+ self->size = 4;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_to_2d_doc,
-".. method:: to_2d()\n"
-"\n"
-" Return a 2d copy of the vector.\n"
-"\n"
-" :return: a new vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: to_2d()\n"
+ "\n"
+ " Return a 2d copy of the vector.\n"
+ "\n"
+ " :return: a new vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_to_2d(VectorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Vector_CreatePyObject(self->vec, 2, Py_TYPE(self));
+ return Vector_CreatePyObject(self->vec, 2, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_3d_doc,
-".. method:: to_3d()\n"
-"\n"
-" Return a 3d copy of the vector.\n"
-"\n"
-" :return: a new vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: to_3d()\n"
+ "\n"
+ " Return a 3d copy of the vector.\n"
+ "\n"
+ " :return: a new vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_to_3d(VectorObject *self)
{
- float tvec[3] = {0.0f};
+ float tvec[3] = {0.0f};
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 3));
- return Vector_CreatePyObject(tvec, 3, Py_TYPE(self));
+ memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 3));
+ return Vector_CreatePyObject(tvec, 3, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_4d_doc,
-".. method:: to_4d()\n"
-"\n"
-" Return a 4d copy of the vector.\n"
-"\n"
-" :return: a new vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: to_4d()\n"
+ "\n"
+ " Return a 4d copy of the vector.\n"
+ "\n"
+ " :return: a new vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_to_4d(VectorObject *self)
{
- float tvec[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+ float tvec[4] = {0.0f, 0.0f, 0.0f, 1.0f};
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 4));
- return Vector_CreatePyObject(tvec, 4, Py_TYPE(self));
+ memcpy(tvec, self->vec, sizeof(float) * MIN2(self->size, 4));
+ return Vector_CreatePyObject(tvec, 4, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_to_tuple_doc,
-".. 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 [-1, 21].\n"
-" :type precision: int\n"
-" :return: the values of the vector rounded by *precision*\n"
-" :rtype: tuple\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 [-1, 21].\n"
+ " :type precision: int\n"
+ " :return: the values of the vector rounded by *precision*\n"
+ " :rtype: tuple\n");
/* note: BaseMath_ReadCallback must be called beforehand */
static PyObject *Vector_to_tuple_ext(VectorObject *self, int ndigits)
{
- PyObject *ret;
- int i;
+ PyObject *ret;
+ int i;
- ret = PyTuple_New(self->size);
+ 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]));
- }
- }
+ 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;
+ return ret;
}
static PyObject *Vector_to_tuple(VectorObject *self, PyObject *args)
{
- int ndigits = 0;
+ int ndigits = 0;
- if (!PyArg_ParseTuple(args, "|i:to_tuple", &ndigits)) {
- return NULL;
- }
+ 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 (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 (PyTuple_GET_SIZE(args) == 0) {
+ ndigits = -1;
+ }
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Vector_to_tuple_ext(self, ndigits);
+ return Vector_to_tuple_ext(self, ndigits);
}
PyDoc_STRVAR(Vector_to_track_quat_doc,
-".. method:: to_track_quat(track, up)\n"
-"\n"
-" Return a quaternion rotation from the vector and the track and up axis.\n"
-"\n"
-" :arg track: Track axis in ['X', 'Y', 'Z', '-X', '-Y', '-Z'].\n"
-" :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.\n"
-" :rtype: :class:`Quaternion`\n"
-);
+ ".. method:: to_track_quat(track, up)\n"
+ "\n"
+ " Return a quaternion rotation from the vector and the track and up axis.\n"
+ "\n"
+ " :arg track: Track axis in ['X', 'Y', 'Z', '-X', '-Y', '-Z'].\n"
+ " :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.\n"
+ " :rtype: :class:`Quaternion`\n");
static PyObject *Vector_to_track_quat(VectorObject *self, PyObject *args)
{
- float vec[3], quat[4];
- const char *strack, *sup;
- short track = 2, up = 1;
-
- if (!PyArg_ParseTuple(args, "|ss:to_track_quat", &strack, &sup)) {
- return NULL;
- }
-
- if (self->size != 3) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.to_track_quat(): "
- "only for 3D vectors");
- return NULL;
- }
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (strack) {
- const char *axis_err_msg = "only X, -X, Y, -Y, Z or -Z for track axis";
-
- if (strlen(strack) == 2) {
- if (strack[0] == '-') {
- switch (strack[1]) {
- case 'X':
- track = 3;
- break;
- case 'Y':
- track = 4;
- break;
- case 'Z':
- track = 5;
- break;
- default:
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
- else {
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
- else if (strlen(strack) == 1) {
- switch (strack[0]) {
- case '-':
- case 'X':
- track = 0;
- break;
- case 'Y':
- track = 1;
- break;
- case 'Z':
- track = 2;
- break;
- default:
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
- else {
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
-
- if (sup) {
- const char *axis_err_msg = "only X, Y or Z for up axis";
- if (strlen(sup) == 1) {
- switch (*sup) {
- case 'X':
- up = 0;
- break;
- case 'Y':
- up = 1;
- break;
- case 'Z':
- up = 2;
- break;
- default:
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
- else {
- PyErr_SetString(PyExc_ValueError, axis_err_msg);
- return NULL;
- }
- }
-
- if (track == up) {
- PyErr_SetString(PyExc_ValueError,
- "Can't have the same axis for track and up");
- return NULL;
- }
-
- /*
- * flip vector around, since vectoquat expect a vector from target to tracking object
- * and the python function expects the inverse (a vector to the target).
- */
- negate_v3_v3(vec, self->vec);
-
- vec_to_quat(quat, vec, track, up);
-
- return Quaternion_CreatePyObject(quat, NULL);
-}
-
-PyDoc_STRVAR(Vector_orthogonal_doc,
-".. method:: orthogonal()\n"
-"\n"
-" Return a perpendicular vector.\n"
-"\n"
-" :return: a new vector 90 degrees from this vector.\n"
-" :rtype: :class:`Vector`\n"
-"\n"
-" .. note:: the axis is undefined, only use when any orthogonal vector is acceptable.\n"
-);
+ float vec[3], quat[4];
+ const char *strack, *sup;
+ short track = 2, up = 1;
+
+ if (!PyArg_ParseTuple(args, "|ss:to_track_quat", &strack, &sup)) {
+ return NULL;
+ }
+
+ if (self->size != 3) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.to_track_quat(): "
+ "only for 3D vectors");
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (strack) {
+ const char *axis_err_msg = "only X, -X, Y, -Y, Z or -Z for track axis";
+
+ if (strlen(strack) == 2) {
+ if (strack[0] == '-') {
+ switch (strack[1]) {
+ case 'X':
+ track = 3;
+ break;
+ case 'Y':
+ track = 4;
+ break;
+ case 'Z':
+ track = 5;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+ else if (strlen(strack) == 1) {
+ switch (strack[0]) {
+ case '-':
+ case 'X':
+ track = 0;
+ break;
+ case 'Y':
+ track = 1;
+ break;
+ case 'Z':
+ track = 2;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+
+ if (sup) {
+ const char *axis_err_msg = "only X, Y or Z for up axis";
+ if (strlen(sup) == 1) {
+ switch (*sup) {
+ case 'X':
+ up = 0;
+ break;
+ case 'Y':
+ up = 1;
+ break;
+ case 'Z':
+ up = 2;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, axis_err_msg);
+ return NULL;
+ }
+ }
+
+ if (track == up) {
+ PyErr_SetString(PyExc_ValueError, "Can't have the same axis for track and up");
+ return NULL;
+ }
+
+ /*
+ * flip vector around, since vectoquat expect a vector from target to tracking object
+ * and the python function expects the inverse (a vector to the target).
+ */
+ negate_v3_v3(vec, self->vec);
+
+ vec_to_quat(quat, vec, track, up);
+
+ return Quaternion_CreatePyObject(quat, NULL);
+}
+
+PyDoc_STRVAR(
+ Vector_orthogonal_doc,
+ ".. method:: orthogonal()\n"
+ "\n"
+ " Return a perpendicular vector.\n"
+ "\n"
+ " :return: a new vector 90 degrees from this vector.\n"
+ " :rtype: :class:`Vector`\n"
+ "\n"
+ " .. note:: the axis is undefined, only use when any orthogonal vector is acceptable.\n");
static PyObject *Vector_orthogonal(VectorObject *self)
{
- float vec[3];
+ float vec[3];
- if (self->size > 3) {
- PyErr_SetString(PyExc_TypeError,
- "Vector.orthogonal(): "
- "Vector must be 3D or 2D");
- return NULL;
- }
+ if (self->size > 3) {
+ PyErr_SetString(PyExc_TypeError,
+ "Vector.orthogonal(): "
+ "Vector must be 3D or 2D");
+ return NULL;
+ }
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (self->size == 3) {
- ortho_v3_v3(vec, self->vec);
- }
- else {
- ortho_v2_v2(vec, self->vec);
- }
+ if (self->size == 3) {
+ ortho_v3_v3(vec, self->vec);
+ }
+ else {
+ ortho_v2_v2(vec, self->vec);
+ }
- return Vector_CreatePyObject(vec, self->size, Py_TYPE(self));
+ return Vector_CreatePyObject(vec, self->size, Py_TYPE(self));
}
-
/**
* Vector.reflect(mirror): return a reflected vector on the mirror normal.
* <pre>
@@ -861,541 +839,533 @@ static PyObject *Vector_orthogonal(VectorObject *self)
* </pre>
*/
PyDoc_STRVAR(Vector_reflect_doc,
-".. method:: reflect(mirror)\n"
-"\n"
-" Return the reflection vector from the *mirror* argument.\n"
-"\n"
-" :arg mirror: This vector could be a normal from the reflecting surface.\n"
-" :type mirror: :class:`Vector`\n"
-" :return: The reflected vector matching the size of this vector.\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: reflect(mirror)\n"
+ "\n"
+ " Return the reflection vector from the *mirror* argument.\n"
+ "\n"
+ " :arg mirror: This vector could be a normal from the reflecting surface.\n"
+ " :type mirror: :class:`Vector`\n"
+ " :return: The reflected vector matching the size of this vector.\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_reflect(VectorObject *self, PyObject *value)
{
- int value_size;
- float mirror[3], vec[3];
- float reflect[3] = {0.0f};
- float tvec[MAX_DIMENSIONS];
+ int value_size;
+ float mirror[3], vec[3];
+ float reflect[3] = {0.0f};
+ float tvec[MAX_DIMENSIONS];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if ((value_size = mathutils_array_parse(tvec, 2, 4, value, "Vector.reflect(other), invalid 'other' arg")) == -1) {
- return NULL;
- }
+ if ((value_size = mathutils_array_parse(
+ tvec, 2, 4, value, "Vector.reflect(other), invalid 'other' arg")) == -1) {
+ return NULL;
+ }
- if (self->size < 2 || self->size > 4) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 2D, 3D or 4D");
- return NULL;
- }
+ if (self->size < 2 || self->size > 4) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 2D, 3D or 4D");
+ return NULL;
+ }
- mirror[0] = tvec[0];
- mirror[1] = tvec[1];
- mirror[2] = (value_size > 2) ? tvec[2] : 0.0f;
+ mirror[0] = tvec[0];
+ mirror[1] = tvec[1];
+ mirror[2] = (value_size > 2) ? tvec[2] : 0.0f;
- vec[0] = self->vec[0];
- vec[1] = self->vec[1];
- vec[2] = (value_size > 2) ? self->vec[2] : 0.0f;
+ vec[0] = self->vec[0];
+ vec[1] = self->vec[1];
+ vec[2] = (value_size > 2) ? self->vec[2] : 0.0f;
- normalize_v3(mirror);
- reflect_v3_v3v3(reflect, vec, mirror);
+ normalize_v3(mirror);
+ reflect_v3_v3v3(reflect, vec, mirror);
- return Vector_CreatePyObject(reflect, self->size, Py_TYPE(self));
+ return Vector_CreatePyObject(reflect, self->size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_cross_doc,
-".. method:: cross(other)\n"
-"\n"
-" Return the cross product of this vector and another.\n"
-"\n"
-" :arg other: The other vector to perform the cross product with.\n"
-" :type other: :class:`Vector`\n"
-" :return: The cross product.\n"
-" :rtype: :class:`Vector` or float when 2D vectors are used\n"
-"\n"
-" .. note:: both vectors must be 2D or 3D\n"
-);
+ ".. method:: cross(other)\n"
+ "\n"
+ " Return the cross product of this vector and another.\n"
+ "\n"
+ " :arg other: The other vector to perform the cross product with.\n"
+ " :type other: :class:`Vector`\n"
+ " :return: The cross product.\n"
+ " :rtype: :class:`Vector` or float when 2D vectors are used\n"
+ "\n"
+ " .. note:: both vectors must be 2D or 3D\n");
static PyObject *Vector_cross(VectorObject *self, PyObject *value)
{
- PyObject *ret;
- float tvec[3];
+ PyObject *ret;
+ float tvec[3];
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (self->size > 3) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 2D or 3D");
- return NULL;
- }
+ if (self->size > 3) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 2D or 3D");
+ return NULL;
+ }
- if (mathutils_array_parse(tvec, self->size, self->size, value, "Vector.cross(other), invalid 'other' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(
+ tvec, self->size, self->size, value, "Vector.cross(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
- if (self->size == 3) {
- ret = Vector_CreatePyObject(NULL, 3, Py_TYPE(self));
- cross_v3_v3v3(((VectorObject *)ret)->vec, self->vec, tvec);
- }
- else {
- /* size == 2 */
- ret = PyFloat_FromDouble(cross_v2v2(self->vec, tvec));
- }
- return ret;
+ if (self->size == 3) {
+ ret = Vector_CreatePyObject(NULL, 3, Py_TYPE(self));
+ cross_v3_v3v3(((VectorObject *)ret)->vec, self->vec, tvec);
+ }
+ else {
+ /* size == 2 */
+ ret = PyFloat_FromDouble(cross_v2v2(self->vec, tvec));
+ }
+ return ret;
}
PyDoc_STRVAR(Vector_dot_doc,
-".. method:: dot(other)\n"
-"\n"
-" Return the dot product of this vector and another.\n"
-"\n"
-" :arg other: The other vector to perform the dot product with.\n"
-" :type other: :class:`Vector`\n"
-" :return: The dot product.\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. method:: dot(other)\n"
+ "\n"
+ " Return the dot product of this vector and another.\n"
+ "\n"
+ " :arg other: The other vector to perform the dot product with.\n"
+ " :type other: :class:`Vector`\n"
+ " :return: The dot product.\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_dot(VectorObject *self, PyObject *value)
{
- float *tvec;
- PyObject *ret;
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (mathutils_array_parse_alloc(&tvec, self->size, value, "Vector.dot(other), invalid 'other' arg") == -1) {
- return NULL;
- }
-
- ret = PyFloat_FromDouble(dot_vn_vn(self->vec, tvec, self->size));
- PyMem_Free(tvec);
- return ret;
-}
-
-PyDoc_STRVAR(Vector_angle_doc,
-".. function:: angle(other, fallback=None)\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"
-" :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: angle in radians or fallback when given\n"
-" :rtype: float\n"
-);
+ float *tvec;
+ PyObject *ret;
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse_alloc(
+ &tvec, self->size, value, "Vector.dot(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
+
+ ret = PyFloat_FromDouble(dot_vn_vn(self->vec, tvec, self->size));
+ PyMem_Free(tvec);
+ return ret;
+}
+
+PyDoc_STRVAR(
+ Vector_angle_doc,
+ ".. function:: angle(other, fallback=None)\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"
+ " :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: angle in radians or fallback when given\n"
+ " :rtype: float\n");
static PyObject *Vector_angle(VectorObject *self, PyObject *args)
{
- const int size = MIN2(self->size, 3); /* 4D angle makes no sense */
- float tvec[MAX_DIMENSIONS];
- PyObject *value;
- double dot = 0.0f, dot_self = 0.0f, dot_other = 0.0f;
- int x;
- PyObject *fallback = NULL;
-
- if (!PyArg_ParseTuple(args, "O|O:angle", &value, &fallback)) {
- return NULL;
- }
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- /* don't use clamped size, rule of thumb is vector sizes must match,
- * even though n this case 'w' is ignored */
- if (mathutils_array_parse(tvec, self->size, self->size, value, "Vector.angle(other), invalid 'other' arg") == -1) {
- return NULL;
- }
-
- if (self->size > 4) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 2D, 3D or 4D");
- return NULL;
- }
-
- for (x = 0; x < size; x++) {
- dot_self += (double)self->vec[x] * (double)self->vec[x];
- dot_other += (double)tvec[x] * (double)tvec[x];
- dot += (double)self->vec[x] * (double)tvec[x];
- }
-
- if (!dot_self || !dot_other) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Vector.angle(other): "
- "zero length vectors have no valid angle");
- return NULL;
- }
- }
-
- return PyFloat_FromDouble(saacos(dot / (sqrt(dot_self) * sqrt(dot_other))));
-}
-
-PyDoc_STRVAR(Vector_angle_signed_doc,
-".. function:: angle_signed(other, fallback)\n"
-"\n"
-" Return the signed angle between two 2D vectors (clockwise is positive).\n"
-"\n"
-" :arg other: another vector to compare the angle with\n"
-" :type other: :class:`Vector`\n"
-" :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: angle in radians or fallback when given\n"
-" :rtype: float\n"
-);
+ const int size = MIN2(self->size, 3); /* 4D angle makes no sense */
+ float tvec[MAX_DIMENSIONS];
+ PyObject *value;
+ double dot = 0.0f, dot_self = 0.0f, dot_other = 0.0f;
+ int x;
+ PyObject *fallback = NULL;
+
+ if (!PyArg_ParseTuple(args, "O|O:angle", &value, &fallback)) {
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ /* don't use clamped size, rule of thumb is vector sizes must match,
+ * even though n this case 'w' is ignored */
+ if (mathutils_array_parse(
+ tvec, self->size, self->size, value, "Vector.angle(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
+
+ if (self->size > 4) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 2D, 3D or 4D");
+ return NULL;
+ }
+
+ for (x = 0; x < size; x++) {
+ dot_self += (double)self->vec[x] * (double)self->vec[x];
+ dot_other += (double)tvec[x] * (double)tvec[x];
+ dot += (double)self->vec[x] * (double)tvec[x];
+ }
+
+ if (!dot_self || !dot_other) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector.angle(other): "
+ "zero length vectors have no valid angle");
+ return NULL;
+ }
+ }
+
+ return PyFloat_FromDouble(saacos(dot / (sqrt(dot_self) * sqrt(dot_other))));
+}
+
+PyDoc_STRVAR(
+ Vector_angle_signed_doc,
+ ".. function:: angle_signed(other, fallback)\n"
+ "\n"
+ " Return the signed angle between two 2D vectors (clockwise is positive).\n"
+ "\n"
+ " :arg other: another vector to compare the angle with\n"
+ " :type other: :class:`Vector`\n"
+ " :arg fallback: return this when the angle can't be calculated (zero length vector),\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: angle in radians or fallback when given\n"
+ " :rtype: float\n");
static PyObject *Vector_angle_signed(VectorObject *self, PyObject *args)
{
- float tvec[2];
-
- PyObject *value;
- PyObject *fallback = NULL;
+ float tvec[2];
- if (!PyArg_ParseTuple(args, "O|O:angle_signed", &value, &fallback)) {
- return NULL;
- }
+ PyObject *value;
+ PyObject *fallback = NULL;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O|O:angle_signed", &value, &fallback)) {
+ return NULL;
+ }
- if (mathutils_array_parse(tvec, 2, 2, value, "Vector.angle_signed(other), invalid 'other' arg") == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (self->size != 2) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 2D");
- return NULL;
- }
+ if (mathutils_array_parse(
+ tvec, 2, 2, value, "Vector.angle_signed(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
- if (is_zero_v2(self->vec) || is_zero_v2(tvec)) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Vector.angle_signed(other): "
- "zero length vectors have no valid angle");
- return NULL;
- }
- }
+ if (self->size != 2) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 2D");
+ return NULL;
+ }
+ if (is_zero_v2(self->vec) || is_zero_v2(tvec)) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector.angle_signed(other): "
+ "zero length vectors have no valid angle");
+ return NULL;
+ }
+ }
- return PyFloat_FromDouble(angle_signed_v2v2(self->vec, tvec));
+ return PyFloat_FromDouble(angle_signed_v2v2(self->vec, tvec));
}
-
PyDoc_STRVAR(Vector_rotation_difference_doc,
-".. function:: rotation_difference(other)\n"
-"\n"
-" Returns a quaternion representing the rotational difference between this\n"
-" vector and another.\n"
-"\n"
-" :arg other: second vector.\n"
-" :type other: :class:`Vector`\n"
-" :return: the rotational difference between the two vectors.\n"
-" :rtype: :class:`Quaternion`\n"
-"\n"
-" .. note:: 2D vectors raise an :exc:`AttributeError`.\n"
-);
+ ".. function:: rotation_difference(other)\n"
+ "\n"
+ " Returns a quaternion representing the rotational difference between this\n"
+ " vector and another.\n"
+ "\n"
+ " :arg other: second vector.\n"
+ " :type other: :class:`Vector`\n"
+ " :return: the rotational difference between the two vectors.\n"
+ " :rtype: :class:`Quaternion`\n"
+ "\n"
+ " .. note:: 2D vectors raise an :exc:`AttributeError`.\n");
static PyObject *Vector_rotation_difference(VectorObject *self, PyObject *value)
{
- float quat[4], vec_a[3], vec_b[3];
+ float quat[4], vec_a[3], vec_b[3];
- if (self->size < 3 || self->size > 4) {
- PyErr_SetString(PyExc_ValueError,
- "vec.difference(value): "
- "expects both vectors to be size 3 or 4");
- return NULL;
- }
+ if (self->size < 3 || self->size > 4) {
+ PyErr_SetString(PyExc_ValueError,
+ "vec.difference(value): "
+ "expects both vectors to be size 3 or 4");
+ return NULL;
+ }
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse(vec_b, 3, MAX_DIMENSIONS, value, "Vector.difference(other), invalid 'other' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(
+ vec_b, 3, MAX_DIMENSIONS, value, "Vector.difference(other), invalid 'other' arg") ==
+ -1) {
+ return NULL;
+ }
- normalize_v3_v3(vec_a, self->vec);
- normalize_v3(vec_b);
+ normalize_v3_v3(vec_a, self->vec);
+ normalize_v3(vec_b);
- rotation_between_vecs_to_quat(quat, vec_a, vec_b);
+ rotation_between_vecs_to_quat(quat, vec_a, vec_b);
- return Quaternion_CreatePyObject(quat, NULL);
+ return Quaternion_CreatePyObject(quat, NULL);
}
PyDoc_STRVAR(Vector_project_doc,
-".. function:: project(other)\n"
-"\n"
-" Return the projection of this vector onto the *other*.\n"
-"\n"
-" :arg other: second vector.\n"
-" :type other: :class:`Vector`\n"
-" :return: the parallel projection vector\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. function:: project(other)\n"
+ "\n"
+ " Return the projection of this vector onto the *other*.\n"
+ "\n"
+ " :arg other: second vector.\n"
+ " :type other: :class:`Vector`\n"
+ " :return: the parallel projection vector\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_project(VectorObject *self, PyObject *value)
{
- const int size = self->size;
- float *tvec;
- double dot = 0.0f, dot2 = 0.0f;
- int x;
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (mathutils_array_parse_alloc(&tvec, size, value, "Vector.project(other), invalid 'other' arg") == -1) {
- return NULL;
- }
-
- /* get dot products */
- for (x = 0; x < size; x++) {
- dot += (double)(self->vec[x] * tvec[x]);
- dot2 += (double)(tvec[x] * tvec[x]);
- }
- /* projection */
- dot /= dot2;
- for (x = 0; x < size; x++) {
- tvec[x] *= (float)dot;
- }
- return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
+ const int size = self->size;
+ float *tvec;
+ double dot = 0.0f, dot2 = 0.0f;
+ int x;
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse_alloc(
+ &tvec, size, value, "Vector.project(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
+
+ /* get dot products */
+ for (x = 0; x < size; x++) {
+ dot += (double)(self->vec[x] * tvec[x]);
+ dot2 += (double)(tvec[x] * tvec[x]);
+ }
+ /* projection */
+ dot /= dot2;
+ for (x = 0; x < size; x++) {
+ tvec[x] *= (float)dot;
+ }
+ return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_lerp_doc,
-".. function:: lerp(other, factor)\n"
-"\n"
-" Returns the interpolation of two vectors.\n"
-"\n"
-" :arg other: value to interpolate with.\n"
-" :type other: :class:`Vector`\n"
-" :arg factor: The interpolation value in [0.0, 1.0].\n"
-" :type factor: float\n"
-" :return: The interpolated vector.\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. function:: lerp(other, factor)\n"
+ "\n"
+ " Returns the interpolation of two vectors.\n"
+ "\n"
+ " :arg other: value to interpolate with.\n"
+ " :type other: :class:`Vector`\n"
+ " :arg factor: The interpolation value in [0.0, 1.0].\n"
+ " :type factor: float\n"
+ " :return: The interpolated vector.\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_lerp(VectorObject *self, PyObject *args)
{
- const int size = self->size;
- PyObject *value = NULL;
- float fac;
- float *tvec;
+ const int size = self->size;
+ PyObject *value = NULL;
+ float fac;
+ float *tvec;
- if (!PyArg_ParseTuple(args, "Of:lerp", &value, &fac)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "Of:lerp", &value, &fac)) {
+ return NULL;
+ }
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- if (mathutils_array_parse_alloc(&tvec, size, value, "Vector.lerp(other), invalid 'other' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse_alloc(&tvec, size, value, "Vector.lerp(other), invalid 'other' arg") ==
+ -1) {
+ return NULL;
+ }
- interp_vn_vn(tvec, self->vec, 1.0f - fac, size);
+ interp_vn_vn(tvec, self->vec, 1.0f - fac, size);
- return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
+ return Vector_CreatePyObject_alloc(tvec, size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_slerp_doc,
-".. function:: slerp(other, factor, fallback=None)\n"
-"\n"
-" Returns the interpolation of two non-zero vectors (spherical coordinates).\n"
-"\n"
-" :arg other: value to interpolate with.\n"
-" :type other: :class:`Vector`\n"
-" :arg factor: The interpolation value typically in [0.0, 1.0].\n"
-" :type factor: float\n"
-" :arg fallback: return this when the vector can't be calculated (zero length vector or direct opposites),\n"
-" (instead of raising a :exc:`ValueError`).\n"
-" :type fallback: any\n"
-" :return: The interpolated vector.\n"
-" :rtype: :class:`Vector`\n"
-);
+ ".. function:: slerp(other, factor, fallback=None)\n"
+ "\n"
+ " Returns the interpolation of two non-zero vectors (spherical coordinates).\n"
+ "\n"
+ " :arg other: value to interpolate with.\n"
+ " :type other: :class:`Vector`\n"
+ " :arg factor: The interpolation value typically in [0.0, 1.0].\n"
+ " :type factor: float\n"
+ " :arg fallback: return this when the vector can't be calculated (zero length "
+ "vector or direct opposites),\n"
+ " (instead of raising a :exc:`ValueError`).\n"
+ " :type fallback: any\n"
+ " :return: The interpolated vector.\n"
+ " :rtype: :class:`Vector`\n");
static PyObject *Vector_slerp(VectorObject *self, PyObject *args)
{
- const int size = self->size;
- PyObject *value = NULL;
- float fac, cosom, w[2];
- float self_vec[3], other_vec[3], ret_vec[3];
- float self_len_sq, other_len_sq;
- int x;
- PyObject *fallback = NULL;
-
- if (!PyArg_ParseTuple(args, "Of|O:slerp", &value, &fac, &fallback)) {
- return NULL;
- }
-
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
-
- if (self->size > 3) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 2D or 3D");
- return NULL;
- }
-
- if (mathutils_array_parse(other_vec, size, size, value, "Vector.slerp(other), invalid 'other' arg") == -1) {
- return NULL;
- }
-
- self_len_sq = normalize_vn_vn(self_vec, self->vec, size);
- other_len_sq = normalize_vn(other_vec, size);
-
- /* use fallbacks for zero length vectors */
- if (UNLIKELY((self_len_sq < FLT_EPSILON) ||
- (other_len_sq < FLT_EPSILON)))
- {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Vector.slerp(): "
- "zero length vectors unsupported");
- return NULL;
- }
- }
-
- /* We have sane state, execute slerp */
- cosom = (float)dot_vn_vn(self_vec, other_vec, size);
-
- /* direct opposite, can't slerp */
- if (UNLIKELY(cosom < (-1.0f + FLT_EPSILON))) {
- /* avoid exception */
- if (fallback) {
- Py_INCREF(fallback);
- return fallback;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "Vector.slerp(): "
- "opposite vectors unsupported");
- return NULL;
- }
- }
-
- interp_dot_slerp(fac, cosom, w);
-
- for (x = 0; x < size; x++) {
- ret_vec[x] = (w[0] * self_vec[x]) + (w[1] * other_vec[x]);
- }
-
- return Vector_CreatePyObject(ret_vec, size, Py_TYPE(self));
+ const int size = self->size;
+ PyObject *value = NULL;
+ float fac, cosom, w[2];
+ float self_vec[3], other_vec[3], ret_vec[3];
+ float self_len_sq, other_len_sq;
+ int x;
+ PyObject *fallback = NULL;
+
+ if (!PyArg_ParseTuple(args, "Of|O:slerp", &value, &fac, &fallback)) {
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
+
+ if (self->size > 3) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 2D or 3D");
+ return NULL;
+ }
+
+ if (mathutils_array_parse(
+ other_vec, size, size, value, "Vector.slerp(other), invalid 'other' arg") == -1) {
+ return NULL;
+ }
+
+ self_len_sq = normalize_vn_vn(self_vec, self->vec, size);
+ other_len_sq = normalize_vn(other_vec, size);
+
+ /* use fallbacks for zero length vectors */
+ if (UNLIKELY((self_len_sq < FLT_EPSILON) || (other_len_sq < FLT_EPSILON))) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector.slerp(): "
+ "zero length vectors unsupported");
+ return NULL;
+ }
+ }
+
+ /* We have sane state, execute slerp */
+ cosom = (float)dot_vn_vn(self_vec, other_vec, size);
+
+ /* direct opposite, can't slerp */
+ if (UNLIKELY(cosom < (-1.0f + FLT_EPSILON))) {
+ /* avoid exception */
+ if (fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector.slerp(): "
+ "opposite vectors unsupported");
+ return NULL;
+ }
+ }
+
+ interp_dot_slerp(fac, cosom, w);
+
+ for (x = 0; x < size; x++) {
+ ret_vec[x] = (w[0] * self_vec[x]) + (w[1] * other_vec[x]);
+ }
+
+ return Vector_CreatePyObject(ret_vec, size, Py_TYPE(self));
}
PyDoc_STRVAR(Vector_rotate_doc,
-".. function:: rotate(other)\n"
-"\n"
-" Rotate the vector by a rotation value.\n"
-"\n"
-" :arg other: rotation component of mathutils value\n"
-" :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n"
-);
+ ".. function:: rotate(other)\n"
+ "\n"
+ " Rotate the vector by a rotation value.\n"
+ "\n"
+ " :arg other: rotation component of mathutils value\n"
+ " :type other: :class:`Euler`, :class:`Quaternion` or :class:`Matrix`\n");
static PyObject *Vector_rotate(VectorObject *self, PyObject *value)
{
- float other_rmat[3][3];
+ float other_rmat[3][3];
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return NULL;
+ }
- if (mathutils_any_to_rotmat(other_rmat, value, "Vector.rotate(value)") == -1) {
- return NULL;
- }
+ if (mathutils_any_to_rotmat(other_rmat, value, "Vector.rotate(value)") == -1) {
+ return NULL;
+ }
- if (self->size < 3 || self->size > 4) {
- PyErr_SetString(PyExc_ValueError,
- "Vector must be 3D or 4D");
- return NULL;
- }
+ if (self->size < 3 || self->size > 4) {
+ PyErr_SetString(PyExc_ValueError, "Vector must be 3D or 4D");
+ return NULL;
+ }
- mul_m3_v3(other_rmat, self->vec);
+ mul_m3_v3(other_rmat, self->vec);
- (void)BaseMath_WriteCallback(self);
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(Vector_copy_doc,
-".. function:: copy()\n"
-"\n"
-" Returns a copy of this vector.\n"
-"\n"
-" :return: A copy of the vector.\n"
-" :rtype: :class:`Vector`\n"
-"\n"
-" .. note:: use this to get a copy of a wrapped vector with\n"
-" no reference to the original data.\n"
-);
+ ".. function:: copy()\n"
+ "\n"
+ " Returns a copy of this vector.\n"
+ "\n"
+ " :return: A copy of the vector.\n"
+ " :rtype: :class:`Vector`\n"
+ "\n"
+ " .. note:: use this to get a copy of a wrapped vector with\n"
+ " no reference to the original data.\n");
static PyObject *Vector_copy(VectorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return Vector_CreatePyObject(self->vec, self->size, Py_TYPE(self));
+ return Vector_CreatePyObject(self->vec, self->size, Py_TYPE(self));
}
static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args)
{
- if (!PyC_CheckArgs_DeepCopy(args)) {
- return NULL;
- }
- return Vector_copy(self);
+ if (!PyC_CheckArgs_DeepCopy(args)) {
+ return NULL;
+ }
+ return Vector_copy(self);
}
static PyObject *Vector_repr(VectorObject *self)
{
- PyObject *ret, *tuple;
+ PyObject *ret, *tuple;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- tuple = Vector_to_tuple_ext(self, -1);
- ret = PyUnicode_FromFormat("Vector(%R)", tuple);
- Py_DECREF(tuple);
- return ret;
+ tuple = Vector_to_tuple_ext(self, -1);
+ ret = PyUnicode_FromFormat("Vector(%R)", tuple);
+ Py_DECREF(tuple);
+ return ret;
}
#ifndef MATH_STANDALONE
static PyObject *Vector_str(VectorObject *self)
{
- int i;
+ int i;
- DynStr *ds;
+ DynStr *ds;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- ds = BLI_dynstr_new();
+ ds = BLI_dynstr_new();
- BLI_dynstr_append(ds, "<Vector (");
+ BLI_dynstr_append(ds, "<Vector (");
- for (i = 0; i < self->size; i++) {
- BLI_dynstr_appendf(ds, i ? ", %.4f" : "%.4f", self->vec[i]);
- }
+ for (i = 0; i < self->size; i++) {
+ BLI_dynstr_appendf(ds, i ? ", %.4f" : "%.4f", self->vec[i]);
+ }
- BLI_dynstr_append(ds, ")>");
+ BLI_dynstr_append(ds, ")>");
- return mathutils_dynstr_to_py(ds); /* frees ds */
+ return mathutils_dynstr_to_py(ds); /* frees ds */
}
#endif
@@ -1403,299 +1373,304 @@ static PyObject *Vector_str(VectorObject *self)
/* sequence length len(vector) */
static int Vector_len(VectorObject *self)
{
- return self->size;
+ return self->size;
}
/* sequence accessor (get): vector[index] */
static PyObject *vector_item_internal(VectorObject *self, int i, const bool is_attr)
{
- if (i < 0) {
- i = self->size - i;
- }
+ if (i < 0) {
+ i = self->size - i;
+ }
- if (i < 0 || i >= self->size) {
- if (is_attr) {
- PyErr_Format(PyExc_AttributeError,
- "Vector.%c: unavailable on %dd vector",
- *(((char *)"xyzw") + i), self->size);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "vector[index]: out of range");
- }
- return NULL;
- }
+ if (i < 0 || i >= self->size) {
+ if (is_attr) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector.%c: unavailable on %dd vector",
+ *(((char *)"xyzw") + i),
+ self->size);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "vector[index]: out of range");
+ }
+ return NULL;
+ }
- if (BaseMath_ReadIndexCallback(self, i) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadIndexCallback(self, i) == -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(self->vec[i]);
+ return PyFloat_FromDouble(self->vec[i]);
}
static PyObject *Vector_item(VectorObject *self, int i)
{
- return vector_item_internal(self, i, false);
+ return vector_item_internal(self, i, false);
}
/* sequence accessor (set): vector[index] = value */
static int vector_ass_item_internal(VectorObject *self, int i, PyObject *value, const bool is_attr)
{
- float scalar;
-
- if (BaseMath_Prepare_ForWrite(self) == -1) {
- return -1;
- }
-
- if ((scalar = PyFloat_AsDouble(value)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError,
- "vector[index] = x: "
- "assigned value not a number");
- return -1;
- }
-
- if (i < 0) {
- i = self->size - i;
- }
-
- if (i < 0 || i >= self->size) {
- if (is_attr) {
- PyErr_Format(PyExc_AttributeError,
- "Vector.%c = x: unavailable on %dd vector",
- *(((char *)"xyzw") + i), self->size);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "vector[index] = x: "
- "assignment index out of range");
- }
- return -1;
- }
- self->vec[i] = scalar;
-
- if (BaseMath_WriteIndexCallback(self, i) == -1) {
- return -1;
- }
- return 0;
+ float scalar;
+
+ if (BaseMath_Prepare_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ if ((scalar = PyFloat_AsDouble(value)) == -1.0f &&
+ PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError,
+ "vector[index] = x: "
+ "assigned value not a number");
+ return -1;
+ }
+
+ if (i < 0) {
+ i = self->size - i;
+ }
+
+ if (i < 0 || i >= self->size) {
+ if (is_attr) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector.%c = x: unavailable on %dd vector",
+ *(((char *)"xyzw") + i),
+ self->size);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError,
+ "vector[index] = x: "
+ "assignment index out of range");
+ }
+ return -1;
+ }
+ self->vec[i] = scalar;
+
+ if (BaseMath_WriteIndexCallback(self, i) == -1) {
+ return -1;
+ }
+ return 0;
}
static int Vector_ass_item(VectorObject *self, int i, PyObject *value)
{
- return vector_ass_item_internal(self, i, value, false);
+ return vector_ass_item_internal(self, i, value, false);
}
/* sequence slice (get): vector[a:b] */
static PyObject *Vector_slice(VectorObject *self, int begin, int end)
{
- PyObject *tuple;
- int count;
+ PyObject *tuple;
+ int count;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- CLAMP(begin, 0, self->size);
- if (end < 0) {
- end = self->size + end + 1;
- }
- CLAMP(end, 0, self->size);
- begin = MIN2(begin, end);
+ CLAMP(begin, 0, self->size);
+ if (end < 0) {
+ end = self->size + end + 1;
+ }
+ CLAMP(end, 0, self->size);
+ begin = MIN2(begin, end);
- tuple = PyTuple_New(end - begin);
- for (count = begin; count < end; count++) {
- PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->vec[count]));
- }
+ tuple = PyTuple_New(end - begin);
+ for (count = begin; count < end; count++) {
+ PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(self->vec[count]));
+ }
- return tuple;
+ return tuple;
}
/* sequence slice (set): vector[a:b] = value */
static int Vector_ass_slice(VectorObject *self, int begin, int end, PyObject *seq)
{
- int size = 0;
- float *vec = NULL;
+ int size = 0;
+ float *vec = NULL;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- CLAMP(begin, 0, self->size);
- CLAMP(end, 0, self->size);
- begin = MIN2(begin, end);
+ CLAMP(begin, 0, self->size);
+ CLAMP(end, 0, self->size);
+ begin = MIN2(begin, end);
- size = (end - begin);
- if (mathutils_array_parse_alloc(&vec, size, seq, "vector[begin:end] = [...]") == -1) {
- return -1;
- }
+ size = (end - begin);
+ if (mathutils_array_parse_alloc(&vec, size, seq, "vector[begin:end] = [...]") == -1) {
+ return -1;
+ }
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "vec[:] = seq: "
- "problem allocating pointer space");
- return -1;
- }
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "vec[:] = seq: "
+ "problem allocating pointer space");
+ return -1;
+ }
- /*parsed well - now set in vector*/
- memcpy(self->vec + begin, vec, size * sizeof(float));
+ /*parsed well - now set in vector*/
+ memcpy(self->vec + begin, vec, size * sizeof(float));
- PyMem_Free(vec);
+ PyMem_Free(vec);
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
- return 0;
+ return 0;
}
/* Numeric Protocols */
/* addition: obj + obj */
static PyObject *Vector_add(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
- float *vec = NULL;
-
- if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
- PyErr_Format(PyExc_AttributeError,
- "Vector addition: (%s + %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- vec1 = (VectorObject *)v1;
- vec2 = (VectorObject *)v2;
-
- if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
-
- /*VECTOR + VECTOR*/
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector addition: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
-
- vec = PyMem_Malloc(vec1->size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector(): "
- "problem allocating pointer space");
- return NULL;
- }
-
- add_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
-
- return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
+ VectorObject *vec1 = NULL, *vec2 = NULL;
+ float *vec = NULL;
+
+ if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector addition: (%s + %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ vec1 = (VectorObject *)v1;
+ vec2 = (VectorObject *)v2;
+
+ if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+
+ /*VECTOR + VECTOR*/
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector addition: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
+
+ vec = PyMem_Malloc(vec1->size * sizeof(float));
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
+
+ add_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
+
+ return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* addition in-place: obj += obj */
static PyObject *Vector_iadd(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
+ VectorObject *vec1 = NULL, *vec2 = NULL;
- if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
- PyErr_Format(PyExc_AttributeError,
- "Vector addition: (%s += %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- vec1 = (VectorObject *)v1;
- vec2 = (VectorObject *)v2;
+ if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector addition: (%s += %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ vec1 = (VectorObject *)v1;
+ vec2 = (VectorObject *)v2;
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector addition: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector addition: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
- if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
- add_vn_vn(vec1->vec, vec2->vec, vec1->size);
+ add_vn_vn(vec1->vec, vec2->vec, vec1->size);
- (void)BaseMath_WriteCallback(vec1);
- Py_INCREF(v1);
- return v1;
+ (void)BaseMath_WriteCallback(vec1);
+ Py_INCREF(v1);
+ return v1;
}
/* subtraction: obj - obj */
static PyObject *Vector_sub(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
- float *vec;
+ VectorObject *vec1 = NULL, *vec2 = NULL;
+ float *vec;
- if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
- PyErr_Format(PyExc_AttributeError,
- "Vector subtraction: (%s - %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- vec1 = (VectorObject *)v1;
- vec2 = (VectorObject *)v2;
+ if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector subtraction: (%s - %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ vec1 = (VectorObject *)v1;
+ vec2 = (VectorObject *)v2;
- if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector subtraction: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector subtraction: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
- vec = PyMem_Malloc(vec1->size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector(): "
- "problem allocating pointer space");
- return NULL;
- }
+ vec = PyMem_Malloc(vec1->size * sizeof(float));
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector(): "
+ "problem allocating pointer space");
+ return NULL;
+ }
- sub_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
+ sub_vn_vnvn(vec, vec1->vec, vec2->vec, vec1->size);
- return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
+ return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* subtraction in-place: obj -= obj */
static PyObject *Vector_isub(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
+ VectorObject *vec1 = NULL, *vec2 = NULL;
- if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
- PyErr_Format(PyExc_AttributeError,
- "Vector subtraction: (%s -= %s) "
- "invalid type for this operation",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
- vec1 = (VectorObject *)v1;
- vec2 = (VectorObject *)v2;
+ if (!VectorObject_Check(v1) || !VectorObject_Check(v2)) {
+ PyErr_Format(PyExc_AttributeError,
+ "Vector subtraction: (%s -= %s) "
+ "invalid type for this operation",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+ vec1 = (VectorObject *)v1;
+ vec2 = (VectorObject *)v2;
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector subtraction: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector subtraction: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
- if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(vec1) == -1 || BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
- sub_vn_vn(vec1->vec, vec2->vec, vec1->size);
+ sub_vn_vn(vec1->vec, vec2->vec, vec1->size);
- (void)BaseMath_WriteCallback(vec1);
- Py_INCREF(v1);
- return v1;
+ (void)BaseMath_WriteCallback(vec1);
+ Py_INCREF(v1);
+ return v1;
}
/*------------------------obj * obj------------------------------
* multiplication */
-
/**
* Column vector multiplication (Matrix * Vector).
* <pre>
@@ -1709,576 +1684,577 @@ static PyObject *Vector_isub(PyObject *v1, PyObject *v2)
*/
int column_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat)
{
- float vec_cpy[MAX_DIMENSIONS];
- int row, col, z = 0;
+ float vec_cpy[MAX_DIMENSIONS];
+ int row, col, z = 0;
- if (mat->num_col != vec->size) {
- if (mat->num_col == 4 && vec->size == 3) {
- vec_cpy[3] = 1.0f;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "matrix * vector: "
- "len(matrix.col) and len(vector) must be the same, "
- "except for 4x4 matrix * 3D vector.");
- return -1;
- }
- }
+ if (mat->num_col != vec->size) {
+ if (mat->num_col == 4 && vec->size == 3) {
+ vec_cpy[3] = 1.0f;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "matrix * vector: "
+ "len(matrix.col) and len(vector) must be the same, "
+ "except for 4x4 matrix * 3D vector.");
+ return -1;
+ }
+ }
- memcpy(vec_cpy, vec->vec, vec->size * sizeof(float));
+ memcpy(vec_cpy, vec->vec, vec->size * sizeof(float));
- r_vec[3] = 1.0f;
+ r_vec[3] = 1.0f;
- for (row = 0; row < mat->num_row; row++) {
- double dot = 0.0f;
- for (col = 0; col < mat->num_col; col++) {
- dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[col]);
- }
- r_vec[z++] = (float)dot;
- }
+ for (row = 0; row < mat->num_row; row++) {
+ double dot = 0.0f;
+ for (col = 0; col < mat->num_col; col++) {
+ dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[col]);
+ }
+ r_vec[z++] = (float)dot;
+ }
- return 0;
+ return 0;
}
static PyObject *vector_mul_float(VectorObject *vec, const float scalar)
{
- float *tvec = PyMem_Malloc(vec->size * sizeof(float));
- if (tvec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "vec * float: "
- "problem allocating pointer space");
- return NULL;
- }
+ float *tvec = PyMem_Malloc(vec->size * sizeof(float));
+ if (tvec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "vec * float: "
+ "problem allocating pointer space");
+ return NULL;
+ }
- mul_vn_vn_fl(tvec, vec->vec, vec->size, scalar);
- return Vector_CreatePyObject_alloc(tvec, vec->size, Py_TYPE(vec));
+ mul_vn_vn_fl(tvec, vec->vec, vec->size, scalar);
+ return Vector_CreatePyObject_alloc(tvec, vec->size, Py_TYPE(vec));
}
#ifdef USE_MATHUTILS_ELEM_MUL
static PyObject *vector_mul_vec(VectorObject *vec1, VectorObject *vec2)
{
- float *tvec = PyMem_Malloc(vec1->size * sizeof(float));
- if (tvec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "vec * vec: "
- "problem allocating pointer space");
- return NULL;
- }
+ float *tvec = PyMem_Malloc(vec1->size * sizeof(float));
+ if (tvec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "vec * vec: "
+ "problem allocating pointer space");
+ return NULL;
+ }
- mul_vn_vnvn(tvec, vec1->vec, vec2->vec, vec1->size);
- return Vector_CreatePyObject_alloc(tvec, vec1->size, Py_TYPE(vec1));
+ mul_vn_vnvn(tvec, vec1->vec, vec2->vec, vec1->size);
+ return Vector_CreatePyObject_alloc(tvec, vec1->size, Py_TYPE(vec1));
}
#endif
static PyObject *Vector_mul(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
- float scalar;
-
- if (VectorObject_Check(v1)) {
- vec1 = (VectorObject *)v1;
- if (BaseMath_ReadCallback(vec1) == -1) {
- return NULL;
- }
- }
- if (VectorObject_Check(v2)) {
- vec2 = (VectorObject *)v2;
- if (BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
- }
-
-
- /* Intentionally don't support (Quaternion) here, uses reverse order instead. */
-
- /* make sure v1 is always the vector */
- if (vec1 && vec2) {
+ VectorObject *vec1 = NULL, *vec2 = NULL;
+ float scalar;
+
+ if (VectorObject_Check(v1)) {
+ vec1 = (VectorObject *)v1;
+ if (BaseMath_ReadCallback(vec1) == -1) {
+ return NULL;
+ }
+ }
+ if (VectorObject_Check(v2)) {
+ vec2 = (VectorObject *)v2;
+ if (BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+ }
+
+ /* Intentionally don't support (Quaternion) here, uses reverse order instead. */
+
+ /* make sure v1 is always the vector */
+ if (vec1 && vec2) {
#ifdef USE_MATHUTILS_ELEM_MUL
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_ValueError,
- "Vector multiplication: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
-
- /* element-wise product */
- return vector_mul_vec(vec1, vec2);
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector multiplication: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
+
+ /* element-wise product */
+ return vector_mul_vec(vec1, vec2);
#endif
- }
- else if (vec1) {
- if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* VEC * FLOAT */
- return vector_mul_float(vec1, scalar);
- }
- }
- else if (vec2) {
- if (((scalar = PyFloat_AsDouble(v1)) == -1.0f && PyErr_Occurred()) == 0) { /* FLOAT * VEC */
- return vector_mul_float(vec2, scalar);
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ }
+ else if (vec1) {
+ if (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0) { /* VEC * FLOAT */
+ return vector_mul_float(vec1, scalar);
+ }
+ }
+ else if (vec2) {
+ if (((scalar = PyFloat_AsDouble(v1)) == -1.0f && PyErr_Occurred()) == 0) { /* FLOAT * VEC */
+ return vector_mul_float(vec2, scalar);
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
}
/* multiplication in-place: obj *= obj */
static PyObject *Vector_imul(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
- float scalar;
-
- if (VectorObject_Check(v1)) {
- vec1 = (VectorObject *)v1;
- if (BaseMath_ReadCallback(vec1) == -1) {
- return NULL;
- }
- }
- if (VectorObject_Check(v2)) {
- vec2 = (VectorObject *)v2;
- if (BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
- }
-
- if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
- return NULL;
- }
-
- /* Intentionally don't support (Quaternion, Matrix) here, uses reverse order instead. */
-
- if (vec1 && vec2) {
+ VectorObject *vec1 = NULL, *vec2 = NULL;
+ float scalar;
+
+ if (VectorObject_Check(v1)) {
+ vec1 = (VectorObject *)v1;
+ if (BaseMath_ReadCallback(vec1) == -1) {
+ return NULL;
+ }
+ }
+ if (VectorObject_Check(v2)) {
+ vec2 = (VectorObject *)v2;
+ if (BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+ }
+
+ if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
+ return NULL;
+ }
+
+ /* Intentionally don't support (Quaternion, Matrix) here, uses reverse order instead. */
+
+ if (vec1 && vec2) {
#ifdef USE_MATHUTILS_ELEM_MUL
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_ValueError,
- "Vector multiplication: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
-
- /* element-wise product inplace */
- mul_vn_vn(vec1->vec, vec2->vec, vec1->size);
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector multiplication: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
+
+ /* element-wise product inplace */
+ mul_vn_vn(vec1->vec, vec2->vec, vec1->size);
#else
- PyErr_Format(PyExc_TypeError,
- "Inplace element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "Inplace element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
#endif
- }
- else if (vec1 && (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) == 0)) { /* VEC *= FLOAT */
- mul_vn_fl(vec1->vec, vec1->size, scalar);
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "Inplace element-wise multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
- }
-
- (void)BaseMath_WriteCallback(vec1);
- Py_INCREF(v1);
- return v1;
+ }
+ else if (vec1 && (((scalar = PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) ==
+ 0)) { /* VEC *= FLOAT */
+ mul_vn_fl(vec1->vec, vec1->size, scalar);
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "Inplace element-wise multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
+ }
+
+ (void)BaseMath_WriteCallback(vec1);
+ Py_INCREF(v1);
+ return v1;
}
static PyObject *Vector_matmul(PyObject *v1, PyObject *v2)
{
- VectorObject *vec1 = NULL, *vec2 = NULL;
- int vec_size;
-
- if (VectorObject_Check(v1)) {
- vec1 = (VectorObject *)v1;
- if (BaseMath_ReadCallback(vec1) == -1) {
- return NULL;
- }
- }
- if (VectorObject_Check(v2)) {
- vec2 = (VectorObject *)v2;
- if (BaseMath_ReadCallback(vec2) == -1) {
- return NULL;
- }
- }
-
-
- /* Intentionally don't support (Quaternion) here, uses reverse order instead. */
-
- /* make sure v1 is always the vector */
- if (vec1 && vec2) {
- if (vec1->size != vec2->size) {
- PyErr_SetString(PyExc_ValueError,
- "Vector multiplication: "
- "vectors must have the same dimensions for this operation");
- return NULL;
- }
-
- /*dot product*/
- return PyFloat_FromDouble(dot_vn_vn(vec1->vec, vec2->vec, vec1->size));
- }
- else if (vec1) {
- if (MatrixObject_Check(v2)) {
- /* VEC @ MATRIX */
- float tvec[MAX_DIMENSIONS];
-
- if (BaseMath_ReadCallback((MatrixObject *)v2) == -1) {
- return NULL;
- }
- if (row_vector_multiplication(tvec, vec1, (MatrixObject *)v2) == -1) {
- return NULL;
- }
-
- if (((MatrixObject *)v2)->num_row == 4 && vec1->size == 3) {
- vec_size = 3;
- }
- else {
- vec_size = ((MatrixObject *)v2)->num_col;
- }
-
- return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(vec1));
- }
- }
-
- PyErr_Format(PyExc_TypeError,
- "Vector multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ VectorObject *vec1 = NULL, *vec2 = NULL;
+ int vec_size;
+
+ if (VectorObject_Check(v1)) {
+ vec1 = (VectorObject *)v1;
+ if (BaseMath_ReadCallback(vec1) == -1) {
+ return NULL;
+ }
+ }
+ if (VectorObject_Check(v2)) {
+ vec2 = (VectorObject *)v2;
+ if (BaseMath_ReadCallback(vec2) == -1) {
+ return NULL;
+ }
+ }
+
+ /* Intentionally don't support (Quaternion) here, uses reverse order instead. */
+
+ /* make sure v1 is always the vector */
+ if (vec1 && vec2) {
+ if (vec1->size != vec2->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "Vector multiplication: "
+ "vectors must have the same dimensions for this operation");
+ return NULL;
+ }
+
+ /*dot product*/
+ return PyFloat_FromDouble(dot_vn_vn(vec1->vec, vec2->vec, vec1->size));
+ }
+ else if (vec1) {
+ if (MatrixObject_Check(v2)) {
+ /* VEC @ MATRIX */
+ float tvec[MAX_DIMENSIONS];
+
+ if (BaseMath_ReadCallback((MatrixObject *)v2) == -1) {
+ return NULL;
+ }
+ if (row_vector_multiplication(tvec, vec1, (MatrixObject *)v2) == -1) {
+ return NULL;
+ }
+
+ if (((MatrixObject *)v2)->num_row == 4 && vec1->size == 3) {
+ vec_size = 3;
+ }
+ else {
+ vec_size = ((MatrixObject *)v2)->num_col;
+ }
+
+ return Vector_CreatePyObject(tvec, vec_size, Py_TYPE(vec1));
+ }
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "Vector multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
}
static PyObject *Vector_imatmul(PyObject *v1, PyObject *v2)
{
- PyErr_Format(PyExc_TypeError,
- "Inplace vector multiplication: "
- "not supported between '%.200s' and '%.200s' types",
- Py_TYPE(v1)->tp_name, Py_TYPE(v2)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "Inplace vector multiplication: "
+ "not supported between '%.200s' and '%.200s' types",
+ Py_TYPE(v1)->tp_name,
+ Py_TYPE(v2)->tp_name);
+ return NULL;
}
/* divid: obj / obj */
static PyObject *Vector_div(PyObject *v1, PyObject *v2)
{
- float *vec = NULL, scalar;
- VectorObject *vec1 = NULL;
+ float *vec = NULL, scalar;
+ VectorObject *vec1 = NULL;
- if (!VectorObject_Check(v1)) { /* not a vector */
- PyErr_SetString(PyExc_TypeError,
- "Vector division: "
- "Vector must be divided by a float");
- return NULL;
- }
- vec1 = (VectorObject *)v1; /* vector */
+ if (!VectorObject_Check(v1)) { /* not a vector */
+ PyErr_SetString(PyExc_TypeError,
+ "Vector division: "
+ "Vector must be divided by a float");
+ return NULL;
+ }
+ vec1 = (VectorObject *)v1; /* vector */
- if (BaseMath_ReadCallback(vec1) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(vec1) == -1) {
+ return NULL;
+ }
- 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");
- return NULL;
- }
+ 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");
+ return NULL;
+ }
- if (scalar == 0.0f) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "Vector division: "
- "divide by zero error");
- return NULL;
- }
+ if (scalar == 0.0f) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "Vector division: "
+ "divide by zero error");
+ return NULL;
+ }
- vec = PyMem_Malloc(vec1->size * sizeof(float));
+ vec = PyMem_Malloc(vec1->size * sizeof(float));
- if (vec == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "vec / value: "
- "problem allocating pointer space");
- return NULL;
- }
+ if (vec == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "vec / value: "
+ "problem allocating pointer space");
+ return NULL;
+ }
- mul_vn_vn_fl(vec, vec1->vec, vec1->size, 1.0f / scalar);
+ mul_vn_vn_fl(vec, vec1->vec, vec1->size, 1.0f / scalar);
- return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
+ return Vector_CreatePyObject_alloc(vec, vec1->size, Py_TYPE(v1));
}
/* divide in-place: obj /= obj */
static PyObject *Vector_idiv(PyObject *v1, PyObject *v2)
{
- float scalar;
- VectorObject *vec1 = (VectorObject *)v1;
+ float scalar;
+ VectorObject *vec1 = (VectorObject *)v1;
- if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback_ForWrite(vec1) == -1) {
+ return NULL;
+ }
- 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");
- return NULL;
- }
+ 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");
+ return NULL;
+ }
- if (scalar == 0.0f) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "Vector division: "
- "divide by zero error");
- return NULL;
- }
+ if (scalar == 0.0f) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "Vector division: "
+ "divide by zero error");
+ return NULL;
+ }
- mul_vn_fl(vec1->vec, vec1->size, 1.0f / scalar);
+ mul_vn_fl(vec1->vec, vec1->size, 1.0f / scalar);
- (void)BaseMath_WriteCallback(vec1);
+ (void)BaseMath_WriteCallback(vec1);
- Py_INCREF(v1);
- return v1;
+ Py_INCREF(v1);
+ return v1;
}
/* -obj
* returns the negative of this object*/
static PyObject *Vector_neg(VectorObject *self)
{
- float *tvec;
+ float *tvec;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- tvec = PyMem_Malloc(self->size * sizeof(float));
- negate_vn_vn(tvec, self->vec, self->size);
- return Vector_CreatePyObject_alloc(tvec, self->size, Py_TYPE(self));
+ tvec = PyMem_Malloc(self->size * sizeof(float));
+ negate_vn_vn(tvec, self->vec, self->size);
+ return Vector_CreatePyObject_alloc(tvec, self->size, Py_TYPE(self));
}
/*------------------------tp_richcmpr
* returns -1 exception, 0 false, 1 true */
static PyObject *Vector_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
{
- VectorObject *vecA = NULL, *vecB = NULL;
- int result = 0;
- double epsilon = 0.000001f;
- double lenA, lenB;
-
- if (!VectorObject_Check(objectA) || !VectorObject_Check(objectB)) {
- if (comparison_type == Py_NE) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
- }
- vecA = (VectorObject *)objectA;
- vecB = (VectorObject *)objectB;
-
- if (BaseMath_ReadCallback(vecA) == -1 || BaseMath_ReadCallback(vecB) == -1) {
- return NULL;
- }
-
- if (vecA->size != vecB->size) {
- if (comparison_type == Py_NE) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
- }
-
- switch (comparison_type) {
- case Py_LT:
- lenA = len_squared_vn(vecA->vec, vecA->size);
- lenB = len_squared_vn(vecB->vec, vecB->size);
- if (lenA < lenB) {
- result = 1;
- }
- break;
- case Py_LE:
- lenA = len_squared_vn(vecA->vec, vecA->size);
- lenB = len_squared_vn(vecB->vec, vecB->size);
- if (lenA < lenB) {
- result = 1;
- }
- else {
- result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
- }
- break;
- case Py_EQ:
- result = EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
- break;
- case Py_NE:
- result = !EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
- break;
- case Py_GT:
- lenA = len_squared_vn(vecA->vec, vecA->size);
- lenB = len_squared_vn(vecB->vec, vecB->size);
- if (lenA > lenB) {
- result = 1;
- }
- break;
- case Py_GE:
- lenA = len_squared_vn(vecA->vec, vecA->size);
- lenB = len_squared_vn(vecB->vec, vecB->size);
- if (lenA > lenB) {
- result = 1;
- }
- else {
- result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
- }
- break;
- default:
- printf("The result of the comparison could not be evaluated");
- break;
- }
- if (result == 1) {
- Py_RETURN_TRUE;
- }
- else {
- Py_RETURN_FALSE;
- }
+ VectorObject *vecA = NULL, *vecB = NULL;
+ int result = 0;
+ double epsilon = 0.000001f;
+ double lenA, lenB;
+
+ if (!VectorObject_Check(objectA) || !VectorObject_Check(objectB)) {
+ if (comparison_type == Py_NE) {
+ Py_RETURN_TRUE;
+ }
+ else {
+ Py_RETURN_FALSE;
+ }
+ }
+ vecA = (VectorObject *)objectA;
+ vecB = (VectorObject *)objectB;
+
+ if (BaseMath_ReadCallback(vecA) == -1 || BaseMath_ReadCallback(vecB) == -1) {
+ return NULL;
+ }
+
+ if (vecA->size != vecB->size) {
+ if (comparison_type == Py_NE) {
+ Py_RETURN_TRUE;
+ }
+ else {
+ Py_RETURN_FALSE;
+ }
+ }
+
+ switch (comparison_type) {
+ case Py_LT:
+ lenA = len_squared_vn(vecA->vec, vecA->size);
+ lenB = len_squared_vn(vecB->vec, vecB->size);
+ if (lenA < lenB) {
+ result = 1;
+ }
+ break;
+ case Py_LE:
+ lenA = len_squared_vn(vecA->vec, vecA->size);
+ lenB = len_squared_vn(vecB->vec, vecB->size);
+ if (lenA < lenB) {
+ result = 1;
+ }
+ else {
+ result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
+ }
+ break;
+ case Py_EQ:
+ result = EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
+ break;
+ case Py_NE:
+ result = !EXPP_VectorsAreEqual(vecA->vec, vecB->vec, vecA->size, 1);
+ break;
+ case Py_GT:
+ lenA = len_squared_vn(vecA->vec, vecA->size);
+ lenB = len_squared_vn(vecB->vec, vecB->size);
+ if (lenA > lenB) {
+ result = 1;
+ }
+ break;
+ case Py_GE:
+ lenA = len_squared_vn(vecA->vec, vecA->size);
+ lenB = len_squared_vn(vecB->vec, vecB->size);
+ if (lenA > lenB) {
+ result = 1;
+ }
+ else {
+ result = (((lenA + epsilon) > lenB) && ((lenA - epsilon) < lenB));
+ }
+ break;
+ default:
+ printf("The result of the comparison could not be evaluated");
+ break;
+ }
+ if (result == 1) {
+ Py_RETURN_TRUE;
+ }
+ else {
+ Py_RETURN_FALSE;
+ }
}
static Py_hash_t Vector_hash(VectorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return -1;
+ }
- if (BaseMathObject_Prepare_ForHash(self) == -1) {
- return -1;
- }
+ if (BaseMathObject_Prepare_ForHash(self) == -1) {
+ return -1;
+ }
- return mathutils_array_hash(self->vec, self->size);
+ return mathutils_array_hash(self->vec, self->size);
}
/*-----------------PROTCOL DECLARATIONS--------------------------*/
static PySequenceMethods Vector_SeqMethods = {
- (lenfunc) Vector_len, /* sq_length */
- (binaryfunc) NULL, /* sq_concat */
- (ssizeargfunc) NULL, /* 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 */
+ (lenfunc)Vector_len, /* sq_length */
+ (binaryfunc)NULL, /* sq_concat */
+ (ssizeargfunc)NULL, /* 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)
{
- 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 += self->size;
- }
- return Vector_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (step == 1) {
- return Vector_slice(self, start, stop);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with vectors");
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "vector indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ 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 += self->size;
+ }
+ return Vector_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (step == 1) {
+ return Vector_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static int Vector_ass_subscript(VectorObject *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 += self->size;
- }
- return Vector_ass_item(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
- return -1;
- }
-
- if (step == 1) {
- return Vector_ass_slice(self, start, stop, value);
- }
- else {
- PyErr_SetString(PyExc_IndexError,
- "slice steps not supported with vectors");
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "vector indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return -1;
- }
+ 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 += self->size;
+ }
+ return Vector_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx(item, self->size, &start, &stop, &step, &slicelength) < 0) {
+ return -1;
+ }
+
+ if (step == 1) {
+ return Vector_ass_slice(self, start, stop, value);
+ }
+ else {
+ PyErr_SetString(PyExc_IndexError, "slice steps not supported with vectors");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(
+ PyExc_TypeError, "vector indices must be integers, not %.200s", Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
static PyMappingMethods Vector_AsMapping = {
- (lenfunc)Vector_len,
- (binaryfunc)Vector_subscript,
- (objobjargproc)Vector_ass_subscript,
+ (lenfunc)Vector_len,
+ (binaryfunc)Vector_subscript,
+ (objobjargproc)Vector_ass_subscript,
};
-
static PyNumberMethods Vector_NumMethods = {
- (binaryfunc) Vector_add, /*nb_add*/
- (binaryfunc) Vector_sub, /*nb_subtract*/
- (binaryfunc) Vector_mul, /*nb_multiply*/
- NULL, /*nb_remainder*/
- NULL, /*nb_divmod*/
- NULL, /*nb_power*/
- (unaryfunc) Vector_neg, /*nb_negative*/
- (unaryfunc) Vector_copy,/*tp_positive*/
- (unaryfunc) NULL, /*tp_absolute*/
- (inquiry) NULL, /*tp_bool*/
- (unaryfunc) NULL, /*nb_invert*/
- NULL, /*nb_lshift*/
- (binaryfunc)NULL, /*nb_rshift*/
- NULL, /*nb_and*/
- NULL, /*nb_xor*/
- NULL, /*nb_or*/
- NULL, /*nb_int*/
- NULL, /*nb_reserved*/
- NULL, /*nb_float*/
- Vector_iadd, /* nb_inplace_add */
- Vector_isub, /* nb_inplace_subtract */
- Vector_imul, /* nb_inplace_multiply */
- NULL, /* nb_inplace_remainder */
- NULL, /* nb_inplace_power */
- NULL, /* nb_inplace_lshift */
- NULL, /* nb_inplace_rshift */
- NULL, /* nb_inplace_and */
- NULL, /* nb_inplace_xor */
- NULL, /* nb_inplace_or */
- NULL, /* nb_floor_divide */
- Vector_div, /* nb_true_divide */
- NULL, /* nb_inplace_floor_divide */
- Vector_idiv, /* nb_inplace_true_divide */
- NULL, /* nb_index */
- (binaryfunc) Vector_matmul, /* nb_matrix_multiply */
- (binaryfunc) Vector_imatmul, /* nb_inplace_matrix_multiply */
+ (binaryfunc)Vector_add, /*nb_add*/
+ (binaryfunc)Vector_sub, /*nb_subtract*/
+ (binaryfunc)Vector_mul, /*nb_multiply*/
+ NULL, /*nb_remainder*/
+ NULL, /*nb_divmod*/
+ NULL, /*nb_power*/
+ (unaryfunc)Vector_neg, /*nb_negative*/
+ (unaryfunc)Vector_copy, /*tp_positive*/
+ (unaryfunc)NULL, /*tp_absolute*/
+ (inquiry)NULL, /*tp_bool*/
+ (unaryfunc)NULL, /*nb_invert*/
+ NULL, /*nb_lshift*/
+ (binaryfunc)NULL, /*nb_rshift*/
+ NULL, /*nb_and*/
+ NULL, /*nb_xor*/
+ NULL, /*nb_or*/
+ NULL, /*nb_int*/
+ NULL, /*nb_reserved*/
+ NULL, /*nb_float*/
+ Vector_iadd, /* nb_inplace_add */
+ Vector_isub, /* nb_inplace_subtract */
+ Vector_imul, /* nb_inplace_multiply */
+ NULL, /* nb_inplace_remainder */
+ NULL, /* nb_inplace_power */
+ NULL, /* nb_inplace_lshift */
+ NULL, /* nb_inplace_rshift */
+ NULL, /* nb_inplace_and */
+ NULL, /* nb_inplace_xor */
+ NULL, /* nb_inplace_or */
+ NULL, /* nb_floor_divide */
+ Vector_div, /* nb_true_divide */
+ NULL, /* nb_inplace_floor_divide */
+ Vector_idiv, /* nb_inplace_true_divide */
+ NULL, /* nb_index */
+ (binaryfunc)Vector_matmul, /* nb_matrix_multiply */
+ (binaryfunc)Vector_imatmul, /* nb_inplace_matrix_multiply */
};
/*------------------PY_OBECT DEFINITION--------------------------*/
@@ -2292,88 +2268,81 @@ PyDoc_STRVAR(Vector_axis_w_doc, "Vector W axis (4D Vectors only).\n\n:type: floa
static PyObject *Vector_axis_get(VectorObject *self, void *type)
{
- return vector_item_internal(self, POINTER_AS_INT(type), true);
+ return vector_item_internal(self, POINTER_AS_INT(type), true);
}
static int Vector_axis_set(VectorObject *self, PyObject *value, void *type)
{
- return vector_ass_item_internal(self, POINTER_AS_INT(type), value, true);
+ return vector_ass_item_internal(self, POINTER_AS_INT(type), value, true);
}
/* vector.length */
-PyDoc_STRVAR(Vector_length_doc,
-"Vector Length.\n\n:type: float"
-);
+PyDoc_STRVAR(Vector_length_doc, "Vector Length.\n\n:type: float");
static PyObject *Vector_length_get(VectorObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(sqrt(dot_vn_vn(self->vec, self->vec, self->size)));
+ return PyFloat_FromDouble(sqrt(dot_vn_vn(self->vec, self->vec, self->size)));
}
static int Vector_length_set(VectorObject *self, PyObject *value)
{
- double dot = 0.0f, param;
+ double dot = 0.0f, param;
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
- if ((param = PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "length must be set to a number");
- return -1;
- }
+ 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.0) {
- PyErr_SetString(PyExc_ValueError,
- "cannot set a vectors length to a negative value");
- return -1;
- }
- if (param == 0.0) {
- copy_vn_fl(self->vec, self->size, 0.0f);
- return 0;
- }
+ if (param < 0.0) {
+ PyErr_SetString(PyExc_ValueError, "cannot set a vectors length to a negative value");
+ return -1;
+ }
+ if (param == 0.0) {
+ copy_vn_fl(self->vec, self->size, 0.0f);
+ return 0;
+ }
- dot = dot_vn_vn(self->vec, self->vec, self->size);
+ dot = dot_vn_vn(self->vec, self->vec, self->size);
- if (!dot) {
- /* cant sqrt zero */
- return 0;
- }
+ if (!dot) {
+ /* cant sqrt zero */
+ return 0;
+ }
- dot = sqrt(dot);
+ dot = sqrt(dot);
- if (dot == param) {
- return 0;
- }
+ if (dot == param) {
+ return 0;
+ }
- dot = dot / param;
+ dot = dot / param;
- mul_vn_fl(self->vec, self->size, 1.0 / dot);
+ mul_vn_fl(self->vec, self->size, 1.0 / dot);
- (void)BaseMath_WriteCallback(self); /* checked already */
+ (void)BaseMath_WriteCallback(self); /* checked already */
- return 0;
+ return 0;
}
/* vector.length_squared */
-PyDoc_STRVAR(Vector_length_squared_doc,
-"Vector length squared (v.dot(v)).\n\n:type: float"
-);
+PyDoc_STRVAR(Vector_length_squared_doc, "Vector length squared (v.dot(v)).\n\n:type: float");
static PyObject *Vector_length_squared_get(VectorObject *self, void *UNUSED(closure))
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(dot_vn_vn(self->vec, self->vec, self->size));
+ return PyFloat_FromDouble(dot_vn_vn(self->vec, self->vec, self->size));
}
-
/**
* Python script used to make swizzle array:
*
@@ -2434,33 +2403,33 @@ static PyObject *Vector_length_squared_get(VectorObject *self, void *UNUSED(clos
*/
static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
{
- size_t axis_to;
- size_t axis_from;
- float vec[MAX_DIMENSIONS];
- unsigned int swizzleClosure;
+ size_t axis_to;
+ size_t axis_from;
+ float vec[MAX_DIMENSIONS];
+ unsigned int swizzleClosure;
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- /* Unpack the axes from the closure into an array. */
- axis_to = 0;
- swizzleClosure = POINTER_AS_INT(closure);
- while (swizzleClosure & SWIZZLE_VALID_AXIS) {
- axis_from = swizzleClosure & SWIZZLE_AXIS;
- if (axis_from >= self->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector swizzle: "
- "specified axis not present");
- return NULL;
- }
+ /* Unpack the axes from the closure into an array. */
+ axis_to = 0;
+ swizzleClosure = POINTER_AS_INT(closure);
+ while (swizzleClosure & SWIZZLE_VALID_AXIS) {
+ axis_from = swizzleClosure & SWIZZLE_AXIS;
+ if (axis_from >= self->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector swizzle: "
+ "specified axis not present");
+ return NULL;
+ }
- vec[axis_to] = self->vec[axis_from];
- swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- axis_to++;
- }
+ vec[axis_to] = self->vec[axis_from];
+ swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
+ axis_to++;
+ }
- return Vector_CreatePyObject(vec, axis_to, Py_TYPE(self));
+ return Vector_CreatePyObject(vec, axis_to, Py_TYPE(self));
}
/**
@@ -2476,450 +2445,666 @@ static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
*/
static int Vector_swizzle_set(VectorObject *self, PyObject *value, void *closure)
{
- size_t size_from;
- float scalarVal;
-
- size_t axis_from;
- size_t axis_to;
-
- unsigned int swizzleClosure;
-
- float tvec[MAX_DIMENSIONS];
- float vec_assign[MAX_DIMENSIONS];
-
- if (BaseMath_ReadCallback_ForWrite(self) == -1) {
- return -1;
- }
-
- /* 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 = POINTER_AS_INT(closure);
- axis_from = 0;
-
- while (swizzleClosure & SWIZZLE_VALID_AXIS) {
- axis_to = swizzleClosure & SWIZZLE_AXIS;
- if (axis_to >= self->size) {
- PyErr_SetString(PyExc_AttributeError,
- "Vector swizzle: "
- "specified axis not present");
- return -1;
- }
- swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- axis_from++;
- }
-
- if (((scalarVal = PyFloat_AsDouble(value)) == -1 && PyErr_Occurred()) == 0) {
- int i;
-
- for (i = 0; i < MAX_DIMENSIONS; i++) {
- vec_assign[i] = scalarVal;
- }
-
- size_from = axis_from;
- }
- else if (((void)PyErr_Clear()), /* run but ignore the result */
- (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,
- "Vector swizzle: size does not match swizzle");
- return -1;
- }
-
- /* Copy vector contents onto swizzled axes. */
- axis_from = 0;
- swizzleClosure = POINTER_AS_INT(closure);
-
- /* We must first copy current vec into tvec, else some org values may be lost.
- * See [#31760].
- * Assuming self->size can't be higher than MAX_DIMENSIONS! */
- memcpy(tvec, self->vec, self->size * sizeof(float));
-
- 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++;
- }
-
- /* We must copy back the whole tvec into vec, else some changes may be lost (e.g. xz...).
- * See [#31760]. */
- memcpy(self->vec, tvec, self->size * sizeof(float));
- /* continue with BaseMathObject_WriteCallback at the end */
-
- if (BaseMath_WriteCallback(self) == -1) {
- return -1;
- }
- else {
- return 0;
- }
-}
-
-#define _SWIZZLE1(a) ((a) | SWIZZLE_VALID_AXIS)
-#define _SWIZZLE2(a, b) (_SWIZZLE1(a) | (((b) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS)))
-#define _SWIZZLE3(a, b, c) (_SWIZZLE2(a, b) | (((c) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))
-#define _SWIZZLE4(a, b, c, d) (_SWIZZLE3(a, b, c) | (((d) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3)))
-
-#define SWIZZLE2(a, b) POINTER_FROM_INT(_SWIZZLE2(a, b))
-#define SWIZZLE3(a, b, c) POINTER_FROM_INT(_SWIZZLE3(a, b, c))
+ size_t size_from;
+ float scalarVal;
+
+ size_t axis_from;
+ size_t axis_to;
+
+ unsigned int swizzleClosure;
+
+ float tvec[MAX_DIMENSIONS];
+ float vec_assign[MAX_DIMENSIONS];
+
+ if (BaseMath_ReadCallback_ForWrite(self) == -1) {
+ return -1;
+ }
+
+ /* 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 = POINTER_AS_INT(closure);
+ axis_from = 0;
+
+ while (swizzleClosure & SWIZZLE_VALID_AXIS) {
+ axis_to = swizzleClosure & SWIZZLE_AXIS;
+ if (axis_to >= self->size) {
+ PyErr_SetString(PyExc_AttributeError,
+ "Vector swizzle: "
+ "specified axis not present");
+ return -1;
+ }
+ swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
+ axis_from++;
+ }
+
+ if (((scalarVal = PyFloat_AsDouble(value)) == -1 && PyErr_Occurred()) == 0) {
+ int i;
+
+ for (i = 0; i < MAX_DIMENSIONS; i++) {
+ vec_assign[i] = scalarVal;
+ }
+
+ size_from = axis_from;
+ }
+ else if (((void)PyErr_Clear()), /* run but ignore the result */
+ (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, "Vector swizzle: size does not match swizzle");
+ return -1;
+ }
+
+ /* Copy vector contents onto swizzled axes. */
+ axis_from = 0;
+ swizzleClosure = POINTER_AS_INT(closure);
+
+ /* We must first copy current vec into tvec, else some org values may be lost.
+ * See [#31760].
+ * Assuming self->size can't be higher than MAX_DIMENSIONS! */
+ memcpy(tvec, self->vec, self->size * sizeof(float));
+
+ 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++;
+ }
+
+ /* We must copy back the whole tvec into vec, else some changes may be lost (e.g. xz...).
+ * See [#31760]. */
+ memcpy(self->vec, tvec, self->size * sizeof(float));
+ /* continue with BaseMathObject_WriteCallback at the end */
+
+ if (BaseMath_WriteCallback(self) == -1) {
+ return -1;
+ }
+ else {
+ return 0;
+ }
+}
+
+#define _SWIZZLE1(a) ((a) | SWIZZLE_VALID_AXIS)
+#define _SWIZZLE2(a, b) (_SWIZZLE1(a) | (((b) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS)))
+#define _SWIZZLE3(a, b, c) \
+ (_SWIZZLE2(a, b) | (((c) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))
+#define _SWIZZLE4(a, b, c, d) \
+ (_SWIZZLE3(a, b, c) | (((d) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3)))
+
+#define SWIZZLE2(a, b) POINTER_FROM_INT(_SWIZZLE2(a, b))
+#define SWIZZLE3(a, b, c) POINTER_FROM_INT(_SWIZZLE3(a, b, c))
#define SWIZZLE4(a, b, c, d) POINTER_FROM_INT(_SWIZZLE4(a, b, c, d))
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Vector_getseters[] = {
- {(char *)"x", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_x_doc, (void *)0},
- {(char *)"y", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_y_doc, (void *)1},
- {(char *)"z", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_z_doc, (void *)2},
- {(char *)"w", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_w_doc, (void *)3},
- {(char *)"length", (getter)Vector_length_get, (setter)Vector_length_set, Vector_length_doc, NULL},
- {(char *)"length_squared", (getter)Vector_length_squared_get, (setter)NULL, Vector_length_squared_doc, NULL},
- {(char *)"magnitude", (getter)Vector_length_get, (setter)Vector_length_set, Vector_length_doc, NULL},
- {(char *)"is_wrapped", (getter)BaseMathObject_is_wrapped_get, (setter)NULL, BaseMathObject_is_wrapped_doc, NULL},
- {(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
- {(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
-
- /* autogenerated swizzle attrs, see Python script above */
- {(char *)"xx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(0, 0)},
- {(char *)"xxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 0)},
- {(char *)"xxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 0)},
- {(char *)"xxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 1)},
- {(char *)"xxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 2)},
- {(char *)"xxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 3)},
- {(char *)"xxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 1)},
- {(char *)"xxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 0)},
- {(char *)"xxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 1)},
- {(char *)"xxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 2)},
- {(char *)"xxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 3)},
- {(char *)"xxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 2)},
- {(char *)"xxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 0)},
- {(char *)"xxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 1)},
- {(char *)"xxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 2)},
- {(char *)"xxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 3)},
- {(char *)"xxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 3)},
- {(char *)"xxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 0)},
- {(char *)"xxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 1)},
- {(char *)"xxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 2)},
- {(char *)"xxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 3)},
- {(char *)"xy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 1)},
- {(char *)"xyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 0)},
- {(char *)"xyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 0)},
- {(char *)"xyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 1)},
- {(char *)"xyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 2)},
- {(char *)"xyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 3)},
- {(char *)"xyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 1)},
- {(char *)"xyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 0)},
- {(char *)"xyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 1)},
- {(char *)"xyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 2)},
- {(char *)"xyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 3)},
- {(char *)"xyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 2)},
- {(char *)"xyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 0)},
- {(char *)"xyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 1)},
- {(char *)"xyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 2)},
- {(char *)"xyzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 2, 3)},
- {(char *)"xyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 3)},
- {(char *)"xywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 0)},
- {(char *)"xywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 1)},
- {(char *)"xywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 3, 2)},
- {(char *)"xyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 3)},
- {(char *)"xz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 2)},
- {(char *)"xzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 0)},
- {(char *)"xzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 0)},
- {(char *)"xzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 1)},
- {(char *)"xzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 2)},
- {(char *)"xzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 3)},
- {(char *)"xzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 1)},
- {(char *)"xzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 0)},
- {(char *)"xzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 1)},
- {(char *)"xzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 2)},
- {(char *)"xzyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 1, 3)},
- {(char *)"xzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 2)},
- {(char *)"xzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 0)},
- {(char *)"xzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 1)},
- {(char *)"xzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 2)},
- {(char *)"xzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 3)},
- {(char *)"xzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 3)},
- {(char *)"xzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 0)},
- {(char *)"xzwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 3, 1)},
- {(char *)"xzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 2)},
- {(char *)"xzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 3)},
- {(char *)"xw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 3)},
- {(char *)"xwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 0)},
- {(char *)"xwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 0)},
- {(char *)"xwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 1)},
- {(char *)"xwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 2)},
- {(char *)"xwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 3)},
- {(char *)"xwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 1)},
- {(char *)"xwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 0)},
- {(char *)"xwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 1)},
- {(char *)"xwyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 1, 2)},
- {(char *)"xwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 3)},
- {(char *)"xwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 2)},
- {(char *)"xwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 0)},
- {(char *)"xwzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 2, 1)},
- {(char *)"xwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 2)},
- {(char *)"xwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 3)},
- {(char *)"xww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 3)},
- {(char *)"xwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 0)},
- {(char *)"xwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 1)},
- {(char *)"xwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 2)},
- {(char *)"xwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 3)},
- {(char *)"yx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 0)},
- {(char *)"yxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 0)},
- {(char *)"yxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 0)},
- {(char *)"yxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 1)},
- {(char *)"yxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 2)},
- {(char *)"yxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 3)},
- {(char *)"yxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 1)},
- {(char *)"yxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 0)},
- {(char *)"yxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 1)},
- {(char *)"yxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 2)},
- {(char *)"yxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 3)},
- {(char *)"yxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 2)},
- {(char *)"yxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 0)},
- {(char *)"yxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 1)},
- {(char *)"yxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 2)},
- {(char *)"yxzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 2, 3)},
- {(char *)"yxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 3)},
- {(char *)"yxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 0)},
- {(char *)"yxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 1)},
- {(char *)"yxwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 3, 2)},
- {(char *)"yxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 3)},
- {(char *)"yy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(1, 1)},
- {(char *)"yyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 0)},
- {(char *)"yyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 0)},
- {(char *)"yyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 1)},
- {(char *)"yyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 2)},
- {(char *)"yyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 3)},
- {(char *)"yyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 1)},
- {(char *)"yyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 0)},
- {(char *)"yyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 1)},
- {(char *)"yyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 2)},
- {(char *)"yyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 3)},
- {(char *)"yyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 2)},
- {(char *)"yyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 0)},
- {(char *)"yyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 1)},
- {(char *)"yyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 2)},
- {(char *)"yyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 3)},
- {(char *)"yyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 3)},
- {(char *)"yywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 0)},
- {(char *)"yywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 1)},
- {(char *)"yywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 2)},
- {(char *)"yyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 3)},
- {(char *)"yz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 2)},
- {(char *)"yzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 0)},
- {(char *)"yzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 0)},
- {(char *)"yzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 1)},
- {(char *)"yzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 2)},
- {(char *)"yzxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 0, 3)},
- {(char *)"yzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 1)},
- {(char *)"yzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 0)},
- {(char *)"yzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 1)},
- {(char *)"yzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 2)},
- {(char *)"yzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 3)},
- {(char *)"yzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 2)},
- {(char *)"yzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 0)},
- {(char *)"yzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 1)},
- {(char *)"yzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 2)},
- {(char *)"yzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 3)},
- {(char *)"yzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 3)},
- {(char *)"yzwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 3, 0)},
- {(char *)"yzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 1)},
- {(char *)"yzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 2)},
- {(char *)"yzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 3)},
- {(char *)"yw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 3)},
- {(char *)"ywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 0)},
- {(char *)"ywxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 0)},
- {(char *)"ywxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 1)},
- {(char *)"ywxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 0, 2)},
- {(char *)"ywxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 3)},
- {(char *)"ywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 1)},
- {(char *)"ywyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 0)},
- {(char *)"ywyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 1)},
- {(char *)"ywyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 2)},
- {(char *)"ywyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 3)},
- {(char *)"ywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 2)},
- {(char *)"ywzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 2, 0)},
- {(char *)"ywzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 1)},
- {(char *)"ywzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 2)},
- {(char *)"ywzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 3)},
- {(char *)"yww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 3)},
- {(char *)"ywwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 0)},
- {(char *)"ywwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 1)},
- {(char *)"ywwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 2)},
- {(char *)"ywww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 3)},
- {(char *)"zx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 0)},
- {(char *)"zxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 0)},
- {(char *)"zxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 0)},
- {(char *)"zxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 1)},
- {(char *)"zxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 2)},
- {(char *)"zxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 3)},
- {(char *)"zxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 1)},
- {(char *)"zxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 0)},
- {(char *)"zxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 1)},
- {(char *)"zxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 2)},
- {(char *)"zxyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 1, 3)},
- {(char *)"zxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 2)},
- {(char *)"zxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 0)},
- {(char *)"zxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 1)},
- {(char *)"zxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 2)},
- {(char *)"zxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 3)},
- {(char *)"zxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 3)},
- {(char *)"zxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 0)},
- {(char *)"zxwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 3, 1)},
- {(char *)"zxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 2)},
- {(char *)"zxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 3)},
- {(char *)"zy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 1)},
- {(char *)"zyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 0)},
- {(char *)"zyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 0)},
- {(char *)"zyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 1)},
- {(char *)"zyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 2)},
- {(char *)"zyxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 0, 3)},
- {(char *)"zyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 1)},
- {(char *)"zyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 0)},
- {(char *)"zyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 1)},
- {(char *)"zyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 2)},
- {(char *)"zyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 3)},
- {(char *)"zyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 2)},
- {(char *)"zyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 0)},
- {(char *)"zyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 1)},
- {(char *)"zyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 2)},
- {(char *)"zyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 3)},
- {(char *)"zyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 3)},
- {(char *)"zywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 3, 0)},
- {(char *)"zywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 1)},
- {(char *)"zywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 2)},
- {(char *)"zyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 3)},
- {(char *)"zz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(2, 2)},
- {(char *)"zzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 0)},
- {(char *)"zzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 0)},
- {(char *)"zzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 1)},
- {(char *)"zzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 2)},
- {(char *)"zzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 3)},
- {(char *)"zzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 1)},
- {(char *)"zzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 0)},
- {(char *)"zzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 1)},
- {(char *)"zzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 2)},
- {(char *)"zzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 3)},
- {(char *)"zzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 2)},
- {(char *)"zzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 0)},
- {(char *)"zzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 1)},
- {(char *)"zzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 2)},
- {(char *)"zzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 3)},
- {(char *)"zzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 3)},
- {(char *)"zzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 0)},
- {(char *)"zzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 1)},
- {(char *)"zzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 2)},
- {(char *)"zzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 3)},
- {(char *)"zw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 3)},
- {(char *)"zwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 0)},
- {(char *)"zwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 0)},
- {(char *)"zwxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 0, 1)},
- {(char *)"zwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 2)},
- {(char *)"zwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 3)},
- {(char *)"zwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 1)},
- {(char *)"zwyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 1, 0)},
- {(char *)"zwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 1)},
- {(char *)"zwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 2)},
- {(char *)"zwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 3)},
- {(char *)"zwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 2)},
- {(char *)"zwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 0)},
- {(char *)"zwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 1)},
- {(char *)"zwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 2)},
- {(char *)"zwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 3)},
- {(char *)"zww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 3)},
- {(char *)"zwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 0)},
- {(char *)"zwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 1)},
- {(char *)"zwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 2)},
- {(char *)"zwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 3)},
- {(char *)"wx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 0)},
- {(char *)"wxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 0)},
- {(char *)"wxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 0)},
- {(char *)"wxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 1)},
- {(char *)"wxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 2)},
- {(char *)"wxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 3)},
- {(char *)"wxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 1)},
- {(char *)"wxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 0)},
- {(char *)"wxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 1)},
- {(char *)"wxyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 1, 2)},
- {(char *)"wxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 3)},
- {(char *)"wxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 2)},
- {(char *)"wxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 0)},
- {(char *)"wxzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 2, 1)},
- {(char *)"wxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 2)},
- {(char *)"wxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 3)},
- {(char *)"wxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 3)},
- {(char *)"wxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 0)},
- {(char *)"wxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 1)},
- {(char *)"wxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 2)},
- {(char *)"wxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 3)},
- {(char *)"wy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 1)},
- {(char *)"wyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 0)},
- {(char *)"wyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 0)},
- {(char *)"wyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 1)},
- {(char *)"wyxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 0, 2)},
- {(char *)"wyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 3)},
- {(char *)"wyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 1)},
- {(char *)"wyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 0)},
- {(char *)"wyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 1)},
- {(char *)"wyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 2)},
- {(char *)"wyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 3)},
- {(char *)"wyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 2)},
- {(char *)"wyzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 2, 0)},
- {(char *)"wyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 1)},
- {(char *)"wyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 2)},
- {(char *)"wyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 3)},
- {(char *)"wyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 3)},
- {(char *)"wywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 0)},
- {(char *)"wywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 1)},
- {(char *)"wywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 2)},
- {(char *)"wyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 3)},
- {(char *)"wz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 2)},
- {(char *)"wzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 0)},
- {(char *)"wzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 0)},
- {(char *)"wzxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 0, 1)},
- {(char *)"wzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 2)},
- {(char *)"wzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 3)},
- {(char *)"wzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 1)},
- {(char *)"wzyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 1, 0)},
- {(char *)"wzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 1)},
- {(char *)"wzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 2)},
- {(char *)"wzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 3)},
- {(char *)"wzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 2)},
- {(char *)"wzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 0)},
- {(char *)"wzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 1)},
- {(char *)"wzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 2)},
- {(char *)"wzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 3)},
- {(char *)"wzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 3)},
- {(char *)"wzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 0)},
- {(char *)"wzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 1)},
- {(char *)"wzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 2)},
- {(char *)"wzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 3)},
- {(char *)"ww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(3, 3)},
- {(char *)"wwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 0)},
- {(char *)"wwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 0)},
- {(char *)"wwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 1)},
- {(char *)"wwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 2)},
- {(char *)"wwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 3)},
- {(char *)"wwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 1)},
- {(char *)"wwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 0)},
- {(char *)"wwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 1)},
- {(char *)"wwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 2)},
- {(char *)"wwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 3)},
- {(char *)"wwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 2)},
- {(char *)"wwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 0)},
- {(char *)"wwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 1)},
- {(char *)"wwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 2)},
- {(char *)"wwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 3)},
- {(char *)"www", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 3)},
- {(char *)"wwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 0)},
- {(char *)"wwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 1)},
- {(char *)"wwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 2)},
- {(char *)"wwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 3)},
+ {(char *)"x", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_x_doc, (void *)0},
+ {(char *)"y", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_y_doc, (void *)1},
+ {(char *)"z", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_z_doc, (void *)2},
+ {(char *)"w", (getter)Vector_axis_get, (setter)Vector_axis_set, Vector_axis_w_doc, (void *)3},
+ {(char *)"length",
+ (getter)Vector_length_get,
+ (setter)Vector_length_set,
+ Vector_length_doc,
+ NULL},
+ {(char *)"length_squared",
+ (getter)Vector_length_squared_get,
+ (setter)NULL,
+ Vector_length_squared_doc,
+ NULL},
+ {(char *)"magnitude",
+ (getter)Vector_length_get,
+ (setter)Vector_length_set,
+ Vector_length_doc,
+ NULL},
+ {(char *)"is_wrapped",
+ (getter)BaseMathObject_is_wrapped_get,
+ (setter)NULL,
+ BaseMathObject_is_wrapped_doc,
+ NULL},
+ {(char *)"is_frozen",
+ (getter)BaseMathObject_is_frozen_get,
+ (setter)NULL,
+ BaseMathObject_is_frozen_doc,
+ NULL},
+ {(char *)"owner",
+ (getter)BaseMathObject_owner_get,
+ (setter)NULL,
+ BaseMathObject_owner_doc,
+ NULL},
+
+ /* autogenerated swizzle attrs, see Python script above */
+ {(char *)"xx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(0, 0)},
+ {(char *)"xxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 0)},
+ {(char *)"xxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 0)},
+ {(char *)"xxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 1)},
+ {(char *)"xxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 2)},
+ {(char *)"xxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 3)},
+ {(char *)"xxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 1)},
+ {(char *)"xxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 0)},
+ {(char *)"xxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 1)},
+ {(char *)"xxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 2)},
+ {(char *)"xxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 3)},
+ {(char *)"xxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 2)},
+ {(char *)"xxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 0)},
+ {(char *)"xxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 1)},
+ {(char *)"xxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 2)},
+ {(char *)"xxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 3)},
+ {(char *)"xxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 3)},
+ {(char *)"xxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 0)},
+ {(char *)"xxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 1)},
+ {(char *)"xxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 2)},
+ {(char *)"xxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 3)},
+ {(char *)"xy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 1)},
+ {(char *)"xyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 0)},
+ {(char *)"xyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 0)},
+ {(char *)"xyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 1)},
+ {(char *)"xyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 2)},
+ {(char *)"xyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 3)},
+ {(char *)"xyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 1)},
+ {(char *)"xyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 0)},
+ {(char *)"xyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 1)},
+ {(char *)"xyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 2)},
+ {(char *)"xyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 3)},
+ {(char *)"xyz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 1, 2)},
+ {(char *)"xyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 0)},
+ {(char *)"xyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 1)},
+ {(char *)"xyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 2)},
+ {(char *)"xyzw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 1, 2, 3)},
+ {(char *)"xyw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 1, 3)},
+ {(char *)"xywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 0)},
+ {(char *)"xywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 1)},
+ {(char *)"xywz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 1, 3, 2)},
+ {(char *)"xyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 3)},
+ {(char *)"xz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 2)},
+ {(char *)"xzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 0)},
+ {(char *)"xzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 0)},
+ {(char *)"xzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 1)},
+ {(char *)"xzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 2)},
+ {(char *)"xzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 3)},
+ {(char *)"xzy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 2, 1)},
+ {(char *)"xzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 0)},
+ {(char *)"xzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 1)},
+ {(char *)"xzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 2)},
+ {(char *)"xzyw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 2, 1, 3)},
+ {(char *)"xzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 2)},
+ {(char *)"xzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 0)},
+ {(char *)"xzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 1)},
+ {(char *)"xzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 2)},
+ {(char *)"xzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 3)},
+ {(char *)"xzw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 2, 3)},
+ {(char *)"xzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 0)},
+ {(char *)"xzwy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 2, 3, 1)},
+ {(char *)"xzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 2)},
+ {(char *)"xzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 3)},
+ {(char *)"xw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 3)},
+ {(char *)"xwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 0)},
+ {(char *)"xwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 0)},
+ {(char *)"xwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 1)},
+ {(char *)"xwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 2)},
+ {(char *)"xwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 3)},
+ {(char *)"xwy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 3, 1)},
+ {(char *)"xwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 0)},
+ {(char *)"xwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 1)},
+ {(char *)"xwyz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 3, 1, 2)},
+ {(char *)"xwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 3)},
+ {(char *)"xwz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(0, 3, 2)},
+ {(char *)"xwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 0)},
+ {(char *)"xwzy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(0, 3, 2, 1)},
+ {(char *)"xwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 2)},
+ {(char *)"xwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 3)},
+ {(char *)"xww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 3)},
+ {(char *)"xwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 0)},
+ {(char *)"xwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 1)},
+ {(char *)"xwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 2)},
+ {(char *)"xwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 3)},
+ {(char *)"yx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 0)},
+ {(char *)"yxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 0)},
+ {(char *)"yxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 0)},
+ {(char *)"yxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 1)},
+ {(char *)"yxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 2)},
+ {(char *)"yxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 3)},
+ {(char *)"yxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 1)},
+ {(char *)"yxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 0)},
+ {(char *)"yxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 1)},
+ {(char *)"yxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 2)},
+ {(char *)"yxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 3)},
+ {(char *)"yxz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 0, 2)},
+ {(char *)"yxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 0)},
+ {(char *)"yxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 1)},
+ {(char *)"yxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 2)},
+ {(char *)"yxzw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 0, 2, 3)},
+ {(char *)"yxw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 0, 3)},
+ {(char *)"yxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 0)},
+ {(char *)"yxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 1)},
+ {(char *)"yxwz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 0, 3, 2)},
+ {(char *)"yxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 3)},
+ {(char *)"yy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(1, 1)},
+ {(char *)"yyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 0)},
+ {(char *)"yyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 0)},
+ {(char *)"yyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 1)},
+ {(char *)"yyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 2)},
+ {(char *)"yyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 3)},
+ {(char *)"yyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 1)},
+ {(char *)"yyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 0)},
+ {(char *)"yyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 1)},
+ {(char *)"yyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 2)},
+ {(char *)"yyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 3)},
+ {(char *)"yyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 2)},
+ {(char *)"yyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 0)},
+ {(char *)"yyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 1)},
+ {(char *)"yyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 2)},
+ {(char *)"yyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 3)},
+ {(char *)"yyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 3)},
+ {(char *)"yywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 0)},
+ {(char *)"yywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 1)},
+ {(char *)"yywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 2)},
+ {(char *)"yyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 3)},
+ {(char *)"yz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 2)},
+ {(char *)"yzx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 2, 0)},
+ {(char *)"yzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 0)},
+ {(char *)"yzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 1)},
+ {(char *)"yzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 2)},
+ {(char *)"yzxw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 2, 0, 3)},
+ {(char *)"yzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 1)},
+ {(char *)"yzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 0)},
+ {(char *)"yzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 1)},
+ {(char *)"yzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 2)},
+ {(char *)"yzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 3)},
+ {(char *)"yzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 2)},
+ {(char *)"yzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 0)},
+ {(char *)"yzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 1)},
+ {(char *)"yzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 2)},
+ {(char *)"yzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 3)},
+ {(char *)"yzw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 2, 3)},
+ {(char *)"yzwx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 2, 3, 0)},
+ {(char *)"yzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 1)},
+ {(char *)"yzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 2)},
+ {(char *)"yzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 3)},
+ {(char *)"yw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 3)},
+ {(char *)"ywx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 3, 0)},
+ {(char *)"ywxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 0)},
+ {(char *)"ywxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 1)},
+ {(char *)"ywxz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 3, 0, 2)},
+ {(char *)"ywxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 3)},
+ {(char *)"ywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 1)},
+ {(char *)"ywyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 0)},
+ {(char *)"ywyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 1)},
+ {(char *)"ywyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 2)},
+ {(char *)"ywyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 3)},
+ {(char *)"ywz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(1, 3, 2)},
+ {(char *)"ywzx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(1, 3, 2, 0)},
+ {(char *)"ywzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 1)},
+ {(char *)"ywzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 2)},
+ {(char *)"ywzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 3)},
+ {(char *)"yww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 3)},
+ {(char *)"ywwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 0)},
+ {(char *)"ywwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 1)},
+ {(char *)"ywwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 2)},
+ {(char *)"ywww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 3)},
+ {(char *)"zx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 0)},
+ {(char *)"zxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 0)},
+ {(char *)"zxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 0)},
+ {(char *)"zxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 1)},
+ {(char *)"zxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 2)},
+ {(char *)"zxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 3)},
+ {(char *)"zxy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 0, 1)},
+ {(char *)"zxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 0)},
+ {(char *)"zxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 1)},
+ {(char *)"zxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 2)},
+ {(char *)"zxyw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 0, 1, 3)},
+ {(char *)"zxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 2)},
+ {(char *)"zxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 0)},
+ {(char *)"zxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 1)},
+ {(char *)"zxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 2)},
+ {(char *)"zxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 3)},
+ {(char *)"zxw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 0, 3)},
+ {(char *)"zxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 0)},
+ {(char *)"zxwy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 0, 3, 1)},
+ {(char *)"zxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 2)},
+ {(char *)"zxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 3)},
+ {(char *)"zy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 1)},
+ {(char *)"zyx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 1, 0)},
+ {(char *)"zyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 0)},
+ {(char *)"zyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 1)},
+ {(char *)"zyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 2)},
+ {(char *)"zyxw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 1, 0, 3)},
+ {(char *)"zyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 1)},
+ {(char *)"zyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 0)},
+ {(char *)"zyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 1)},
+ {(char *)"zyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 2)},
+ {(char *)"zyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 3)},
+ {(char *)"zyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 2)},
+ {(char *)"zyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 0)},
+ {(char *)"zyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 1)},
+ {(char *)"zyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 2)},
+ {(char *)"zyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 3)},
+ {(char *)"zyw",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 1, 3)},
+ {(char *)"zywx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 1, 3, 0)},
+ {(char *)"zywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 1)},
+ {(char *)"zywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 2)},
+ {(char *)"zyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 3)},
+ {(char *)"zz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(2, 2)},
+ {(char *)"zzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 0)},
+ {(char *)"zzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 0)},
+ {(char *)"zzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 1)},
+ {(char *)"zzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 2)},
+ {(char *)"zzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 3)},
+ {(char *)"zzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 1)},
+ {(char *)"zzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 0)},
+ {(char *)"zzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 1)},
+ {(char *)"zzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 2)},
+ {(char *)"zzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 3)},
+ {(char *)"zzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 2)},
+ {(char *)"zzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 0)},
+ {(char *)"zzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 1)},
+ {(char *)"zzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 2)},
+ {(char *)"zzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 3)},
+ {(char *)"zzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 3)},
+ {(char *)"zzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 0)},
+ {(char *)"zzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 1)},
+ {(char *)"zzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 2)},
+ {(char *)"zzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 3)},
+ {(char *)"zw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 3)},
+ {(char *)"zwx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 3, 0)},
+ {(char *)"zwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 0)},
+ {(char *)"zwxy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 3, 0, 1)},
+ {(char *)"zwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 2)},
+ {(char *)"zwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 3)},
+ {(char *)"zwy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(2, 3, 1)},
+ {(char *)"zwyx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(2, 3, 1, 0)},
+ {(char *)"zwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 1)},
+ {(char *)"zwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 2)},
+ {(char *)"zwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 3)},
+ {(char *)"zwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 2)},
+ {(char *)"zwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 0)},
+ {(char *)"zwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 1)},
+ {(char *)"zwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 2)},
+ {(char *)"zwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 3)},
+ {(char *)"zww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 3)},
+ {(char *)"zwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 0)},
+ {(char *)"zwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 1)},
+ {(char *)"zwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 2)},
+ {(char *)"zwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 3)},
+ {(char *)"wx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 0)},
+ {(char *)"wxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 0)},
+ {(char *)"wxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 0)},
+ {(char *)"wxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 1)},
+ {(char *)"wxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 2)},
+ {(char *)"wxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 3)},
+ {(char *)"wxy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 0, 1)},
+ {(char *)"wxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 0)},
+ {(char *)"wxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 1)},
+ {(char *)"wxyz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 0, 1, 2)},
+ {(char *)"wxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 3)},
+ {(char *)"wxz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 0, 2)},
+ {(char *)"wxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 0)},
+ {(char *)"wxzy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 0, 2, 1)},
+ {(char *)"wxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 2)},
+ {(char *)"wxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 3)},
+ {(char *)"wxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 3)},
+ {(char *)"wxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 0)},
+ {(char *)"wxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 1)},
+ {(char *)"wxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 2)},
+ {(char *)"wxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 3)},
+ {(char *)"wy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 1)},
+ {(char *)"wyx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 1, 0)},
+ {(char *)"wyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 0)},
+ {(char *)"wyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 1)},
+ {(char *)"wyxz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 1, 0, 2)},
+ {(char *)"wyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 3)},
+ {(char *)"wyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 1)},
+ {(char *)"wyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 0)},
+ {(char *)"wyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 1)},
+ {(char *)"wyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 2)},
+ {(char *)"wyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 3)},
+ {(char *)"wyz",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 1, 2)},
+ {(char *)"wyzx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 1, 2, 0)},
+ {(char *)"wyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 1)},
+ {(char *)"wyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 2)},
+ {(char *)"wyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 3)},
+ {(char *)"wyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 3)},
+ {(char *)"wywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 0)},
+ {(char *)"wywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 1)},
+ {(char *)"wywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 2)},
+ {(char *)"wyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 3)},
+ {(char *)"wz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 2)},
+ {(char *)"wzx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 2, 0)},
+ {(char *)"wzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 0)},
+ {(char *)"wzxy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 2, 0, 1)},
+ {(char *)"wzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 2)},
+ {(char *)"wzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 3)},
+ {(char *)"wzy",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE3(3, 2, 1)},
+ {(char *)"wzyx",
+ (getter)Vector_swizzle_get,
+ (setter)Vector_swizzle_set,
+ NULL,
+ SWIZZLE4(3, 2, 1, 0)},
+ {(char *)"wzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 1)},
+ {(char *)"wzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 2)},
+ {(char *)"wzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 3)},
+ {(char *)"wzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 2)},
+ {(char *)"wzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 0)},
+ {(char *)"wzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 1)},
+ {(char *)"wzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 2)},
+ {(char *)"wzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 3)},
+ {(char *)"wzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 3)},
+ {(char *)"wzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 0)},
+ {(char *)"wzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 1)},
+ {(char *)"wzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 2)},
+ {(char *)"wzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 3)},
+ {(char *)"ww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(3, 3)},
+ {(char *)"wwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 0)},
+ {(char *)"wwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 0)},
+ {(char *)"wwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 1)},
+ {(char *)"wwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 2)},
+ {(char *)"wwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 3)},
+ {(char *)"wwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 1)},
+ {(char *)"wwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 0)},
+ {(char *)"wwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 1)},
+ {(char *)"wwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 2)},
+ {(char *)"wwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 3)},
+ {(char *)"wwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 2)},
+ {(char *)"wwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 0)},
+ {(char *)"wwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 1)},
+ {(char *)"wwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 2)},
+ {(char *)"wwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 3)},
+ {(char *)"www", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 3)},
+ {(char *)"wwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 0)},
+ {(char *)"wwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 1)},
+ {(char *)"wwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 2)},
+ {(char *)"wwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 3)},
#undef AXIS_FROM_CHAR
#undef SWIZZLE1
@@ -2931,7 +3116,7 @@ static PyGetSetDef Vector_getseters[] = {
#undef _SWIZZLE3
#undef _SWIZZLE4
- {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
+ {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/**
@@ -2943,108 +3128,111 @@ static PyGetSetDef Vector_getseters[] = {
* </pre>
* \note vector/matrix multiplication is not commutative.
*/
-static int row_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat)
-{
- float vec_cpy[MAX_DIMENSIONS];
- int row, col, z = 0, vec_size = vec->size;
-
- if (mat->num_row != vec_size) {
- if (mat->num_row == 4 && vec_size == 3) {
- vec_cpy[3] = 1.0f;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "vector * matrix: matrix column size "
- "and the vector size must be the same");
- return -1;
- }
- }
-
- if (BaseMath_ReadCallback(vec) == -1 || BaseMath_ReadCallback(mat) == -1) {
- return -1;
- }
-
- memcpy(vec_cpy, vec->vec, vec_size * sizeof(float));
-
- r_vec[3] = 1.0f;
- /* muliplication */
- for (col = 0; col < mat->num_col; col++) {
- double dot = 0.0;
- for (row = 0; row < mat->num_row; row++) {
- dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[row]);
- }
- r_vec[z++] = (float)dot;
- }
- return 0;
+static int row_vector_multiplication(float r_vec[MAX_DIMENSIONS],
+ VectorObject *vec,
+ MatrixObject *mat)
+{
+ float vec_cpy[MAX_DIMENSIONS];
+ int row, col, z = 0, vec_size = vec->size;
+
+ if (mat->num_row != vec_size) {
+ if (mat->num_row == 4 && vec_size == 3) {
+ vec_cpy[3] = 1.0f;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "vector * matrix: matrix column size "
+ "and the vector size must be the same");
+ return -1;
+ }
+ }
+
+ if (BaseMath_ReadCallback(vec) == -1 || BaseMath_ReadCallback(mat) == -1) {
+ return -1;
+ }
+
+ memcpy(vec_cpy, vec->vec, vec_size * sizeof(float));
+
+ r_vec[3] = 1.0f;
+ /* muliplication */
+ for (col = 0; col < mat->num_col; col++) {
+ double dot = 0.0;
+ for (row = 0; row < mat->num_row; row++) {
+ dot += (double)(MATRIX_ITEM(mat, row, col) * vec_cpy[row]);
+ }
+ r_vec[z++] = (float)dot;
+ }
+ return 0;
}
/*----------------------------Vector.negate() -------------------- */
PyDoc_STRVAR(Vector_negate_doc,
-".. method:: negate()\n"
-"\n"
-" Set all values to their negative.\n"
-);
+ ".. method:: negate()\n"
+ "\n"
+ " Set all values to their negative.\n");
static PyObject *Vector_negate(VectorObject *self)
{
- if (BaseMath_ReadCallback(self) == -1) {
- return NULL;
- }
+ if (BaseMath_ReadCallback(self) == -1) {
+ return NULL;
+ }
- negate_vn(self->vec, self->size);
+ negate_vn(self->vec, self->size);
- (void)BaseMath_WriteCallback(self); /* already checked for error */
- Py_RETURN_NONE;
+ (void)BaseMath_WriteCallback(self); /* already checked for error */
+ Py_RETURN_NONE;
}
static struct PyMethodDef Vector_methods[] = {
- /* Class Methods */
- {"Fill", (PyCFunction) C_Vector_Fill, METH_VARARGS | METH_CLASS, C_Vector_Fill_doc},
- {"Range", (PyCFunction) C_Vector_Range, METH_VARARGS | METH_CLASS, C_Vector_Range_doc},
- {"Linspace", (PyCFunction) C_Vector_Linspace, METH_VARARGS | METH_CLASS, C_Vector_Linspace_doc},
- {"Repeat", (PyCFunction) C_Vector_Repeat, METH_VARARGS | METH_CLASS, C_Vector_Repeat_doc},
-
- /* in place only */
- {"zero", (PyCFunction) Vector_zero, METH_NOARGS, Vector_zero_doc},
- {"negate", (PyCFunction) Vector_negate, METH_NOARGS, Vector_negate_doc},
-
- /* operate on original or copy */
- {"normalize", (PyCFunction) Vector_normalize, METH_NOARGS, Vector_normalize_doc},
- {"normalized", (PyCFunction) Vector_normalized, METH_NOARGS, Vector_normalized_doc},
-
- {"resize", (PyCFunction) Vector_resize, METH_O, Vector_resize_doc},
- {"resized", (PyCFunction) Vector_resized, METH_O, Vector_resized_doc},
- {"to_2d", (PyCFunction) Vector_to_2d, METH_NOARGS, Vector_to_2d_doc},
- {"resize_2d", (PyCFunction) Vector_resize_2d, METH_NOARGS, Vector_resize_2d_doc},
- {"to_3d", (PyCFunction) Vector_to_3d, METH_NOARGS, Vector_to_3d_doc},
- {"resize_3d", (PyCFunction) Vector_resize_3d, METH_NOARGS, Vector_resize_3d_doc},
- {"to_4d", (PyCFunction) Vector_to_4d, METH_NOARGS, Vector_to_4d_doc},
- {"resize_4d", (PyCFunction) Vector_resize_4d, METH_NOARGS, Vector_resize_4d_doc},
- {"to_tuple", (PyCFunction) Vector_to_tuple, METH_VARARGS, Vector_to_tuple_doc},
- {"to_track_quat", (PyCFunction) Vector_to_track_quat, METH_VARARGS, Vector_to_track_quat_doc},
- {"orthogonal", (PyCFunction) Vector_orthogonal, METH_NOARGS, Vector_orthogonal_doc},
-
- /* operation between 2 or more types */
- {"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_VARARGS, Vector_angle_doc},
- {"angle_signed", (PyCFunction) Vector_angle_signed, METH_VARARGS, Vector_angle_signed_doc},
- {"rotation_difference", (PyCFunction) Vector_rotation_difference, METH_O, Vector_rotation_difference_doc},
- {"project", (PyCFunction) Vector_project, METH_O, Vector_project_doc},
- {"lerp", (PyCFunction) Vector_lerp, METH_VARARGS, Vector_lerp_doc},
- {"slerp", (PyCFunction) Vector_slerp, METH_VARARGS, Vector_slerp_doc},
- {"rotate", (PyCFunction) Vector_rotate, METH_O, Vector_rotate_doc},
-
- /* base-math methods */
- {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
-
- {"copy", (PyCFunction) Vector_copy, METH_NOARGS, Vector_copy_doc},
- {"__copy__", (PyCFunction) Vector_copy, METH_NOARGS, NULL},
- {"__deepcopy__", (PyCFunction) Vector_deepcopy, METH_VARARGS, NULL},
- {NULL, NULL, 0, NULL},
+ /* Class Methods */
+ {"Fill", (PyCFunction)C_Vector_Fill, METH_VARARGS | METH_CLASS, C_Vector_Fill_doc},
+ {"Range", (PyCFunction)C_Vector_Range, METH_VARARGS | METH_CLASS, C_Vector_Range_doc},
+ {"Linspace", (PyCFunction)C_Vector_Linspace, METH_VARARGS | METH_CLASS, C_Vector_Linspace_doc},
+ {"Repeat", (PyCFunction)C_Vector_Repeat, METH_VARARGS | METH_CLASS, C_Vector_Repeat_doc},
+
+ /* in place only */
+ {"zero", (PyCFunction)Vector_zero, METH_NOARGS, Vector_zero_doc},
+ {"negate", (PyCFunction)Vector_negate, METH_NOARGS, Vector_negate_doc},
+
+ /* operate on original or copy */
+ {"normalize", (PyCFunction)Vector_normalize, METH_NOARGS, Vector_normalize_doc},
+ {"normalized", (PyCFunction)Vector_normalized, METH_NOARGS, Vector_normalized_doc},
+
+ {"resize", (PyCFunction)Vector_resize, METH_O, Vector_resize_doc},
+ {"resized", (PyCFunction)Vector_resized, METH_O, Vector_resized_doc},
+ {"to_2d", (PyCFunction)Vector_to_2d, METH_NOARGS, Vector_to_2d_doc},
+ {"resize_2d", (PyCFunction)Vector_resize_2d, METH_NOARGS, Vector_resize_2d_doc},
+ {"to_3d", (PyCFunction)Vector_to_3d, METH_NOARGS, Vector_to_3d_doc},
+ {"resize_3d", (PyCFunction)Vector_resize_3d, METH_NOARGS, Vector_resize_3d_doc},
+ {"to_4d", (PyCFunction)Vector_to_4d, METH_NOARGS, Vector_to_4d_doc},
+ {"resize_4d", (PyCFunction)Vector_resize_4d, METH_NOARGS, Vector_resize_4d_doc},
+ {"to_tuple", (PyCFunction)Vector_to_tuple, METH_VARARGS, Vector_to_tuple_doc},
+ {"to_track_quat", (PyCFunction)Vector_to_track_quat, METH_VARARGS, Vector_to_track_quat_doc},
+ {"orthogonal", (PyCFunction)Vector_orthogonal, METH_NOARGS, Vector_orthogonal_doc},
+
+ /* operation between 2 or more types */
+ {"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_VARARGS, Vector_angle_doc},
+ {"angle_signed", (PyCFunction)Vector_angle_signed, METH_VARARGS, Vector_angle_signed_doc},
+ {"rotation_difference",
+ (PyCFunction)Vector_rotation_difference,
+ METH_O,
+ Vector_rotation_difference_doc},
+ {"project", (PyCFunction)Vector_project, METH_O, Vector_project_doc},
+ {"lerp", (PyCFunction)Vector_lerp, METH_VARARGS, Vector_lerp_doc},
+ {"slerp", (PyCFunction)Vector_slerp, METH_VARARGS, Vector_slerp_doc},
+ {"rotate", (PyCFunction)Vector_rotate, METH_O, Vector_rotate_doc},
+
+ /* base-math methods */
+ {"freeze", (PyCFunction)BaseMathObject_freeze, METH_NOARGS, BaseMathObject_freeze_doc},
+
+ {"copy", (PyCFunction)Vector_copy, METH_NOARGS, Vector_copy_doc},
+ {"__copy__", (PyCFunction)Vector_copy, METH_NOARGS, NULL},
+ {"__deepcopy__", (PyCFunction)Vector_deepcopy, METH_VARARGS, NULL},
+ {NULL, NULL, 0, NULL},
};
-
/**
* Note:
* #Py_TPFLAGS_CHECKTYPES allows us to avoid casting all types to Vector when coercing
@@ -3053,144 +3241,140 @@ static struct PyMethodDef Vector_methods[] = {
*/
PyDoc_STRVAR(vector_doc,
-".. class:: Vector(seq)\n"
-"\n"
-" This object gives access to Vectors in Blender.\n"
-"\n"
-" :param seq: Components of the vector, must be a sequence of at least two\n"
-" :type seq: sequence of numbers\n"
-);
+ ".. class:: Vector(seq)\n"
+ "\n"
+ " This object gives access to Vectors in Blender.\n"
+ "\n"
+ " :param seq: Components of the vector, must be a sequence of at least two\n"
+ " :type seq: sequence of numbers\n");
PyTypeObject vector_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* For printing, in format "<module>.<name>" */
- "Vector", /* char *tp_name; */
- sizeof(VectorObject), /* int tp_basicsize; */
- 0, /* tp_itemsize; For allocation */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* For printing, in format "<module>.<name>" */
+ "Vector", /* char *tp_name; */
+ sizeof(VectorObject), /* int tp_basicsize; */
+ 0, /* tp_itemsize; For allocation */
- /* Methods to implement standard operations */
+ /* Methods to implement standard operations */
- (destructor) BaseMathObject_dealloc, /* destructor tp_dealloc; */
- NULL, /* printfunc tp_print; */
- NULL, /* getattrfunc tp_getattr; */
- NULL, /* setattrfunc tp_setattr; */
- NULL, /* cmpfunc tp_compare; */
- (reprfunc)Vector_repr, /* reprfunc tp_repr; */
+ (destructor)BaseMathObject_dealloc, /* destructor tp_dealloc; */
+ NULL, /* printfunc tp_print; */
+ NULL, /* getattrfunc tp_getattr; */
+ NULL, /* setattrfunc tp_setattr; */
+ NULL, /* cmpfunc tp_compare; */
+ (reprfunc)Vector_repr, /* reprfunc tp_repr; */
- /* Method suites for standard classes */
+ /* Method suites for standard classes */
- &Vector_NumMethods, /* PyNumberMethods *tp_as_number; */
- &Vector_SeqMethods, /* PySequenceMethods *tp_as_sequence; */
- &Vector_AsMapping, /* PyMappingMethods *tp_as_mapping; */
+ &Vector_NumMethods, /* PyNumberMethods *tp_as_number; */
+ &Vector_SeqMethods, /* PySequenceMethods *tp_as_sequence; */
+ &Vector_AsMapping, /* PyMappingMethods *tp_as_mapping; */
- /* More standard operations (here for binary compatibility) */
+ /* More standard operations (here for binary compatibility) */
- (hashfunc)Vector_hash, /* hashfunc tp_hash; */
- NULL, /* ternaryfunc tp_call; */
+ (hashfunc)Vector_hash, /* hashfunc tp_hash; */
+ NULL, /* ternaryfunc tp_call; */
#ifndef MATH_STANDALONE
- (reprfunc)Vector_str, /* reprfunc tp_str; */
+ (reprfunc)Vector_str, /* reprfunc tp_str; */
#else
- NULL, /* reprfunc tp_str; */
+ NULL, /* reprfunc tp_str; */
#endif
- NULL, /* getattrofunc tp_getattro; */
- NULL, /* setattrofunc tp_setattro; */
-
- /* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
-
- /*** Flags to define presence of optional/expanded features ***/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- vector_doc, /* char *tp_doc; Documentation string */
- /*** Assigned meaning in release 2.0 ***/
-
- /* call function for all accessible objects */
- (traverseproc)BaseMathObject_traverse, /* tp_traverse */
-
- /* delete references to contained objects */
- (inquiry)BaseMathObject_clear, /* tp_clear */
-
- /*** Assigned meaning in release 2.1 ***/
- /*** rich comparisons ***/
- (richcmpfunc)Vector_richcmpr, /* richcmpfunc tp_richcompare; */
-
- /*** weak reference enabler ***/
- 0, /* long tp_weaklistoffset; */
-
- /*** Added in release 2.2 ***/
- /* Iterators */
- NULL, /* getiterfunc tp_iter; */
- NULL, /* iternextfunc tp_iternext; */
-
- /*** Attribute descriptor and subclassing stuff ***/
- Vector_methods, /* struct PyMethodDef *tp_methods; */
- NULL, /* struct PyMemberDef *tp_members; */
- Vector_getseters, /* struct PyGetSetDef *tp_getset; */
- NULL, /* struct _typeobject *tp_base; */
- NULL, /* PyObject *tp_dict; */
- NULL, /* descrgetfunc tp_descr_get; */
- NULL, /* descrsetfunc tp_descr_set; */
- 0, /* long tp_dictoffset; */
- NULL, /* initproc tp_init; */
- NULL, /* allocfunc tp_alloc; */
- Vector_new, /* newfunc tp_new; */
- /* Low-level free-memory routine */
- NULL, /* freefunc tp_free; */
- /* For PyObject_IS_GC */
- NULL, /* inquiry tp_is_gc; */
- NULL, /* PyObject *tp_bases; */
- /* method resolution order */
- NULL, /* PyObject *tp_mro; */
- NULL, /* PyObject *tp_cache; */
- NULL, /* PyObject *tp_subclasses; */
- NULL, /* PyObject *tp_weaklist; */
- NULL,
+ NULL, /* getattrofunc tp_getattro; */
+ NULL, /* setattrofunc tp_setattro; */
+
+ /* Functions to access object as input/output buffer */
+ NULL, /* PyBufferProcs *tp_as_buffer; */
+
+ /*** Flags to define presence of optional/expanded features ***/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ vector_doc, /* char *tp_doc; Documentation string */
+ /*** Assigned meaning in release 2.0 ***/
+
+ /* call function for all accessible objects */
+ (traverseproc)BaseMathObject_traverse, /* tp_traverse */
+
+ /* delete references to contained objects */
+ (inquiry)BaseMathObject_clear, /* tp_clear */
+
+ /*** Assigned meaning in release 2.1 ***/
+ /*** rich comparisons ***/
+ (richcmpfunc)Vector_richcmpr, /* richcmpfunc tp_richcompare; */
+
+ /*** weak reference enabler ***/
+ 0, /* long tp_weaklistoffset; */
+
+ /*** Added in release 2.2 ***/
+ /* Iterators */
+ NULL, /* getiterfunc tp_iter; */
+ NULL, /* iternextfunc tp_iternext; */
+
+ /*** Attribute descriptor and subclassing stuff ***/
+ Vector_methods, /* struct PyMethodDef *tp_methods; */
+ NULL, /* struct PyMemberDef *tp_members; */
+ Vector_getseters, /* struct PyGetSetDef *tp_getset; */
+ NULL, /* struct _typeobject *tp_base; */
+ NULL, /* PyObject *tp_dict; */
+ NULL, /* descrgetfunc tp_descr_get; */
+ NULL, /* descrsetfunc tp_descr_set; */
+ 0, /* long tp_dictoffset; */
+ NULL, /* initproc tp_init; */
+ NULL, /* allocfunc tp_alloc; */
+ Vector_new, /* newfunc tp_new; */
+ /* Low-level free-memory routine */
+ NULL, /* freefunc tp_free; */
+ /* For PyObject_IS_GC */
+ NULL, /* inquiry tp_is_gc; */
+ NULL, /* PyObject *tp_bases; */
+ /* method resolution order */
+ NULL, /* PyObject *tp_mro; */
+ NULL, /* PyObject *tp_cache; */
+ NULL, /* PyObject *tp_subclasses; */
+ NULL, /* PyObject *tp_weaklist; */
+ NULL,
};
-PyObject *Vector_CreatePyObject(
- const float *vec, const int size,
- PyTypeObject *base_type)
-{
- VectorObject *self;
- float *vec_alloc;
-
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector(): invalid size");
- return NULL;
- }
-
- vec_alloc = PyMem_Malloc(size * sizeof(float));
- if (UNLIKELY(vec_alloc == NULL)) {
- PyErr_SetString(PyExc_MemoryError,
- "Vector(): "
- "problem allocating data");
- return NULL;
- }
-
- self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
- if (self) {
- self->vec = vec_alloc;
- self->size = size;
-
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
-
- if (vec) {
- memcpy(self->vec, vec, size * sizeof(float));
- }
- else { /* new empty */
- copy_vn_fl(self->vec, size, 0.0f);
- if (size == 4) { /* do the homogeneous thing */
- self->vec[3] = 1.0f;
- }
- }
- self->flag = BASE_MATH_FLAG_DEFAULT;
- }
- else {
- PyMem_Free(vec_alloc);
- }
-
- return (PyObject *)self;
+PyObject *Vector_CreatePyObject(const float *vec, const int size, PyTypeObject *base_type)
+{
+ VectorObject *self;
+ float *vec_alloc;
+
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
+ return NULL;
+ }
+
+ vec_alloc = PyMem_Malloc(size * sizeof(float));
+ if (UNLIKELY(vec_alloc == NULL)) {
+ PyErr_SetString(PyExc_MemoryError,
+ "Vector(): "
+ "problem allocating data");
+ return NULL;
+ }
+
+ self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
+ if (self) {
+ self->vec = vec_alloc;
+ self->size = size;
+
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
+
+ if (vec) {
+ memcpy(self->vec, vec, size * sizeof(float));
+ }
+ else { /* new empty */
+ copy_vn_fl(self->vec, size, 0.0f);
+ if (size == 4) { /* do the homogeneous thing */
+ self->vec[3] = 1.0f;
+ }
+ }
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ }
+ else {
+ PyMem_Free(vec_alloc);
+ }
+
+ return (PyObject *)self;
}
/**
@@ -3198,64 +3382,60 @@ PyObject *Vector_CreatePyObject(
*
* \param vec: Use this vector in-place.
*/
-PyObject *Vector_CreatePyObject_wrap(
- float *vec, const int size,
- PyTypeObject *base_type)
+PyObject *Vector_CreatePyObject_wrap(float *vec, const int size, PyTypeObject *base_type)
{
- VectorObject *self;
+ VectorObject *self;
- if (size < 2) {
- PyErr_SetString(PyExc_RuntimeError,
- "Vector(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_RuntimeError, "Vector(): invalid size");
+ return NULL;
+ }
- self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
- if (self) {
- self->size = size;
+ self = BASE_MATH_NEW(VectorObject, vector_Type, base_type);
+ if (self) {
+ self->size = size;
- /* init callbacks as NULL */
- self->cb_user = NULL;
- self->cb_type = self->cb_subtype = 0;
+ /* init callbacks as NULL */
+ self->cb_user = NULL;
+ self->cb_type = self->cb_subtype = 0;
- self->vec = vec;
- self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
- }
- return (PyObject *) self;
+ self->vec = vec;
+ self->flag = BASE_MATH_FLAG_DEFAULT | BASE_MATH_FLAG_IS_WRAP;
+ }
+ return (PyObject *)self;
}
/**
* Create a vector where the value is defined by registered callbacks,
* see: #Mathutils_RegisterCallback
*/
-PyObject *Vector_CreatePyObject_cb(
- PyObject *cb_user, int size,
- unsigned char cb_type, unsigned char cb_subtype)
+PyObject *Vector_CreatePyObject_cb(PyObject *cb_user,
+ int size,
+ unsigned char cb_type,
+ unsigned char cb_subtype)
{
- VectorObject *self = (VectorObject *)Vector_CreatePyObject(NULL, size, NULL);
- if (self) {
- Py_INCREF(cb_user);
- self->cb_user = cb_user;
- self->cb_type = cb_type;
- self->cb_subtype = cb_subtype;
- PyObject_GC_Track(self);
- }
+ VectorObject *self = (VectorObject *)Vector_CreatePyObject(NULL, size, NULL);
+ if (self) {
+ Py_INCREF(cb_user);
+ self->cb_user = cb_user;
+ self->cb_type = cb_type;
+ self->cb_subtype = cb_subtype;
+ PyObject_GC_Track(self);
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
/**
* \param vec: Initialized vector value to use in-place, allocated with: PyMem_Malloc
*/
-PyObject *Vector_CreatePyObject_alloc(
- float *vec, const int size,
- PyTypeObject *base_type)
+PyObject *Vector_CreatePyObject_alloc(float *vec, const int size, PyTypeObject *base_type)
{
- VectorObject *self;
- self = (VectorObject *)Vector_CreatePyObject_wrap(vec, size, base_type);
- if (self) {
- self->flag = BASE_MATH_FLAG_DEFAULT;
- }
+ VectorObject *self;
+ self = (VectorObject *)Vector_CreatePyObject_wrap(vec, size, base_type);
+ if (self) {
+ self->flag = BASE_MATH_FLAG_DEFAULT;
+ }
- return (PyObject *)self;
+ return (PyObject *)self;
}
diff --git a/source/blender/python/mathutils/mathutils_Vector.h b/source/blender/python/mathutils/mathutils_Vector.h
index 7ebc3fbf1d6..f75702bc54c 100644
--- a/source/blender/python/mathutils/mathutils_Vector.h
+++ b/source/blender/python/mathutils/mathutils_Vector.h
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#ifndef __MATHUTILS_VECTOR_H__
#define __MATHUTILS_VECTOR_H__
@@ -28,27 +27,26 @@ extern PyTypeObject vector_Type;
#define VectorObject_CheckExact(v) (Py_TYPE(v) == &vector_Type)
typedef struct {
- BASE_MATH_MEMBERS(vec);
+ BASE_MATH_MEMBERS(vec);
- int size; /* vec size 2 or more */
+ int size; /* vec size 2 or more */
} VectorObject;
/*prototypes*/
-PyObject *Vector_CreatePyObject(
- const float *vec, const int size,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Vector_CreatePyObject_wrap(
- float *vec, const int size,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-PyObject *Vector_CreatePyObject_cb(
- PyObject *user, int size,
- unsigned char cb_type, unsigned char subtype
- ) ATTR_WARN_UNUSED_RESULT;
-PyObject *Vector_CreatePyObject_alloc(
- float *vec, const int size,
- PyTypeObject *base_type
- ) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-
-#endif /* __MATHUTILS_VECTOR_H__ */
+PyObject *Vector_CreatePyObject(const float *vec,
+ const int size,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT;
+PyObject *Vector_CreatePyObject_wrap(float *vec,
+ const int size,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+PyObject *Vector_CreatePyObject_cb(PyObject *user,
+ int size,
+ unsigned char cb_type,
+ unsigned char subtype) ATTR_WARN_UNUSED_RESULT;
+PyObject *Vector_CreatePyObject_alloc(float *vec,
+ const int size,
+ PyTypeObject *base_type) ATTR_WARN_UNUSED_RESULT
+ ATTR_NONNULL(1);
+
+#endif /* __MATHUTILS_VECTOR_H__ */
diff --git a/source/blender/python/mathutils/mathutils_bvhtree.c b/source/blender/python/mathutils/mathutils_bvhtree.c
index b1420f316e6..cdb3035c0ca 100644
--- a/source/blender/python/mathutils/mathutils_bvhtree.c
+++ b/source/blender/python/mathutils/mathutils_bvhtree.c
@@ -38,52 +38,50 @@
#include "../generic/python_utildefines.h"
#include "mathutils.h"
-#include "mathutils_bvhtree.h" /* own include */
+#include "mathutils_bvhtree.h" /* own include */
#ifndef MATH_STANDALONE
-#include "DNA_object_types.h"
-#include "DNA_mesh_types.h"
-#include "DNA_meshdata_types.h"
+# include "DNA_object_types.h"
+# include "DNA_mesh_types.h"
+# include "DNA_meshdata_types.h"
-#include "BKE_customdata.h"
-#include "BKE_editmesh_bvh.h"
-#include "BKE_library.h"
-#include "BKE_mesh.h"
-#include "BKE_mesh_runtime.h"
+# include "BKE_customdata.h"
+# include "BKE_editmesh_bvh.h"
+# include "BKE_library.h"
+# include "BKE_mesh.h"
+# include "BKE_mesh_runtime.h"
-#include "DEG_depsgraph_query.h"
+# include "DEG_depsgraph_query.h"
-#include "bmesh.h"
-
-#include "../bmesh/bmesh_py_types.h"
-#endif /* MATH_STANDALONE */
+# include "bmesh.h"
+# include "../bmesh/bmesh_py_types.h"
+#endif /* MATH_STANDALONE */
#include "BLI_strict_flags.h"
-
/* -------------------------------------------------------------------- */
/** \name Docstring (snippets)
* \{ */
#define PYBVH_FIND_GENERIC_DISTANCE_DOC \
-" :arg distance: Maximum distance threshold.\n" \
-" :type distance: float\n"
+ " :arg distance: Maximum distance threshold.\n" \
+ " :type distance: float\n"
#define PYBVH_FIND_GENERIC_RETURN_DOC \
-" :return: Returns a tuple\n" \
-" (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
-" Values will all be None if no hit is found.\n" \
-" :rtype: :class:`tuple`\n"
+ " :return: Returns a tuple\n" \
+ " (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
+ " Values will all be None if no hit is found.\n" \
+ " :rtype: :class:`tuple`\n"
#define PYBVH_FIND_GENERIC_RETURN_LIST_DOC \
-" :return: Returns a list of tuples\n" \
-" (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
-" :rtype: :class:`list`\n"
+ " :return: Returns a list of tuples\n" \
+ " (:class:`Vector` location, :class:`Vector` normal, int index, float distance),\n" \
+ " :rtype: :class:`list`\n"
#define PYBVH_FROM_GENERIC_EPSILON_DOC \
-" :arg epsilon: Increase the threshold for detecting overlap and raycast hits.\n" \
-" :type epsilon: float\n"
+ " :arg epsilon: Increase the threshold for detecting overlap and raycast hits.\n" \
+ " :type epsilon: float\n"
/** \} */
@@ -95,160 +93,157 @@ static const char PY_BVH_TREE_TYPE_DEFAULT = 4;
static const char PY_BVH_AXIS_DEFAULT = 6;
typedef struct {
- PyObject_HEAD
- BVHTree *tree;
- float epsilon;
-
- float (*coords)[3];
- unsigned int (*tris)[3];
- unsigned int coords_len, tris_len;
-
- /* Optional members */
- /* aligned with 'tris' */
- int *orig_index;
- /* aligned with array that 'orig_index' points to */
- float (*orig_normal)[3];
+ PyObject_HEAD BVHTree *tree;
+ float epsilon;
+
+ float (*coords)[3];
+ unsigned int (*tris)[3];
+ unsigned int coords_len, tris_len;
+
+ /* Optional members */
+ /* aligned with 'tris' */
+ int *orig_index;
+ /* aligned with array that 'orig_index' points to */
+ float (*orig_normal)[3];
} PyBVHTree;
-
/* -------------------------------------------------------------------- */
/** \name Utility helper functions
* \{ */
-static PyObject *bvhtree_CreatePyObject(
- BVHTree *tree, float epsilon,
+static PyObject *bvhtree_CreatePyObject(BVHTree *tree,
+ float epsilon,
- float (*coords)[3], unsigned int coords_len,
- unsigned int (*tris)[3], unsigned int tris_len,
+ float (*coords)[3],
+ unsigned int coords_len,
+ unsigned int (*tris)[3],
+ unsigned int tris_len,
- /* optional arrays */
- int *orig_index, float (*orig_normal)[3])
+ /* optional arrays */
+ int *orig_index,
+ float (*orig_normal)[3])
{
- PyBVHTree *result = PyObject_New(PyBVHTree, &PyBVHTree_Type);
+ PyBVHTree *result = PyObject_New(PyBVHTree, &PyBVHTree_Type);
- result->tree = tree;
- result->epsilon = epsilon;
+ result->tree = tree;
+ result->epsilon = epsilon;
- result->coords = coords;
- result->tris = tris;
- result->coords_len = coords_len;
- result->tris_len = tris_len;
+ result->coords = coords;
+ result->tris = tris;
+ result->coords_len = coords_len;
+ result->tris_len = tris_len;
- result->orig_index = orig_index;
- result->orig_normal = orig_normal;
+ result->orig_index = orig_index;
+ result->orig_normal = orig_normal;
- return (PyObject *)result;
+ return (PyObject *)result;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name BVHTreeRayHit to Python utilities
* \{ */
static void py_bvhtree_raycast_to_py_tuple(const BVHTreeRayHit *hit, PyObject *py_retval)
{
- BLI_assert(hit->index >= 0);
- BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
-
- PyTuple_SET_ITEMS(py_retval,
- Vector_CreatePyObject(hit->co, 3, NULL),
- Vector_CreatePyObject(hit->no, 3, NULL),
- PyLong_FromLong(hit->index),
- PyFloat_FromDouble(hit->dist));
-
+ BLI_assert(hit->index >= 0);
+ BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
+
+ PyTuple_SET_ITEMS(py_retval,
+ Vector_CreatePyObject(hit->co, 3, NULL),
+ Vector_CreatePyObject(hit->no, 3, NULL),
+ PyLong_FromLong(hit->index),
+ PyFloat_FromDouble(hit->dist));
}
static PyObject *py_bvhtree_raycast_to_py(const BVHTreeRayHit *hit)
{
- PyObject *py_retval = PyTuple_New(4);
+ PyObject *py_retval = PyTuple_New(4);
- py_bvhtree_raycast_to_py_tuple(hit, py_retval);
+ py_bvhtree_raycast_to_py_tuple(hit, py_retval);
- return py_retval;
+ return py_retval;
}
static PyObject *py_bvhtree_raycast_to_py_none(void)
{
- PyObject *py_retval = PyTuple_New(4);
+ PyObject *py_retval = PyTuple_New(4);
- PyC_Tuple_Fill(py_retval, Py_None);
+ PyC_Tuple_Fill(py_retval, Py_None);
- return py_retval;
+ return py_retval;
}
#if 0
static PyObject *py_bvhtree_raycast_to_py_and_check(const BVHTreeRayHit *hit)
{
- PyObject *py_retval;
+ PyObject *py_retval;
- py_retval = PyTuple_New(4);
+ py_retval = PyTuple_New(4);
- if (hit->index != -1) {
- py_bvhtree_raycast_to_py_tuple(hit, py_retval);
- }
- else {
- PyC_Tuple_Fill(py_retval, Py_None);
- }
+ if (hit->index != -1) {
+ py_bvhtree_raycast_to_py_tuple(hit, py_retval);
+ }
+ else {
+ PyC_Tuple_Fill(py_retval, Py_None);
+ }
- return py_retval;
+ return py_retval;
}
#endif
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name BVHTreeNearest to Python utilities
* \{ */
static void py_bvhtree_nearest_to_py_tuple(const BVHTreeNearest *nearest, PyObject *py_retval)
{
- BLI_assert(nearest->index >= 0);
- BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
-
- PyTuple_SET_ITEMS(py_retval,
- Vector_CreatePyObject(nearest->co, 3, NULL),
- Vector_CreatePyObject(nearest->no, 3, NULL),
- PyLong_FromLong(nearest->index),
- PyFloat_FromDouble(sqrtf(nearest->dist_sq)));
-
+ BLI_assert(nearest->index >= 0);
+ BLI_assert(PyTuple_GET_SIZE(py_retval) == 4);
+
+ PyTuple_SET_ITEMS(py_retval,
+ Vector_CreatePyObject(nearest->co, 3, NULL),
+ Vector_CreatePyObject(nearest->no, 3, NULL),
+ PyLong_FromLong(nearest->index),
+ PyFloat_FromDouble(sqrtf(nearest->dist_sq)));
}
static PyObject *py_bvhtree_nearest_to_py(const BVHTreeNearest *nearest)
{
- PyObject *py_retval = PyTuple_New(4);
+ PyObject *py_retval = PyTuple_New(4);
- py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
+ py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
- return py_retval;
+ return py_retval;
}
static PyObject *py_bvhtree_nearest_to_py_none(void)
{
- PyObject *py_retval = PyTuple_New(4);
+ PyObject *py_retval = PyTuple_New(4);
- PyC_Tuple_Fill(py_retval, Py_None);
+ PyC_Tuple_Fill(py_retval, Py_None);
- return py_retval;
+ return py_retval;
}
#if 0
static PyObject *py_bvhtree_nearest_to_py_and_check(const BVHTreeNearest *nearest)
{
- PyObject *py_retval;
+ PyObject *py_retval;
- py_retval = PyTuple_New(4);
+ py_retval = PyTuple_New(4);
- if (nearest->index != -1) {
- py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
- }
- else {
- PyC_Tuple_Fill(py_retval, Py_None);
- }
+ if (nearest->index != -1) {
+ py_bvhtree_nearest_to_py_tuple(nearest, py_retval);
+ }
+ else {
+ PyC_Tuple_Fill(py_retval, Py_None);
+ }
- return py_retval;
+ return py_retval;
}
#endif
@@ -256,1082 +251,1098 @@ static PyObject *py_bvhtree_nearest_to_py_and_check(const BVHTreeNearest *neares
static void py_bvhtree__tp_dealloc(PyBVHTree *self)
{
- if (self->tree) {
- BLI_bvhtree_free(self->tree);
- }
+ if (self->tree) {
+ BLI_bvhtree_free(self->tree);
+ }
- MEM_SAFE_FREE(self->coords);
- MEM_SAFE_FREE(self->tris);
+ MEM_SAFE_FREE(self->coords);
+ MEM_SAFE_FREE(self->tris);
- MEM_SAFE_FREE(self->orig_index);
- MEM_SAFE_FREE(self->orig_normal);
+ MEM_SAFE_FREE(self->orig_index);
+ MEM_SAFE_FREE(self->orig_normal);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
-
/* -------------------------------------------------------------------- */
/** \name Methods
* \{ */
-static void py_bvhtree_raycast_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
+static void py_bvhtree_raycast_cb(void *userdata,
+ int index,
+ const BVHTreeRay *ray,
+ BVHTreeRayHit *hit)
{
- const PyBVHTree *self = userdata;
-
- const float (*coords)[3] = (const float (*)[3])self->coords;
- const unsigned int *tri = self->tris[index];
- const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
- float dist;
-
- if (self->epsilon == 0.0f) {
- dist = bvhtree_ray_tri_intersection(ray, hit->dist, UNPACK3(tri_co));
- }
- else {
- dist = bvhtree_sphereray_tri_intersection(ray, self->epsilon, hit->dist, UNPACK3(tri_co));
- }
-
- if (dist >= 0 && dist < hit->dist) {
- hit->index = self->orig_index ? self->orig_index[index] : index;
- hit->dist = dist;
- madd_v3_v3v3fl(hit->co, ray->origin, ray->direction, dist);
- if (self->orig_normal) {
- copy_v3_v3(hit->no, self->orig_normal[hit->index]);
- }
- else {
- normal_tri_v3(hit->no, UNPACK3(tri_co));
- }
- }
+ const PyBVHTree *self = userdata;
+
+ const float(*coords)[3] = (const float(*)[3])self->coords;
+ const unsigned int *tri = self->tris[index];
+ const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
+ float dist;
+
+ if (self->epsilon == 0.0f) {
+ dist = bvhtree_ray_tri_intersection(ray, hit->dist, UNPACK3(tri_co));
+ }
+ else {
+ dist = bvhtree_sphereray_tri_intersection(ray, self->epsilon, hit->dist, UNPACK3(tri_co));
+ }
+
+ if (dist >= 0 && dist < hit->dist) {
+ hit->index = self->orig_index ? self->orig_index[index] : index;
+ hit->dist = dist;
+ madd_v3_v3v3fl(hit->co, ray->origin, ray->direction, dist);
+ if (self->orig_normal) {
+ copy_v3_v3(hit->no, self->orig_normal[hit->index]);
+ }
+ else {
+ normal_tri_v3(hit->no, UNPACK3(tri_co));
+ }
+ }
}
-static void py_bvhtree_nearest_point_cb(void *userdata, int index, const float co[3], BVHTreeNearest *nearest)
+static void py_bvhtree_nearest_point_cb(void *userdata,
+ int index,
+ const float co[3],
+ BVHTreeNearest *nearest)
{
- PyBVHTree *self = userdata;
-
- const float (*coords)[3] = (const float (*)[3])self->coords;
- const unsigned int *tri = self->tris[index];
- const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
- float nearest_tmp[3], dist_sq;
-
- closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
- dist_sq = len_squared_v3v3(co, nearest_tmp);
-
- if (dist_sq < nearest->dist_sq) {
- nearest->index = self->orig_index ? self->orig_index[index] : index;
- nearest->dist_sq = dist_sq;
- copy_v3_v3(nearest->co, nearest_tmp);
- if (self->orig_normal) {
- copy_v3_v3(nearest->no, self->orig_normal[nearest->index]);
- }
- else {
- normal_tri_v3(nearest->no, UNPACK3(tri_co));
- }
- }
+ PyBVHTree *self = userdata;
+
+ const float(*coords)[3] = (const float(*)[3])self->coords;
+ const unsigned int *tri = self->tris[index];
+ const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
+ float nearest_tmp[3], dist_sq;
+
+ closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
+ dist_sq = len_squared_v3v3(co, nearest_tmp);
+
+ if (dist_sq < nearest->dist_sq) {
+ nearest->index = self->orig_index ? self->orig_index[index] : index;
+ nearest->dist_sq = dist_sq;
+ copy_v3_v3(nearest->co, nearest_tmp);
+ if (self->orig_normal) {
+ copy_v3_v3(nearest->no, self->orig_normal[nearest->index]);
+ }
+ else {
+ normal_tri_v3(nearest->no, UNPACK3(tri_co));
+ }
+ }
}
PyDoc_STRVAR(py_bvhtree_ray_cast_doc,
-".. method:: ray_cast(origin, direction, distance=sys.float_info.max)\n"
-"\n"
-" Cast a ray onto the mesh.\n"
-"\n"
-" :arg co: Start location of the ray in object space.\n"
-" :type co: :class:`Vector`\n"
-" :arg direction: Direction of the ray in object space.\n"
-" :type direction: :class:`Vector`\n"
-PYBVH_FIND_GENERIC_DISTANCE_DOC
-PYBVH_FIND_GENERIC_RETURN_DOC
-);
+ ".. method:: ray_cast(origin, direction, distance=sys.float_info.max)\n"
+ "\n"
+ " Cast a ray onto the mesh.\n"
+ "\n"
+ " :arg co: Start location of the ray in object space.\n"
+ " :type co: :class:`Vector`\n"
+ " :arg direction: Direction of the ray in object space.\n"
+ " :type direction: :class:`Vector`\n" PYBVH_FIND_GENERIC_DISTANCE_DOC
+ PYBVH_FIND_GENERIC_RETURN_DOC);
static PyObject *py_bvhtree_ray_cast(PyBVHTree *self, PyObject *args)
{
- const char *error_prefix = "ray_cast";
- float co[3], direction[3];
- float max_dist = FLT_MAX;
- BVHTreeRayHit hit;
-
- /* parse args */
- {
- PyObject *py_co, *py_direction;
-
- if (!PyArg_ParseTuple(
- args, (char *)"OO|f:ray_cast",
- &py_co, &py_direction, &max_dist))
- {
- return NULL;
- }
-
- if ((mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) ||
- (mathutils_array_parse(direction, 2, 3 | MU_ARRAY_ZERO, py_direction, error_prefix) == -1))
- {
- return NULL;
- }
-
- normalize_v3(direction);
- }
-
- hit.dist = max_dist;
- hit.index = -1;
-
- /* may fail if the mesh has no faces, in that case the ray-cast misses */
- if (self->tree) {
- if (BLI_bvhtree_ray_cast(
- self->tree, co, direction, 0.0f, &hit,
- py_bvhtree_raycast_cb, self) != -1)
- {
- return py_bvhtree_raycast_to_py(&hit);
- }
- }
-
- return py_bvhtree_raycast_to_py_none();
+ const char *error_prefix = "ray_cast";
+ float co[3], direction[3];
+ float max_dist = FLT_MAX;
+ BVHTreeRayHit hit;
+
+ /* parse args */
+ {
+ PyObject *py_co, *py_direction;
+
+ if (!PyArg_ParseTuple(args, (char *)"OO|f:ray_cast", &py_co, &py_direction, &max_dist)) {
+ return NULL;
+ }
+
+ if ((mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) ||
+ (mathutils_array_parse(direction, 2, 3 | MU_ARRAY_ZERO, py_direction, error_prefix) ==
+ -1)) {
+ return NULL;
+ }
+
+ normalize_v3(direction);
+ }
+
+ hit.dist = max_dist;
+ hit.index = -1;
+
+ /* may fail if the mesh has no faces, in that case the ray-cast misses */
+ if (self->tree) {
+ if (BLI_bvhtree_ray_cast(self->tree, co, direction, 0.0f, &hit, py_bvhtree_raycast_cb, self) !=
+ -1) {
+ return py_bvhtree_raycast_to_py(&hit);
+ }
+ }
+
+ return py_bvhtree_raycast_to_py_none();
}
PyDoc_STRVAR(py_bvhtree_find_nearest_doc,
-".. method:: find_nearest(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
-"\n"
-" Find the nearest element (typically face index) to a point.\n"
-"\n"
-" :arg co: Find nearest element to this point.\n"
-" :type co: :class:`Vector`\n"
-PYBVH_FIND_GENERIC_DISTANCE_DOC
-PYBVH_FIND_GENERIC_RETURN_DOC
-);
+ ".. method:: find_nearest(origin, distance=" PYBVH_MAX_DIST_STR
+ ")\n"
+ "\n"
+ " Find the nearest element (typically face index) to a point.\n"
+ "\n"
+ " :arg co: Find nearest element to this point.\n"
+ " :type co: :class:`Vector`\n" PYBVH_FIND_GENERIC_DISTANCE_DOC
+ PYBVH_FIND_GENERIC_RETURN_DOC);
static PyObject *py_bvhtree_find_nearest(PyBVHTree *self, PyObject *args)
{
- const char *error_prefix = "find_nearest";
- float co[3];
- float max_dist = max_dist_default;
-
- BVHTreeNearest nearest;
-
- /* parse args */
- {
- PyObject *py_co;
-
- if (!PyArg_ParseTuple(
- args, (char *)"O|f:find_nearest",
- &py_co, &max_dist))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
- return NULL;
- }
- }
-
- nearest.index = -1;
- nearest.dist_sq = max_dist * max_dist;
-
- /* may fail if the mesh has no faces, in that case the ray-cast misses */
- if (self->tree) {
- if (BLI_bvhtree_find_nearest(
- self->tree, co, &nearest,
- py_bvhtree_nearest_point_cb, self) != -1)
- {
- return py_bvhtree_nearest_to_py(&nearest);
- }
- }
-
- return py_bvhtree_nearest_to_py_none();
+ const char *error_prefix = "find_nearest";
+ float co[3];
+ float max_dist = max_dist_default;
+
+ BVHTreeNearest nearest;
+
+ /* parse args */
+ {
+ PyObject *py_co;
+
+ if (!PyArg_ParseTuple(args, (char *)"O|f:find_nearest", &py_co, &max_dist)) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ nearest.index = -1;
+ nearest.dist_sq = max_dist * max_dist;
+
+ /* may fail if the mesh has no faces, in that case the ray-cast misses */
+ if (self->tree) {
+ if (BLI_bvhtree_find_nearest(self->tree, co, &nearest, py_bvhtree_nearest_point_cb, self) !=
+ -1) {
+ return py_bvhtree_nearest_to_py(&nearest);
+ }
+ }
+
+ return py_bvhtree_nearest_to_py_none();
}
struct PyBVH_RangeData {
- PyBVHTree *self;
- PyObject *result;
- float dist_sq;
+ PyBVHTree *self;
+ PyObject *result;
+ float dist_sq;
};
-static void py_bvhtree_nearest_point_range_cb(void *userdata, int index, const float co[3], float UNUSED(dist_sq_bvh))
+static void py_bvhtree_nearest_point_range_cb(void *userdata,
+ int index,
+ const float co[3],
+ float UNUSED(dist_sq_bvh))
{
- struct PyBVH_RangeData *data = userdata;
- PyBVHTree *self = data->self;
-
- const float (*coords)[3] = (const float (*)[3])self->coords;
- const unsigned int *tri = self->tris[index];
- const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
- float nearest_tmp[3], dist_sq;
-
- closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
- dist_sq = len_squared_v3v3(co, nearest_tmp);
-
- if (dist_sq < data->dist_sq) {
- BVHTreeNearest nearest;
- nearest.index = self->orig_index ? self->orig_index[index] : index;
- nearest.dist_sq = dist_sq;
- copy_v3_v3(nearest.co, nearest_tmp);
- if (self->orig_normal) {
- copy_v3_v3(nearest.no, self->orig_normal[nearest.index]);
- }
- else {
- normal_tri_v3(nearest.no, UNPACK3(tri_co));
- }
-
- PyList_APPEND(data->result, py_bvhtree_nearest_to_py(&nearest));
- }
+ struct PyBVH_RangeData *data = userdata;
+ PyBVHTree *self = data->self;
+
+ const float(*coords)[3] = (const float(*)[3])self->coords;
+ const unsigned int *tri = self->tris[index];
+ const float *tri_co[3] = {coords[tri[0]], coords[tri[1]], coords[tri[2]]};
+ float nearest_tmp[3], dist_sq;
+
+ closest_on_tri_to_point_v3(nearest_tmp, co, UNPACK3(tri_co));
+ dist_sq = len_squared_v3v3(co, nearest_tmp);
+
+ if (dist_sq < data->dist_sq) {
+ BVHTreeNearest nearest;
+ nearest.index = self->orig_index ? self->orig_index[index] : index;
+ nearest.dist_sq = dist_sq;
+ copy_v3_v3(nearest.co, nearest_tmp);
+ if (self->orig_normal) {
+ copy_v3_v3(nearest.no, self->orig_normal[nearest.index]);
+ }
+ else {
+ normal_tri_v3(nearest.no, UNPACK3(tri_co));
+ }
+
+ PyList_APPEND(data->result, py_bvhtree_nearest_to_py(&nearest));
+ }
}
-PyDoc_STRVAR(py_bvhtree_find_nearest_range_doc,
-".. method:: find_nearest_range(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
-"\n"
-" Find the nearest elements (typically face index) to a point in the distance range.\n"
-"\n"
-" :arg co: Find nearest elements to this point.\n"
-" :type co: :class:`Vector`\n"
-PYBVH_FIND_GENERIC_DISTANCE_DOC
-PYBVH_FIND_GENERIC_RETURN_LIST_DOC
-);
+PyDoc_STRVAR(
+ py_bvhtree_find_nearest_range_doc,
+ ".. method:: find_nearest_range(origin, distance=" PYBVH_MAX_DIST_STR
+ ")\n"
+ "\n"
+ " Find the nearest elements (typically face index) to a point in the distance range.\n"
+ "\n"
+ " :arg co: Find nearest elements to this point.\n"
+ " :type co: :class:`Vector`\n" PYBVH_FIND_GENERIC_DISTANCE_DOC
+ PYBVH_FIND_GENERIC_RETURN_LIST_DOC);
static PyObject *py_bvhtree_find_nearest_range(PyBVHTree *self, PyObject *args)
{
- const char *error_prefix = "find_nearest_range";
- float co[3];
- float max_dist = max_dist_default;
-
- /* parse args */
- {
- PyObject *py_co;
-
- if (!PyArg_ParseTuple(
- args, (char *)"O|f:find_nearest_range",
- &py_co, &max_dist))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
- return NULL;
- }
- }
-
- PyObject *ret = PyList_New(0);
-
- if (self->tree) {
- struct PyBVH_RangeData data = {
- .self = self,
- .result = ret,
- .dist_sq = SQUARE(max_dist),
- };
-
- BLI_bvhtree_range_query(
- self->tree, co, max_dist,
- py_bvhtree_nearest_point_range_cb, &data);
- }
-
- return ret;
-}
+ const char *error_prefix = "find_nearest_range";
+ float co[3];
+ float max_dist = max_dist_default;
+
+ /* parse args */
+ {
+ PyObject *py_co;
+
+ if (!PyArg_ParseTuple(args, (char *)"O|f:find_nearest_range", &py_co, &max_dist)) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(co, 2, 3 | MU_ARRAY_ZERO, py_co, error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ PyObject *ret = PyList_New(0);
+ if (self->tree) {
+ struct PyBVH_RangeData data = {
+ .self = self,
+ .result = ret,
+ .dist_sq = SQUARE(max_dist),
+ };
+
+ BLI_bvhtree_range_query(self->tree, co, max_dist, py_bvhtree_nearest_point_range_cb, &data);
+ }
+
+ return ret;
+}
BLI_INLINE unsigned int overlap_hash(const void *overlap_v)
{
- const BVHTreeOverlap *overlap = overlap_v;
- /* same constants as edge-hash */
- return (((unsigned int)overlap->indexA * 65) ^ ((unsigned int)overlap->indexA * 31));
+ const BVHTreeOverlap *overlap = overlap_v;
+ /* same constants as edge-hash */
+ return (((unsigned int)overlap->indexA * 65) ^ ((unsigned int)overlap->indexA * 31));
}
BLI_INLINE bool overlap_cmp(const void *a_v, const void *b_v)
{
- const BVHTreeOverlap *a = a_v;
- const BVHTreeOverlap *b = b_v;
- return (memcmp(a, b, sizeof(*a)) != 0);
+ const BVHTreeOverlap *a = a_v;
+ const BVHTreeOverlap *b = b_v;
+ return (memcmp(a, b, sizeof(*a)) != 0);
}
struct PyBVHTree_OverlapData {
- PyBVHTree *tree_pair[2];
- float epsilon;
+ PyBVHTree *tree_pair[2];
+ float epsilon;
};
static bool py_bvhtree_overlap_cb(void *userdata, int index_a, int index_b, int UNUSED(thread))
{
- struct PyBVHTree_OverlapData *data = userdata;
- PyBVHTree *tree_a = data->tree_pair[0];
- PyBVHTree *tree_b = data->tree_pair[1];
- const unsigned int *tri_a = tree_a->tris[index_a];
- const unsigned int *tri_b = tree_b->tris[index_b];
- const float *tri_a_co[3] = {tree_a->coords[tri_a[0]], tree_a->coords[tri_a[1]], tree_a->coords[tri_a[2]]};
- const float *tri_b_co[3] = {tree_b->coords[tri_b[0]], tree_b->coords[tri_b[1]], tree_b->coords[tri_b[2]]};
- float ix_pair[2][3];
- int verts_shared = 0;
-
- if (tree_a == tree_b) {
- if (UNLIKELY(index_a == index_b)) {
- return false;
- }
-
- verts_shared = (
- ELEM(tri_a_co[0], UNPACK3(tri_b_co)) +
- ELEM(tri_a_co[1], UNPACK3(tri_b_co)) +
- ELEM(tri_a_co[2], UNPACK3(tri_b_co)));
-
- /* if 2 points are shared, bail out */
- if (verts_shared >= 2) {
- return false;
- }
- }
-
- return (isect_tri_tri_epsilon_v3(UNPACK3(tri_a_co), UNPACK3(tri_b_co), ix_pair[0], ix_pair[1], data->epsilon) &&
- ((verts_shared == 0) || (len_squared_v3v3(ix_pair[0], ix_pair[1]) > data->epsilon)));
+ struct PyBVHTree_OverlapData *data = userdata;
+ PyBVHTree *tree_a = data->tree_pair[0];
+ PyBVHTree *tree_b = data->tree_pair[1];
+ const unsigned int *tri_a = tree_a->tris[index_a];
+ const unsigned int *tri_b = tree_b->tris[index_b];
+ const float *tri_a_co[3] = {
+ tree_a->coords[tri_a[0]], tree_a->coords[tri_a[1]], tree_a->coords[tri_a[2]]};
+ const float *tri_b_co[3] = {
+ tree_b->coords[tri_b[0]], tree_b->coords[tri_b[1]], tree_b->coords[tri_b[2]]};
+ float ix_pair[2][3];
+ int verts_shared = 0;
+
+ if (tree_a == tree_b) {
+ if (UNLIKELY(index_a == index_b)) {
+ return false;
+ }
+
+ verts_shared = (ELEM(tri_a_co[0], UNPACK3(tri_b_co)) + ELEM(tri_a_co[1], UNPACK3(tri_b_co)) +
+ ELEM(tri_a_co[2], UNPACK3(tri_b_co)));
+
+ /* if 2 points are shared, bail out */
+ if (verts_shared >= 2) {
+ return false;
+ }
+ }
+
+ return (isect_tri_tri_epsilon_v3(
+ UNPACK3(tri_a_co), UNPACK3(tri_b_co), ix_pair[0], ix_pair[1], data->epsilon) &&
+ ((verts_shared == 0) || (len_squared_v3v3(ix_pair[0], ix_pair[1]) > data->epsilon)));
}
-PyDoc_STRVAR(py_bvhtree_overlap_doc,
-".. method:: overlap(other_tree)\n"
-"\n"
-" Find overlapping indices between 2 trees.\n"
-"\n"
-" :arg other_tree: Other tree to perform overlap test on.\n"
-" :type other_tree: :class:`BVHTree`\n"
-" :return: Returns a list of unique index pairs,"
-" the first index referencing this tree, the second referencing the **other_tree**.\n"
-" :rtype: :class:`list`\n"
-);
+PyDoc_STRVAR(
+ py_bvhtree_overlap_doc,
+ ".. method:: overlap(other_tree)\n"
+ "\n"
+ " Find overlapping indices between 2 trees.\n"
+ "\n"
+ " :arg other_tree: Other tree to perform overlap test on.\n"
+ " :type other_tree: :class:`BVHTree`\n"
+ " :return: Returns a list of unique index pairs,"
+ " the first index referencing this tree, the second referencing the **other_tree**.\n"
+ " :rtype: :class:`list`\n");
static PyObject *py_bvhtree_overlap(PyBVHTree *self, PyBVHTree *other)
{
- struct PyBVHTree_OverlapData data;
- BVHTreeOverlap *overlap;
- unsigned int overlap_len = 0;
- PyObject *ret;
-
- if (!PyBVHTree_CheckExact(other)) {
- PyErr_SetString(PyExc_ValueError, "Expected a BVHTree argument");
- return NULL;
- }
-
- data.tree_pair[0] = self;
- data.tree_pair[1] = other;
- data.epsilon = max_ff(self->epsilon, other->epsilon);
-
- overlap = BLI_bvhtree_overlap(self->tree, other->tree, &overlap_len, py_bvhtree_overlap_cb, &data);
-
- ret = PyList_New(0);
-
- if (overlap == NULL) {
- /* pass */
- }
- else {
- bool use_unique = (self->orig_index || other->orig_index);
- GSet *pair_test = use_unique ? BLI_gset_new_ex(overlap_hash, overlap_cmp, __func__, overlap_len) : NULL;
- /* simple case, no index remapping */
- unsigned int i;
-
- for (i = 0; i < overlap_len; i++) {
- PyObject *item;
- if (use_unique) {
- if (self->orig_index) {
- overlap[i].indexA = self->orig_index[overlap[i].indexA];
- }
- if (other->orig_index) {
- overlap[i].indexB = other->orig_index[overlap[i].indexB];
- }
-
- /* skip if its already added */
- if (!BLI_gset_add(pair_test, &overlap[i])) {
- continue;
- }
- }
-
- item = PyTuple_New(2);
- PyTuple_SET_ITEMS(item,
- PyLong_FromLong(overlap[i].indexA),
- PyLong_FromLong(overlap[i].indexB));
-
- PyList_Append(ret, item);
- Py_DECREF(item);
- }
-
- if (pair_test) {
- BLI_gset_free(pair_test, NULL);
- }
- }
-
- if (overlap) {
- MEM_freeN(overlap);
- }
-
- return ret;
+ struct PyBVHTree_OverlapData data;
+ BVHTreeOverlap *overlap;
+ unsigned int overlap_len = 0;
+ PyObject *ret;
+
+ if (!PyBVHTree_CheckExact(other)) {
+ PyErr_SetString(PyExc_ValueError, "Expected a BVHTree argument");
+ return NULL;
+ }
+
+ data.tree_pair[0] = self;
+ data.tree_pair[1] = other;
+ data.epsilon = max_ff(self->epsilon, other->epsilon);
+
+ overlap = BLI_bvhtree_overlap(
+ self->tree, other->tree, &overlap_len, py_bvhtree_overlap_cb, &data);
+
+ ret = PyList_New(0);
+
+ if (overlap == NULL) {
+ /* pass */
+ }
+ else {
+ bool use_unique = (self->orig_index || other->orig_index);
+ GSet *pair_test = use_unique ?
+ BLI_gset_new_ex(overlap_hash, overlap_cmp, __func__, overlap_len) :
+ NULL;
+ /* simple case, no index remapping */
+ unsigned int i;
+
+ for (i = 0; i < overlap_len; i++) {
+ PyObject *item;
+ if (use_unique) {
+ if (self->orig_index) {
+ overlap[i].indexA = self->orig_index[overlap[i].indexA];
+ }
+ if (other->orig_index) {
+ overlap[i].indexB = other->orig_index[overlap[i].indexB];
+ }
+
+ /* skip if its already added */
+ if (!BLI_gset_add(pair_test, &overlap[i])) {
+ continue;
+ }
+ }
+
+ item = PyTuple_New(2);
+ PyTuple_SET_ITEMS(
+ item, PyLong_FromLong(overlap[i].indexA), PyLong_FromLong(overlap[i].indexB));
+
+ PyList_Append(ret, item);
+ Py_DECREF(item);
+ }
+
+ if (pair_test) {
+ BLI_gset_free(pair_test, NULL);
+ }
+ }
+
+ if (overlap) {
+ MEM_freeN(overlap);
+ }
+
+ return ret;
}
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Class Methods
* \{ */
-PyDoc_STRVAR(C_BVHTree_FromPolygons_doc,
-".. classmethod:: FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)\n"
-"\n"
-" BVH tree constructed geometry passed in as arguments.\n"
-"\n"
-" :arg vertices: float triplets each representing ``(x, y, z)``\n"
-" :type vertices: float triplet sequence\n"
-" :arg polygons: Sequence of polyugons, each containing indices to the vertices argument.\n"
-" :type polygons: Sequence of sequences containing ints\n"
-" :arg all_triangles: Use when all **polygons** are triangles for more efficient conversion.\n"
-" :type all_triangles: bool\n"
-PYBVH_FROM_GENERIC_EPSILON_DOC
-);
+PyDoc_STRVAR(
+ C_BVHTree_FromPolygons_doc,
+ ".. classmethod:: FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)\n"
+ "\n"
+ " BVH tree constructed geometry passed in as arguments.\n"
+ "\n"
+ " :arg vertices: float triplets each representing ``(x, y, z)``\n"
+ " :type vertices: float triplet sequence\n"
+ " :arg polygons: Sequence of polyugons, each containing indices to the vertices argument.\n"
+ " :type polygons: Sequence of sequences containing ints\n"
+ " :arg all_triangles: Use when all **polygons** are triangles for more efficient "
+ "conversion.\n"
+ " :type all_triangles: bool\n" PYBVH_FROM_GENERIC_EPSILON_DOC);
static PyObject *C_BVHTree_FromPolygons(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
{
- const char *error_prefix = "BVHTree.FromPolygons";
- const char *keywords[] = {"vertices", "polygons", "all_triangles", "epsilon", NULL};
-
- PyObject *py_coords, *py_tris;
- PyObject *py_coords_fast = NULL, *py_tris_fast = NULL;
-
- MemArena *poly_arena = NULL;
- MemArena *pf_arena = NULL;
-
- float (*coords)[3] = NULL;
- unsigned int (*tris)[3] = NULL;
- unsigned int coords_len, tris_len;
- float epsilon = 0.0f;
- bool all_triangles = false;
-
- /* when all_triangles is False */
- int *orig_index = NULL;
- float (*orig_normal)[3] = NULL;
-
- unsigned int i;
- bool valid = true;
-
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *)"OO|$O&f:BVHTree.FromPolygons", (char **)keywords,
- &py_coords, &py_tris,
- PyC_ParseBool, &all_triangles,
- &epsilon))
- {
- return NULL;
- }
-
- if (!(py_coords_fast = PySequence_Fast(py_coords, error_prefix)) ||
- !(py_tris_fast = PySequence_Fast(py_tris, error_prefix)))
- {
- Py_XDECREF(py_coords_fast);
- return NULL;
- }
-
- if (valid) {
- PyObject **py_coords_fast_items = PySequence_Fast_ITEMS(py_coords_fast);
- coords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_coords_fast);
- coords = MEM_mallocN((size_t)coords_len * sizeof(*coords), __func__);
-
- for (i = 0; i < coords_len; i++) {
- PyObject *py_vert = py_coords_fast_items[i];
-
- if (mathutils_array_parse(coords[i], 3, 3, py_vert, "BVHTree vertex: ") == -1) {
- valid = false;
- break;
- }
- }
- }
-
- if (valid == false) {
- /* pass */
- }
- else if (all_triangles) {
- /* all triangles, simple case */
- PyObject **py_tris_fast_items = PySequence_Fast_ITEMS(py_tris_fast);
- tris_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
- tris = MEM_mallocN((size_t)tris_len * sizeof(*tris), __func__);
-
- for (i = 0; i < tris_len; i++) {
- PyObject *py_tricoords = py_tris_fast_items[i];
- PyObject *py_tricoords_fast;
- PyObject **py_tricoords_fast_items;
- unsigned int *tri = tris[i];
- int j;
-
- if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
- valid = false;
- break;
- }
-
- if (PySequence_Fast_GET_SIZE(py_tricoords_fast) != 3) {
- Py_DECREF(py_tricoords_fast);
- PyErr_Format(PyExc_ValueError,
- "%s: non triangle found at index %d with length of %d",
- error_prefix, i, PySequence_Fast_GET_SIZE(py_tricoords_fast));
- valid = false;
- break;
- }
-
- py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
-
- for (j = 0; j < 3; j++) {
- tri[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
- if (UNLIKELY(tri[j] >= (unsigned int)coords_len)) {
- PyErr_Format(PyExc_ValueError,
- "%s: index %d must be less than %d",
- error_prefix, tri[j], coords_len);
-
- /* decref below */
- valid = false;
- break;
- }
- }
-
- Py_DECREF(py_tricoords_fast);
- }
- }
- else {
- /* ngon support (much more involved) */
- const unsigned int polys_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
- struct PolyLink {
- struct PolyLink *next;
- unsigned int len;
- unsigned int poly[0];
- } *plink_first = NULL, **p_plink_prev = &plink_first, *plink = NULL;
- int poly_index;
-
- tris_len = 0;
-
- poly_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
-
- for (i = 0; i < polys_len; i++) {
- PyObject *py_tricoords = PySequence_Fast_GET_ITEM(py_tris_fast, i);
- PyObject *py_tricoords_fast;
- PyObject **py_tricoords_fast_items;
- unsigned int py_tricoords_len;
- unsigned int j;
-
- if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
- valid = false;
- break;
- }
-
- py_tricoords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tricoords_fast);
- py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
-
- plink = BLI_memarena_alloc(poly_arena, sizeof(*plink) + (sizeof(int) * (size_t)py_tricoords_len));
-
- plink->len = (unsigned int)py_tricoords_len;
- *p_plink_prev = plink;
- p_plink_prev = &plink->next;
-
- for (j = 0; j < py_tricoords_len; j++) {
- plink->poly[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
- if (UNLIKELY(plink->poly[j] >= (unsigned int)coords_len)) {
- PyErr_Format(PyExc_ValueError,
- "%s: index %d must be less than %d",
- error_prefix, plink->poly[j], coords_len);
- /* decref below */
- valid = false;
- break;
- }
- }
-
- Py_DECREF(py_tricoords_fast);
-
- if (py_tricoords_len >= 3) {
- tris_len += (py_tricoords_len - 2);
- }
- }
- *p_plink_prev = NULL;
-
- /* all ngon's are parsed, now tessellate */
-
- pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
- tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
-
- orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
- orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)polys_len, __func__);
-
- for (plink = plink_first, poly_index = 0, i = 0; plink; plink = plink->next, poly_index++) {
- if (plink->len == 3) {
- unsigned int *tri = tris[i];
- memcpy(tri, plink->poly, sizeof(unsigned int[3]));
- orig_index[i] = poly_index;
- normal_tri_v3(orig_normal[poly_index], coords[tri[0]], coords[tri[1]], coords[tri[2]]);
- i++;
- }
- else if (plink->len > 3) {
- float (*proj_coords)[2] = BLI_memarena_alloc(pf_arena, sizeof(*proj_coords) * plink->len);
- float *normal = orig_normal[poly_index];
- const float *co_prev;
- const float *co_curr;
- float axis_mat[3][3];
- unsigned int (*tris_offset)[3] = &tris[i];
- unsigned int j;
-
- /* calc normal and setup 'proj_coords' */
- zero_v3(normal);
- co_prev = coords[plink->poly[plink->len - 1]];
- for (j = 0; j < plink->len; j++) {
- co_curr = coords[plink->poly[j]];
- add_newell_cross_v3_v3v3(normal, co_prev, co_curr);
- co_prev = co_curr;
- }
- normalize_v3(normal);
-
- axis_dominant_v3_to_m3_negate(axis_mat, normal);
-
- for (j = 0; j < plink->len; j++) {
- mul_v2_m3v3(proj_coords[j], axis_mat, coords[plink->poly[j]]);
- }
-
- BLI_polyfill_calc_arena(proj_coords, plink->len, 1, tris_offset, pf_arena);
-
- j = plink->len - 2;
- while (j--) {
- unsigned int *tri = tris_offset[j];
- /* remap to global indices */
- tri[0] = plink->poly[tri[0]];
- tri[1] = plink->poly[tri[1]];
- tri[2] = plink->poly[tri[2]];
-
- orig_index[i] = poly_index;
- i++;
- }
-
- BLI_memarena_clear(pf_arena);
- }
- else {
- zero_v3(orig_normal[poly_index]);
- }
- }
- }
-
- Py_DECREF(py_coords_fast);
- Py_DECREF(py_tris_fast);
-
- if (pf_arena) {
- BLI_memarena_free(pf_arena);
- }
-
- if (poly_arena) {
- BLI_memarena_free(poly_arena);
- }
-
- if (valid) {
- BVHTree *tree;
-
- tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
- if (tree) {
- for (i = 0; i < tris_len; i++) {
- float co[3][3];
-
- copy_v3_v3(co[0], coords[tris[i][0]]);
- copy_v3_v3(co[1], coords[tris[i][1]]);
- copy_v3_v3(co[2], coords[tris[i][2]]);
-
- BLI_bvhtree_insert(tree, (int)i, co[0], 3);
- }
-
- BLI_bvhtree_balance(tree);
- }
-
- return bvhtree_CreatePyObject(
- tree, epsilon,
- coords, coords_len,
- tris, tris_len,
- orig_index, orig_normal);
- }
- else {
- if (coords) {
- MEM_freeN(coords);
- }
- if (tris) {
- MEM_freeN(tris);
- }
-
- return NULL;
- }
+ const char *error_prefix = "BVHTree.FromPolygons";
+ const char *keywords[] = {"vertices", "polygons", "all_triangles", "epsilon", NULL};
+
+ PyObject *py_coords, *py_tris;
+ PyObject *py_coords_fast = NULL, *py_tris_fast = NULL;
+
+ MemArena *poly_arena = NULL;
+ MemArena *pf_arena = NULL;
+
+ float(*coords)[3] = NULL;
+ unsigned int(*tris)[3] = NULL;
+ unsigned int coords_len, tris_len;
+ float epsilon = 0.0f;
+ bool all_triangles = false;
+
+ /* when all_triangles is False */
+ int *orig_index = NULL;
+ float(*orig_normal)[3] = NULL;
+
+ unsigned int i;
+ bool valid = true;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kwargs,
+ (char *)"OO|$O&f:BVHTree.FromPolygons",
+ (char **)keywords,
+ &py_coords,
+ &py_tris,
+ PyC_ParseBool,
+ &all_triangles,
+ &epsilon)) {
+ return NULL;
+ }
+
+ if (!(py_coords_fast = PySequence_Fast(py_coords, error_prefix)) ||
+ !(py_tris_fast = PySequence_Fast(py_tris, error_prefix))) {
+ Py_XDECREF(py_coords_fast);
+ return NULL;
+ }
+
+ if (valid) {
+ PyObject **py_coords_fast_items = PySequence_Fast_ITEMS(py_coords_fast);
+ coords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_coords_fast);
+ coords = MEM_mallocN((size_t)coords_len * sizeof(*coords), __func__);
+
+ for (i = 0; i < coords_len; i++) {
+ PyObject *py_vert = py_coords_fast_items[i];
+
+ if (mathutils_array_parse(coords[i], 3, 3, py_vert, "BVHTree vertex: ") == -1) {
+ valid = false;
+ break;
+ }
+ }
+ }
+
+ if (valid == false) {
+ /* pass */
+ }
+ else if (all_triangles) {
+ /* all triangles, simple case */
+ PyObject **py_tris_fast_items = PySequence_Fast_ITEMS(py_tris_fast);
+ tris_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
+ tris = MEM_mallocN((size_t)tris_len * sizeof(*tris), __func__);
+
+ for (i = 0; i < tris_len; i++) {
+ PyObject *py_tricoords = py_tris_fast_items[i];
+ PyObject *py_tricoords_fast;
+ PyObject **py_tricoords_fast_items;
+ unsigned int *tri = tris[i];
+ int j;
+
+ if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
+ valid = false;
+ break;
+ }
+
+ if (PySequence_Fast_GET_SIZE(py_tricoords_fast) != 3) {
+ Py_DECREF(py_tricoords_fast);
+ PyErr_Format(PyExc_ValueError,
+ "%s: non triangle found at index %d with length of %d",
+ error_prefix,
+ i,
+ PySequence_Fast_GET_SIZE(py_tricoords_fast));
+ valid = false;
+ break;
+ }
+
+ py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
+
+ for (j = 0; j < 3; j++) {
+ tri[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
+ if (UNLIKELY(tri[j] >= (unsigned int)coords_len)) {
+ PyErr_Format(PyExc_ValueError,
+ "%s: index %d must be less than %d",
+ error_prefix,
+ tri[j],
+ coords_len);
+
+ /* decref below */
+ valid = false;
+ break;
+ }
+ }
+
+ Py_DECREF(py_tricoords_fast);
+ }
+ }
+ else {
+ /* ngon support (much more involved) */
+ const unsigned int polys_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tris_fast);
+ struct PolyLink {
+ struct PolyLink *next;
+ unsigned int len;
+ unsigned int poly[0];
+ } *plink_first = NULL, **p_plink_prev = &plink_first, *plink = NULL;
+ int poly_index;
+
+ tris_len = 0;
+
+ poly_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
+
+ for (i = 0; i < polys_len; i++) {
+ PyObject *py_tricoords = PySequence_Fast_GET_ITEM(py_tris_fast, i);
+ PyObject *py_tricoords_fast;
+ PyObject **py_tricoords_fast_items;
+ unsigned int py_tricoords_len;
+ unsigned int j;
+
+ if (!(py_tricoords_fast = PySequence_Fast(py_tricoords, error_prefix))) {
+ valid = false;
+ break;
+ }
+
+ py_tricoords_len = (unsigned int)PySequence_Fast_GET_SIZE(py_tricoords_fast);
+ py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
+
+ plink = BLI_memarena_alloc(poly_arena,
+ sizeof(*plink) + (sizeof(int) * (size_t)py_tricoords_len));
+
+ plink->len = (unsigned int)py_tricoords_len;
+ *p_plink_prev = plink;
+ p_plink_prev = &plink->next;
+
+ for (j = 0; j < py_tricoords_len; j++) {
+ plink->poly[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
+ if (UNLIKELY(plink->poly[j] >= (unsigned int)coords_len)) {
+ PyErr_Format(PyExc_ValueError,
+ "%s: index %d must be less than %d",
+ error_prefix,
+ plink->poly[j],
+ coords_len);
+ /* decref below */
+ valid = false;
+ break;
+ }
+ }
+
+ Py_DECREF(py_tricoords_fast);
+
+ if (py_tricoords_len >= 3) {
+ tris_len += (py_tricoords_len - 2);
+ }
+ }
+ *p_plink_prev = NULL;
+
+ /* all ngon's are parsed, now tessellate */
+
+ pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
+ tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
+
+ orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
+ orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)polys_len, __func__);
+
+ for (plink = plink_first, poly_index = 0, i = 0; plink; plink = plink->next, poly_index++) {
+ if (plink->len == 3) {
+ unsigned int *tri = tris[i];
+ memcpy(tri, plink->poly, sizeof(unsigned int[3]));
+ orig_index[i] = poly_index;
+ normal_tri_v3(orig_normal[poly_index], coords[tri[0]], coords[tri[1]], coords[tri[2]]);
+ i++;
+ }
+ else if (plink->len > 3) {
+ float(*proj_coords)[2] = BLI_memarena_alloc(pf_arena, sizeof(*proj_coords) * plink->len);
+ float *normal = orig_normal[poly_index];
+ const float *co_prev;
+ const float *co_curr;
+ float axis_mat[3][3];
+ unsigned int(*tris_offset)[3] = &tris[i];
+ unsigned int j;
+
+ /* calc normal and setup 'proj_coords' */
+ zero_v3(normal);
+ co_prev = coords[plink->poly[plink->len - 1]];
+ for (j = 0; j < plink->len; j++) {
+ co_curr = coords[plink->poly[j]];
+ add_newell_cross_v3_v3v3(normal, co_prev, co_curr);
+ co_prev = co_curr;
+ }
+ normalize_v3(normal);
+
+ axis_dominant_v3_to_m3_negate(axis_mat, normal);
+
+ for (j = 0; j < plink->len; j++) {
+ mul_v2_m3v3(proj_coords[j], axis_mat, coords[plink->poly[j]]);
+ }
+
+ BLI_polyfill_calc_arena(proj_coords, plink->len, 1, tris_offset, pf_arena);
+
+ j = plink->len - 2;
+ while (j--) {
+ unsigned int *tri = tris_offset[j];
+ /* remap to global indices */
+ tri[0] = plink->poly[tri[0]];
+ tri[1] = plink->poly[tri[1]];
+ tri[2] = plink->poly[tri[2]];
+
+ orig_index[i] = poly_index;
+ i++;
+ }
+
+ BLI_memarena_clear(pf_arena);
+ }
+ else {
+ zero_v3(orig_normal[poly_index]);
+ }
+ }
+ }
+
+ Py_DECREF(py_coords_fast);
+ Py_DECREF(py_tris_fast);
+
+ if (pf_arena) {
+ BLI_memarena_free(pf_arena);
+ }
+
+ if (poly_arena) {
+ BLI_memarena_free(poly_arena);
+ }
+
+ if (valid) {
+ BVHTree *tree;
+
+ tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
+ if (tree) {
+ for (i = 0; i < tris_len; i++) {
+ float co[3][3];
+
+ copy_v3_v3(co[0], coords[tris[i][0]]);
+ copy_v3_v3(co[1], coords[tris[i][1]]);
+ copy_v3_v3(co[2], coords[tris[i][2]]);
+
+ BLI_bvhtree_insert(tree, (int)i, co[0], 3);
+ }
+
+ BLI_bvhtree_balance(tree);
+ }
+
+ return bvhtree_CreatePyObject(
+ tree, epsilon, coords, coords_len, tris, tris_len, orig_index, orig_normal);
+ }
+ else {
+ if (coords) {
+ MEM_freeN(coords);
+ }
+ if (tris) {
+ MEM_freeN(tris);
+ }
+
+ return NULL;
+ }
}
-
#ifndef MATH_STANDALONE
PyDoc_STRVAR(C_BVHTree_FromBMesh_doc,
-".. classmethod:: FromBMesh(bmesh, epsilon=0.0)\n"
-"\n"
-" BVH tree based on :class:`BMesh` data.\n"
-"\n"
-" :arg bmesh: BMesh data.\n"
-" :type bmesh: :class:`BMesh`\n"
-PYBVH_FROM_GENERIC_EPSILON_DOC
-);
+ ".. classmethod:: FromBMesh(bmesh, epsilon=0.0)\n"
+ "\n"
+ " BVH tree based on :class:`BMesh` data.\n"
+ "\n"
+ " :arg bmesh: BMesh data.\n"
+ " :type bmesh: :class:`BMesh`\n" PYBVH_FROM_GENERIC_EPSILON_DOC);
static PyObject *C_BVHTree_FromBMesh(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
{
- const char *keywords[] = {"bmesh", "epsilon", NULL};
+ const char *keywords[] = {"bmesh", "epsilon", NULL};
- BPy_BMesh *py_bm;
+ BPy_BMesh *py_bm;
- float (*coords)[3] = NULL;
- unsigned int (*tris)[3] = NULL;
- unsigned int coords_len, tris_len;
- float epsilon = 0.0f;
+ float(*coords)[3] = NULL;
+ unsigned int(*tris)[3] = NULL;
+ unsigned int coords_len, tris_len;
+ float epsilon = 0.0f;
- BMesh *bm;
- BMLoop *(*looptris)[3];
+ BMesh *bm;
+ BMLoop *(*looptris)[3];
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *)"O!|$f:BVHTree.FromBMesh", (char **)keywords,
- &BPy_BMesh_Type, &py_bm, &epsilon))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kwargs,
+ (char *)"O!|$f:BVHTree.FromBMesh",
+ (char **)keywords,
+ &BPy_BMesh_Type,
+ &py_bm,
+ &epsilon)) {
+ return NULL;
+ }
- bm = py_bm->bm;
+ bm = py_bm->bm;
- /* Get data for tessellation */
- {
- int tris_len_dummy;
+ /* Get data for tessellation */
+ {
+ int tris_len_dummy;
- coords_len = (unsigned int)bm->totvert;
- tris_len = (unsigned int)poly_to_tri_count(bm->totface, bm->totloop);
+ coords_len = (unsigned int)bm->totvert;
+ tris_len = (unsigned int)poly_to_tri_count(bm->totface, bm->totloop);
- coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
- tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
+ coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
+ tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
- looptris = MEM_mallocN(sizeof(*looptris) * (size_t)tris_len, __func__);
+ looptris = MEM_mallocN(sizeof(*looptris) * (size_t)tris_len, __func__);
- BM_mesh_calc_tessellation(bm, looptris, &tris_len_dummy);
- BLI_assert(tris_len_dummy == (int)tris_len);
- }
+ BM_mesh_calc_tessellation(bm, looptris, &tris_len_dummy);
+ BLI_assert(tris_len_dummy == (int)tris_len);
+ }
- {
- BMIter iter;
- BVHTree *tree;
- unsigned int i;
+ {
+ BMIter iter;
+ BVHTree *tree;
+ unsigned int i;
- int *orig_index = NULL;
- float (*orig_normal)[3] = NULL;
+ int *orig_index = NULL;
+ float(*orig_normal)[3] = NULL;
- tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
- if (tree) {
- BMFace *f;
- BMVert *v;
+ tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
+ if (tree) {
+ BMFace *f;
+ BMVert *v;
- orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
- orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)bm->totface, __func__);
+ orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
+ orig_normal = MEM_mallocN(sizeof(*orig_normal) * (size_t)bm->totface, __func__);
- BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
- copy_v3_v3(coords[i], v->co);
- BM_elem_index_set(v, (int)i); /* set_inline */
- }
- BM_ITER_MESH_INDEX (f, &iter, bm, BM_FACES_OF_MESH, i) {
- copy_v3_v3(orig_normal[i], f->no);
- BM_elem_index_set(f, (int)i); /* set_inline */
- }
- bm->elem_index_dirty &= (char)~(BM_VERT | BM_FACE);
+ BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
+ copy_v3_v3(coords[i], v->co);
+ BM_elem_index_set(v, (int)i); /* set_inline */
+ }
+ BM_ITER_MESH_INDEX (f, &iter, bm, BM_FACES_OF_MESH, i) {
+ copy_v3_v3(orig_normal[i], f->no);
+ BM_elem_index_set(f, (int)i); /* set_inline */
+ }
+ bm->elem_index_dirty &= (char)~(BM_VERT | BM_FACE);
- for (i = 0; i < tris_len; i++) {
- float co[3][3];
+ for (i = 0; i < tris_len; i++) {
+ float co[3][3];
- tris[i][0] = (unsigned int)BM_elem_index_get(looptris[i][0]->v);
- tris[i][1] = (unsigned int)BM_elem_index_get(looptris[i][1]->v);
- tris[i][2] = (unsigned int)BM_elem_index_get(looptris[i][2]->v);
+ tris[i][0] = (unsigned int)BM_elem_index_get(looptris[i][0]->v);
+ tris[i][1] = (unsigned int)BM_elem_index_get(looptris[i][1]->v);
+ tris[i][2] = (unsigned int)BM_elem_index_get(looptris[i][2]->v);
- copy_v3_v3(co[0], coords[tris[i][0]]);
- copy_v3_v3(co[1], coords[tris[i][1]]);
- copy_v3_v3(co[2], coords[tris[i][2]]);
+ copy_v3_v3(co[0], coords[tris[i][0]]);
+ copy_v3_v3(co[1], coords[tris[i][1]]);
+ copy_v3_v3(co[2], coords[tris[i][2]]);
- BLI_bvhtree_insert(tree, (int)i, co[0], 3);
- orig_index[i] = BM_elem_index_get(looptris[i][0]->f);
- }
+ BLI_bvhtree_insert(tree, (int)i, co[0], 3);
+ orig_index[i] = BM_elem_index_get(looptris[i][0]->f);
+ }
- BLI_bvhtree_balance(tree);
- }
+ BLI_bvhtree_balance(tree);
+ }
- MEM_freeN(looptris);
+ MEM_freeN(looptris);
- return bvhtree_CreatePyObject(
- tree, epsilon,
- coords, coords_len,
- tris, tris_len,
- orig_index, orig_normal);
- }
+ return bvhtree_CreatePyObject(
+ tree, epsilon, coords, coords_len, tris, tris_len, orig_index, orig_normal);
+ }
}
/* return various derived meshes based on requested settings */
-static Mesh *bvh_get_mesh(
- const char *funcname, struct Depsgraph *depsgraph, struct Scene *scene, Object *ob,
- const bool use_deform, const bool use_cage, bool *r_free_mesh)
+static Mesh *bvh_get_mesh(const char *funcname,
+ struct Depsgraph *depsgraph,
+ struct Scene *scene,
+ Object *ob,
+ const bool use_deform,
+ const bool use_cage,
+ bool *r_free_mesh)
{
- Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
- /* we only need minimum mesh data for topology and vertex locations */
- CustomData_MeshMasks data_masks = CD_MASK_BAREMESH;
- const bool use_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER;
- *r_free_mesh = false;
-
- /* Write the display mesh into the dummy mesh */
- if (use_deform) {
- if (use_render) {
- if (use_cage) {
- PyErr_Format(PyExc_ValueError,
- "%s(...): cage arg is unsupported when dependency graph evaluation mode is RENDER", funcname);
- return NULL;
- }
- else {
- *r_free_mesh = true;
- return mesh_create_eval_final_render(depsgraph, scene, ob, &data_masks);
- }
- }
- else if (ob_eval != NULL) {
- if (use_cage) {
- return mesh_get_eval_deform(depsgraph, scene, ob_eval, &data_masks);
- }
- else {
- return mesh_get_eval_final(depsgraph, scene, ob_eval, &data_masks);
- }
- }
- else {
- PyErr_Format(PyExc_ValueError,
- "%s(...): Cannot get evaluated data from given dependency graph / object pair", funcname);
- return NULL;
- }
- }
- else {
- /* !use_deform */
- if (use_render) {
- if (use_cage) {
- PyErr_Format(PyExc_ValueError,
- "%s(...): cage arg is unsupported when dependency graph evaluation mode is RENDER", funcname);
- return NULL;
- }
- else {
- *r_free_mesh = true;
- return mesh_create_eval_no_deform_render(depsgraph, scene, ob, &data_masks);
- }
- }
- else {
- if (use_cage) {
- PyErr_Format(PyExc_ValueError,
- "%s(...): cage arg is unsupported when deform=False and dependency graph evaluation mode is not RENDER", funcname);
- return NULL;
- }
- else {
- *r_free_mesh = true;
- return mesh_create_eval_no_deform(depsgraph, scene, ob, &data_masks);
- }
- }
- }
+ Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
+ /* we only need minimum mesh data for topology and vertex locations */
+ CustomData_MeshMasks data_masks = CD_MASK_BAREMESH;
+ const bool use_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER;
+ *r_free_mesh = false;
+
+ /* Write the display mesh into the dummy mesh */
+ if (use_deform) {
+ if (use_render) {
+ if (use_cage) {
+ PyErr_Format(
+ PyExc_ValueError,
+ "%s(...): cage arg is unsupported when dependency graph evaluation mode is RENDER",
+ funcname);
+ return NULL;
+ }
+ else {
+ *r_free_mesh = true;
+ return mesh_create_eval_final_render(depsgraph, scene, ob, &data_masks);
+ }
+ }
+ else if (ob_eval != NULL) {
+ if (use_cage) {
+ return mesh_get_eval_deform(depsgraph, scene, ob_eval, &data_masks);
+ }
+ else {
+ return mesh_get_eval_final(depsgraph, scene, ob_eval, &data_masks);
+ }
+ }
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "%s(...): Cannot get evaluated data from given dependency graph / object pair",
+ funcname);
+ return NULL;
+ }
+ }
+ else {
+ /* !use_deform */
+ if (use_render) {
+ if (use_cage) {
+ PyErr_Format(
+ PyExc_ValueError,
+ "%s(...): cage arg is unsupported when dependency graph evaluation mode is RENDER",
+ funcname);
+ return NULL;
+ }
+ else {
+ *r_free_mesh = true;
+ return mesh_create_eval_no_deform_render(depsgraph, scene, ob, &data_masks);
+ }
+ }
+ else {
+ if (use_cage) {
+ PyErr_Format(PyExc_ValueError,
+ "%s(...): cage arg is unsupported when deform=False and dependency graph "
+ "evaluation mode is not RENDER",
+ funcname);
+ return NULL;
+ }
+ else {
+ *r_free_mesh = true;
+ return mesh_create_eval_no_deform(depsgraph, scene, ob, &data_masks);
+ }
+ }
+ }
}
PyDoc_STRVAR(C_BVHTree_FromObject_doc,
-".. classmethod:: FromObject(object, depsgraph, deform=True, render=False, cage=False, epsilon=0.0)\n"
-"\n"
-" BVH tree based on :class:`Object` data.\n"
-"\n"
-" :arg object: Object data.\n"
-" :type object: :class:`Object`\n"
-" :arg depsgraph: Depsgraph to use for evaluating the mesh.\n"
-" :type depsgraph: :class:`Depsgraph`\n"
-" :arg deform: Use mesh with deformations.\n"
-" :type deform: bool\n"
-" :arg cage: Use modifiers cage.\n"
-" :type cage: bool\n"
-PYBVH_FROM_GENERIC_EPSILON_DOC
-);
+ ".. classmethod:: FromObject(object, depsgraph, deform=True, render=False, "
+ "cage=False, epsilon=0.0)\n"
+ "\n"
+ " BVH tree based on :class:`Object` data.\n"
+ "\n"
+ " :arg object: Object data.\n"
+ " :type object: :class:`Object`\n"
+ " :arg depsgraph: Depsgraph to use for evaluating the mesh.\n"
+ " :type depsgraph: :class:`Depsgraph`\n"
+ " :arg deform: Use mesh with deformations.\n"
+ " :type deform: bool\n"
+ " :arg cage: Use modifiers cage.\n"
+ " :type cage: bool\n" PYBVH_FROM_GENERIC_EPSILON_DOC);
static PyObject *C_BVHTree_FromObject(PyObject *UNUSED(cls), PyObject *args, PyObject *kwargs)
{
- /* note, options here match 'bpy_bmesh_from_object' */
- const char *keywords[] = {"object", "depsgraph", "deform", "cage", "epsilon", NULL};
-
- PyObject *py_ob, *py_depsgraph;
- Object *ob;
- struct Depsgraph *depsgraph;
- struct Scene *scene;
- Mesh *mesh;
- bool use_deform = true;
- bool use_cage = false;
- bool free_mesh = false;
-
- const MLoopTri *lt;
- const MLoop *mloop;
-
- float (*coords)[3] = NULL;
- unsigned int (*tris)[3] = NULL;
- unsigned int coords_len, tris_len;
- float epsilon = 0.0f;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *)"OO|$O&O&f:BVHTree.FromObject", (char **)keywords,
- &py_ob, &py_depsgraph,
- PyC_ParseBool, &use_deform,
- PyC_ParseBool, &use_cage,
- &epsilon) ||
- ((ob = PyC_RNA_AsPointer(py_ob, "Object")) == NULL) ||
- ((depsgraph = PyC_RNA_AsPointer(py_depsgraph, "Depsgraph")) == NULL))
- {
- return NULL;
- }
-
- scene = DEG_get_evaluated_scene(depsgraph);
- mesh = bvh_get_mesh("BVHTree", depsgraph, scene, ob, use_deform, use_cage, &free_mesh);
-
- if (mesh == NULL) {
- return NULL;
- }
-
- /* Get data for tessellation */
- {
- lt = BKE_mesh_runtime_looptri_ensure(mesh);
-
- tris_len = (unsigned int)BKE_mesh_runtime_looptri_len(mesh);
- coords_len = (unsigned int)mesh->totvert;
-
- coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
- tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
-
- MVert *mv = mesh->mvert;
- for (int i = 0; i < mesh->totvert; i++, mv++) {
- copy_v3_v3(coords[i], mv->co);
- }
-
- mloop = mesh->mloop;
- }
-
- {
- BVHTree *tree;
- unsigned int i;
-
- int *orig_index = NULL;
- float (*orig_normal)[3] = NULL;
-
- tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
- if (tree) {
- orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
- CustomData *pdata = &mesh->pdata;
- orig_normal = CustomData_get_layer(pdata, CD_NORMAL); /* can be NULL */
- if (orig_normal) {
- orig_normal = MEM_dupallocN(orig_normal);
- }
-
- for (i = 0; i < tris_len; i++, lt++) {
- float co[3][3];
-
- tris[i][0] = mloop[lt->tri[0]].v;
- tris[i][1] = mloop[lt->tri[1]].v;
- tris[i][2] = mloop[lt->tri[2]].v;
-
- copy_v3_v3(co[0], coords[tris[i][0]]);
- copy_v3_v3(co[1], coords[tris[i][1]]);
- copy_v3_v3(co[2], coords[tris[i][2]]);
-
- BLI_bvhtree_insert(tree, (int)i, co[0], 3);
- orig_index[i] = (int)lt->poly;
- }
-
- BLI_bvhtree_balance(tree);
- }
-
- if (free_mesh) {
- BKE_id_free(NULL, mesh);
- }
-
- return bvhtree_CreatePyObject(
- tree, epsilon,
- coords, coords_len,
- tris, tris_len,
- orig_index, orig_normal);
- }
+ /* note, options here match 'bpy_bmesh_from_object' */
+ const char *keywords[] = {"object", "depsgraph", "deform", "cage", "epsilon", NULL};
+
+ PyObject *py_ob, *py_depsgraph;
+ Object *ob;
+ struct Depsgraph *depsgraph;
+ struct Scene *scene;
+ Mesh *mesh;
+ bool use_deform = true;
+ bool use_cage = false;
+ bool free_mesh = false;
+
+ const MLoopTri *lt;
+ const MLoop *mloop;
+
+ float(*coords)[3] = NULL;
+ unsigned int(*tris)[3] = NULL;
+ unsigned int coords_len, tris_len;
+ float epsilon = 0.0f;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kwargs,
+ (char *)"OO|$O&O&f:BVHTree.FromObject",
+ (char **)keywords,
+ &py_ob,
+ &py_depsgraph,
+ PyC_ParseBool,
+ &use_deform,
+ PyC_ParseBool,
+ &use_cage,
+ &epsilon) ||
+ ((ob = PyC_RNA_AsPointer(py_ob, "Object")) == NULL) ||
+ ((depsgraph = PyC_RNA_AsPointer(py_depsgraph, "Depsgraph")) == NULL)) {
+ return NULL;
+ }
+
+ scene = DEG_get_evaluated_scene(depsgraph);
+ mesh = bvh_get_mesh("BVHTree", depsgraph, scene, ob, use_deform, use_cage, &free_mesh);
+
+ if (mesh == NULL) {
+ return NULL;
+ }
+
+ /* Get data for tessellation */
+ {
+ lt = BKE_mesh_runtime_looptri_ensure(mesh);
+
+ tris_len = (unsigned int)BKE_mesh_runtime_looptri_len(mesh);
+ coords_len = (unsigned int)mesh->totvert;
+
+ coords = MEM_mallocN(sizeof(*coords) * (size_t)coords_len, __func__);
+ tris = MEM_mallocN(sizeof(*tris) * (size_t)tris_len, __func__);
+
+ MVert *mv = mesh->mvert;
+ for (int i = 0; i < mesh->totvert; i++, mv++) {
+ copy_v3_v3(coords[i], mv->co);
+ }
+
+ mloop = mesh->mloop;
+ }
+
+ {
+ BVHTree *tree;
+ unsigned int i;
+
+ int *orig_index = NULL;
+ float(*orig_normal)[3] = NULL;
+
+ tree = BLI_bvhtree_new((int)tris_len, epsilon, PY_BVH_TREE_TYPE_DEFAULT, PY_BVH_AXIS_DEFAULT);
+ if (tree) {
+ orig_index = MEM_mallocN(sizeof(*orig_index) * (size_t)tris_len, __func__);
+ CustomData *pdata = &mesh->pdata;
+ orig_normal = CustomData_get_layer(pdata, CD_NORMAL); /* can be NULL */
+ if (orig_normal) {
+ orig_normal = MEM_dupallocN(orig_normal);
+ }
+
+ for (i = 0; i < tris_len; i++, lt++) {
+ float co[3][3];
+
+ tris[i][0] = mloop[lt->tri[0]].v;
+ tris[i][1] = mloop[lt->tri[1]].v;
+ tris[i][2] = mloop[lt->tri[2]].v;
+
+ copy_v3_v3(co[0], coords[tris[i][0]]);
+ copy_v3_v3(co[1], coords[tris[i][1]]);
+ copy_v3_v3(co[2], coords[tris[i][2]]);
+
+ BLI_bvhtree_insert(tree, (int)i, co[0], 3);
+ orig_index[i] = (int)lt->poly;
+ }
+
+ BLI_bvhtree_balance(tree);
+ }
+
+ if (free_mesh) {
+ BKE_id_free(NULL, mesh);
+ }
+
+ return bvhtree_CreatePyObject(
+ tree, epsilon, coords, coords_len, tris, tris_len, orig_index, orig_normal);
+ }
}
-#endif /* MATH_STANDALONE */
+#endif /* MATH_STANDALONE */
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Module & Type definition
* \{ */
static PyMethodDef py_bvhtree_methods[] = {
- {"ray_cast", (PyCFunction)py_bvhtree_ray_cast, METH_VARARGS, py_bvhtree_ray_cast_doc},
- {"find_nearest", (PyCFunction)py_bvhtree_find_nearest, METH_VARARGS, py_bvhtree_find_nearest_doc},
- {"find_nearest_range", (PyCFunction)py_bvhtree_find_nearest_range, METH_VARARGS, py_bvhtree_find_nearest_range_doc},
- {"overlap", (PyCFunction)py_bvhtree_overlap, METH_O, py_bvhtree_overlap_doc},
-
- /* class methods */
- {"FromPolygons", (PyCFunction) C_BVHTree_FromPolygons, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromPolygons_doc},
+ {"ray_cast", (PyCFunction)py_bvhtree_ray_cast, METH_VARARGS, py_bvhtree_ray_cast_doc},
+ {"find_nearest",
+ (PyCFunction)py_bvhtree_find_nearest,
+ METH_VARARGS,
+ py_bvhtree_find_nearest_doc},
+ {"find_nearest_range",
+ (PyCFunction)py_bvhtree_find_nearest_range,
+ METH_VARARGS,
+ py_bvhtree_find_nearest_range_doc},
+ {"overlap", (PyCFunction)py_bvhtree_overlap, METH_O, py_bvhtree_overlap_doc},
+
+ /* class methods */
+ {"FromPolygons",
+ (PyCFunction)C_BVHTree_FromPolygons,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ C_BVHTree_FromPolygons_doc},
#ifndef MATH_STANDALONE
- {"FromBMesh", (PyCFunction) C_BVHTree_FromBMesh, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromBMesh_doc},
- {"FromObject", (PyCFunction) C_BVHTree_FromObject, METH_VARARGS | METH_KEYWORDS | METH_CLASS, C_BVHTree_FromObject_doc},
+ {"FromBMesh",
+ (PyCFunction)C_BVHTree_FromBMesh,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ C_BVHTree_FromBMesh_doc},
+ {"FromObject",
+ (PyCFunction)C_BVHTree_FromObject,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ C_BVHTree_FromObject_doc},
#endif
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
PyTypeObject PyBVHTree_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "BVHTree", /* tp_name */
- sizeof(PyBVHTree), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)py_bvhtree__tp_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- NULL, /* tp_repr */
- NULL, /* tp_as_number */
- NULL, /* tp_as_sequence */
- NULL, /* tp_as_mapping */
- NULL, /* tp_hash */
- NULL, /* tp_call */
- NULL, /* tp_str */
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- NULL, /* Documentation string */
- NULL, /* tp_traverse */
- NULL, /* tp_clear */
- NULL, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- py_bvhtree_methods, /* tp_methods */
- NULL, /* tp_members */
- NULL, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- NULL, /* tp_init */
- (allocfunc)PyType_GenericAlloc, /* tp_alloc */
- (newfunc)PyType_GenericNew, /* tp_new */
- (freefunc)0, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- (destructor)NULL, /* tp_del */
+ PyVarObject_HEAD_INIT(NULL, 0) "BVHTree", /* tp_name */
+ sizeof(PyBVHTree), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)py_bvhtree__tp_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ NULL, /* tp_repr */
+ NULL, /* tp_as_number */
+ NULL, /* tp_as_sequence */
+ NULL, /* tp_as_mapping */
+ NULL, /* tp_hash */
+ NULL, /* tp_call */
+ NULL, /* tp_str */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ NULL, /* Documentation string */
+ NULL, /* tp_traverse */
+ NULL, /* tp_clear */
+ NULL, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ py_bvhtree_methods, /* tp_methods */
+ NULL, /* tp_members */
+ NULL, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ NULL, /* tp_init */
+ (allocfunc)PyType_GenericAlloc, /* tp_alloc */
+ (newfunc)PyType_GenericNew, /* tp_new */
+ (freefunc)0, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ (destructor)NULL, /* tp_del */
};
/* -------------------------------------------------------------------- */
/* Module definition */
PyDoc_STRVAR(py_bvhtree_doc,
-"BVH tree structures for proximity searches and ray casts on geometry."
-);
+ "BVH tree structures for proximity searches and ray casts on geometry.");
static struct PyModuleDef bvhtree_moduledef = {
- PyModuleDef_HEAD_INIT,
- "mathutils.bvhtree", /* m_name */
- py_bvhtree_doc, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils.bvhtree", /* m_name */
+ py_bvhtree_doc, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_mathutils_bvhtree(void)
{
- PyObject *m = PyModule_Create(&bvhtree_moduledef);
+ PyObject *m = PyModule_Create(&bvhtree_moduledef);
- if (m == NULL) {
- return NULL;
- }
+ if (m == NULL) {
+ return NULL;
+ }
- /* Register classes */
- if (PyType_Ready(&PyBVHTree_Type) < 0) {
- return NULL;
- }
+ /* Register classes */
+ if (PyType_Ready(&PyBVHTree_Type) < 0) {
+ return NULL;
+ }
- PyModule_AddObject(m, "BVHTree", (PyObject *)&PyBVHTree_Type);
+ PyModule_AddObject(m, "BVHTree", (PyObject *)&PyBVHTree_Type);
- return m;
+ return m;
}
/** \} */
diff --git a/source/blender/python/mathutils/mathutils_bvhtree.h b/source/blender/python/mathutils/mathutils_bvhtree.h
index 6971eb5ccd4..2991982f3a2 100644
--- a/source/blender/python/mathutils/mathutils_bvhtree.h
+++ b/source/blender/python/mathutils/mathutils_bvhtree.h
@@ -14,7 +14,6 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-
/** \file
* \ingroup mathutils
*/
@@ -26,7 +25,7 @@ PyMODINIT_FUNC PyInit_mathutils_bvhtree(void);
extern PyTypeObject PyBVHTree_Type;
-#define PyBVHTree_Check(v) PyObject_TypeCheck((v), &PyBVHTree_Type)
-#define PyBVHTree_CheckExact(v) (Py_TYPE(v) == &PyBVHTree_Type)
+#define PyBVHTree_Check(v) PyObject_TypeCheck((v), &PyBVHTree_Type)
+#define PyBVHTree_CheckExact(v) (Py_TYPE(v) == &PyBVHTree_Type)
#endif /* __MATHUTILS_BVHTREE_H__ */
diff --git a/source/blender/python/mathutils/mathutils_geometry.c b/source/blender/python/mathutils/mathutils_geometry.c
index 05ec57a004a..5fe3536d899 100644
--- a/source/blender/python/mathutils/mathutils_geometry.c
+++ b/source/blender/python/mathutils/mathutils_geometry.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -41,1497 +40,1534 @@
#include "../generic/python_utildefines.h"
/*-------------------------DOC STRINGS ---------------------------*/
-PyDoc_STRVAR(M_Geometry_doc,
-"The Blender geometry module"
-);
+PyDoc_STRVAR(M_Geometry_doc, "The Blender geometry module");
/* ---------------------------------INTERSECTION FUNCTIONS-------------------- */
PyDoc_STRVAR(M_Geometry_intersect_ray_tri_doc,
-".. function:: intersect_ray_tri(v1, v2, v3, ray, orig, clip=True)\n"
-"\n"
-" Returns the intersection between a ray and a triangle, if possible, returns None otherwise.\n"
-"\n"
-" :arg v1: Point1\n"
-" :type v1: :class:`mathutils.Vector`\n"
-" :arg v2: Point2\n"
-" :type v2: :class:`mathutils.Vector`\n"
-" :arg v3: Point3\n"
-" :type v3: :class:`mathutils.Vector`\n"
-" :arg ray: Direction of the projection\n"
-" :type ray: :class:`mathutils.Vector`\n"
-" :arg orig: Origin\n"
-" :type orig: :class:`mathutils.Vector`\n"
-" :arg clip: When False, don't restrict the intersection to the area of the triangle, use the infinite plane defined by the triangle.\n"
-" :type clip: boolean\n"
-" :return: The point of intersection or None if no intersection is found\n"
-" :rtype: :class:`mathutils.Vector` or None\n"
-);
+ ".. function:: intersect_ray_tri(v1, v2, v3, ray, orig, clip=True)\n"
+ "\n"
+ " Returns the intersection between a ray and a triangle, if possible, returns None "
+ "otherwise.\n"
+ "\n"
+ " :arg v1: Point1\n"
+ " :type v1: :class:`mathutils.Vector`\n"
+ " :arg v2: Point2\n"
+ " :type v2: :class:`mathutils.Vector`\n"
+ " :arg v3: Point3\n"
+ " :type v3: :class:`mathutils.Vector`\n"
+ " :arg ray: Direction of the projection\n"
+ " :type ray: :class:`mathutils.Vector`\n"
+ " :arg orig: Origin\n"
+ " :type orig: :class:`mathutils.Vector`\n"
+ " :arg clip: When False, don't restrict the intersection to the area of the "
+ "triangle, use the infinite plane defined by the triangle.\n"
+ " :type clip: boolean\n"
+ " :return: The point of intersection or None if no intersection is found\n"
+ " :rtype: :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_ray_tri(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_ray_tri";
- PyObject *py_ray, *py_ray_off, *py_tri[3];
- float dir[3], orig[3], tri[3][3], e1[3], e2[3], pvec[3], tvec[3], qvec[3];
- float det, inv_det, u, v, t;
- bool clip = true;
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOOO|O&:intersect_ray_tri",
- UNPACK3_EX(&, py_tri, ),
- &py_ray, &py_ray_off,
- PyC_ParseBool, &clip))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(dir, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_ray, error_prefix) != -1) &&
- (mathutils_array_parse(orig, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_ray_off, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- for (i = 0; i < ARRAY_SIZE(tri); i++) {
- if (mathutils_array_parse(tri[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_tri[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- normalize_v3(dir);
-
- /* find vectors for two edges sharing v1 */
- sub_v3_v3v3(e1, tri[1], tri[0]);
- sub_v3_v3v3(e2, tri[2], tri[0]);
-
- /* begin calculating determinant - also used to calculated U parameter */
- cross_v3_v3v3(pvec, dir, e2);
-
- /* if determinant is near zero, ray lies in plane of triangle */
- det = dot_v3v3(e1, pvec);
-
- if (det > -0.000001f && det < 0.000001f) {
- Py_RETURN_NONE;
- }
-
- inv_det = 1.0f / det;
-
- /* calculate distance from v1 to ray origin */
- sub_v3_v3v3(tvec, orig, tri[0]);
-
- /* calculate U parameter and test bounds */
- u = dot_v3v3(tvec, pvec) * inv_det;
- if (clip && (u < 0.0f || u > 1.0f)) {
- Py_RETURN_NONE;
- }
-
- /* prepare to test the V parameter */
- cross_v3_v3v3(qvec, tvec, e1);
-
- /* calculate V parameter and test bounds */
- v = dot_v3v3(dir, qvec) * inv_det;
-
- if (clip && (v < 0.0f || u + v > 1.0f)) {
- Py_RETURN_NONE;
- }
-
- /* calculate t, ray intersects triangle */
- t = dot_v3v3(e2, qvec) * inv_det;
-
- /* ray hit behind */
- if (t < 0.0f) {
- Py_RETURN_NONE;
- }
-
- mul_v3_fl(dir, t);
- add_v3_v3v3(pvec, orig, dir);
-
- return Vector_CreatePyObject(pvec, 3, NULL);
+ const char *error_prefix = "intersect_ray_tri";
+ PyObject *py_ray, *py_ray_off, *py_tri[3];
+ float dir[3], orig[3], tri[3][3], e1[3], e2[3], pvec[3], tvec[3], qvec[3];
+ float det, inv_det, u, v, t;
+ bool clip = true;
+ int i;
+
+ if (!PyArg_ParseTuple(args,
+ "OOOOO|O&:intersect_ray_tri",
+ UNPACK3_EX(&, py_tri, ),
+ &py_ray,
+ &py_ray_off,
+ PyC_ParseBool,
+ &clip)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(dir, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_ray, error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(
+ orig, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_ray_off, error_prefix) != -1)) == 0) {
+ return NULL;
+ }
+
+ for (i = 0; i < ARRAY_SIZE(tri); i++) {
+ if (mathutils_array_parse(
+ tri[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_tri[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ normalize_v3(dir);
+
+ /* find vectors for two edges sharing v1 */
+ sub_v3_v3v3(e1, tri[1], tri[0]);
+ sub_v3_v3v3(e2, tri[2], tri[0]);
+
+ /* begin calculating determinant - also used to calculated U parameter */
+ cross_v3_v3v3(pvec, dir, e2);
+
+ /* if determinant is near zero, ray lies in plane of triangle */
+ det = dot_v3v3(e1, pvec);
+
+ if (det > -0.000001f && det < 0.000001f) {
+ Py_RETURN_NONE;
+ }
+
+ inv_det = 1.0f / det;
+
+ /* calculate distance from v1 to ray origin */
+ sub_v3_v3v3(tvec, orig, tri[0]);
+
+ /* calculate U parameter and test bounds */
+ u = dot_v3v3(tvec, pvec) * inv_det;
+ if (clip && (u < 0.0f || u > 1.0f)) {
+ Py_RETURN_NONE;
+ }
+
+ /* prepare to test the V parameter */
+ cross_v3_v3v3(qvec, tvec, e1);
+
+ /* calculate V parameter and test bounds */
+ v = dot_v3v3(dir, qvec) * inv_det;
+
+ if (clip && (v < 0.0f || u + v > 1.0f)) {
+ Py_RETURN_NONE;
+ }
+
+ /* calculate t, ray intersects triangle */
+ t = dot_v3v3(e2, qvec) * inv_det;
+
+ /* ray hit behind */
+ if (t < 0.0f) {
+ Py_RETURN_NONE;
+ }
+
+ mul_v3_fl(dir, t);
+ add_v3_v3v3(pvec, orig, dir);
+
+ return Vector_CreatePyObject(pvec, 3, NULL);
}
/* Line-Line intersection using algorithm from mathworld.wolfram.com */
PyDoc_STRVAR(M_Geometry_intersect_line_line_doc,
-".. function:: intersect_line_line(v1, v2, v3, v4)\n"
-"\n"
-" Returns a tuple with the points on each line respectively closest to the other.\n"
-"\n"
-" :arg v1: First point of the first line\n"
-" :type v1: :class:`mathutils.Vector`\n"
-" :arg v2: Second point of the first line\n"
-" :type v2: :class:`mathutils.Vector`\n"
-" :arg v3: First point of the second line\n"
-" :type v3: :class:`mathutils.Vector`\n"
-" :arg v4: Second point of the second line\n"
-" :type v4: :class:`mathutils.Vector`\n"
-" :rtype: tuple of :class:`mathutils.Vector`'s\n"
-);
+ ".. function:: intersect_line_line(v1, v2, v3, v4)\n"
+ "\n"
+ " Returns a tuple with the points on each line respectively closest to the other.\n"
+ "\n"
+ " :arg v1: First point of the first line\n"
+ " :type v1: :class:`mathutils.Vector`\n"
+ " :arg v2: Second point of the first line\n"
+ " :type v2: :class:`mathutils.Vector`\n"
+ " :arg v3: First point of the second line\n"
+ " :type v3: :class:`mathutils.Vector`\n"
+ " :arg v4: Second point of the second line\n"
+ " :type v4: :class:`mathutils.Vector`\n"
+ " :rtype: tuple of :class:`mathutils.Vector`'s\n");
static PyObject *M_Geometry_intersect_line_line(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_line_line";
- PyObject *tuple;
- PyObject *py_lines[4];
- float lines[4][3], i1[3], i2[3];
- int len;
- int result;
-
- if (!PyArg_ParseTuple(
- args, "OOOO:intersect_line_line",
- UNPACK4_EX(&, py_lines, )))
- {
- return NULL;
- }
-
- if ((((len = mathutils_array_parse(lines[0], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[0], error_prefix)) != -1) &&
- (mathutils_array_parse(lines[1], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[1], error_prefix) != -1) &&
- (mathutils_array_parse(lines[2], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[2], error_prefix) != -1) &&
- (mathutils_array_parse(lines[3], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[3], error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- result = isect_line_line_v3(UNPACK4(lines), i1, i2);
- /* The return-code isnt exposed,
- * this way we can check know how close the lines are. */
- if (result == 1) {
- closest_to_line_v3(i2, i1, lines[2], lines[3]);
- }
-
- if (result == 0) {
- /* collinear */
- Py_RETURN_NONE;
- }
- else {
- tuple = PyTuple_New(2);
- PyTuple_SET_ITEMS(tuple,
- Vector_CreatePyObject(i1, len, NULL),
- Vector_CreatePyObject(i2, len, NULL));
- return tuple;
- }
+ const char *error_prefix = "intersect_line_line";
+ PyObject *tuple;
+ PyObject *py_lines[4];
+ float lines[4][3], i1[3], i2[3];
+ int len;
+ int result;
+
+ if (!PyArg_ParseTuple(args, "OOOO:intersect_line_line", UNPACK4_EX(&, py_lines, ))) {
+ return NULL;
+ }
+
+ if ((((len = mathutils_array_parse(
+ lines[0], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[0], error_prefix)) != -1) &&
+ (mathutils_array_parse(
+ lines[1], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[1], error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(
+ lines[2], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[2], error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(
+ lines[3], len, len | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_lines[3], error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+
+ result = isect_line_line_v3(UNPACK4(lines), i1, i2);
+ /* The return-code isnt exposed,
+ * this way we can check know how close the lines are. */
+ if (result == 1) {
+ closest_to_line_v3(i2, i1, lines[2], lines[3]);
+ }
+
+ if (result == 0) {
+ /* collinear */
+ Py_RETURN_NONE;
+ }
+ else {
+ tuple = PyTuple_New(2);
+ PyTuple_SET_ITEMS(
+ tuple, Vector_CreatePyObject(i1, len, NULL), Vector_CreatePyObject(i2, len, NULL));
+ return tuple;
+ }
}
/* Line-Line intersection using algorithm from mathworld.wolfram.com */
-PyDoc_STRVAR(M_Geometry_intersect_sphere_sphere_2d_doc,
-".. function:: intersect_sphere_sphere_2d(p_a, radius_a, p_b, radius_b)\n"
-"\n"
-" Returns 2 points on between intersecting circles.\n"
-"\n"
-" :arg p_a: Center of the first circle\n"
-" :type p_a: :class:`mathutils.Vector`\n"
-" :arg radius_a: Radius of the first circle\n"
-" :type radius_a: float\n"
-" :arg p_b: Center of the second circle\n"
-" :type p_b: :class:`mathutils.Vector`\n"
-" :arg radius_b: Radius of the second circle\n"
-" :type radius_b: float\n"
-" :rtype: tuple of :class:`mathutils.Vector`'s or None when there is no intersection\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_sphere_sphere_2d_doc,
+ ".. function:: intersect_sphere_sphere_2d(p_a, radius_a, p_b, radius_b)\n"
+ "\n"
+ " Returns 2 points on between intersecting circles.\n"
+ "\n"
+ " :arg p_a: Center of the first circle\n"
+ " :type p_a: :class:`mathutils.Vector`\n"
+ " :arg radius_a: Radius of the first circle\n"
+ " :type radius_a: float\n"
+ " :arg p_b: Center of the second circle\n"
+ " :type p_b: :class:`mathutils.Vector`\n"
+ " :arg radius_b: Radius of the second circle\n"
+ " :type radius_b: float\n"
+ " :rtype: tuple of :class:`mathutils.Vector`'s or None when there is no intersection\n");
static PyObject *M_Geometry_intersect_sphere_sphere_2d(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_sphere_sphere_2d";
- PyObject *ret;
- PyObject *py_v_a, *py_v_b;
- float v_a[2], v_b[2];
- float rad_a, rad_b;
- float v_ab[2];
- float dist;
-
- if (!PyArg_ParseTuple(
- args, "OfOf:intersect_sphere_sphere_2d",
- &py_v_a, &rad_a,
- &py_v_b, &rad_b))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(v_a, 2, 2, py_v_a, error_prefix) != -1) &&
- (mathutils_array_parse(v_b, 2, 2, py_v_b, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- ret = PyTuple_New(2);
-
- sub_v2_v2v2(v_ab, v_b, v_a);
- dist = len_v2(v_ab);
-
- if (/* out of range */
- (dist > rad_a + rad_b) ||
- /* fully-contained in the other */
- (dist < fabsf(rad_a - rad_b)) ||
- /* co-incident */
- (dist < FLT_EPSILON))
- {
- /* out of range */
- PyTuple_SET_ITEMS(ret,
- Py_INCREF_RET(Py_None),
- Py_INCREF_RET(Py_None));
- }
- else {
- const float dist_delta = ((rad_a * rad_a) - (rad_b * rad_b) + (dist * dist)) / (2.0f * dist);
- const float h = powf(fabsf((rad_a * rad_a) - (dist_delta * dist_delta)), 0.5f);
- float i_cent[2];
- float i1[2], i2[2];
-
- i_cent[0] = v_a[0] + ((v_ab[0] * dist_delta) / dist);
- i_cent[1] = v_a[1] + ((v_ab[1] * dist_delta) / dist);
-
- i1[0] = i_cent[0] + h * v_ab[1] / dist;
- i1[1] = i_cent[1] - h * v_ab[0] / dist;
-
- i2[0] = i_cent[0] - h * v_ab[1] / dist;
- i2[1] = i_cent[1] + h * v_ab[0] / dist;
-
- PyTuple_SET_ITEMS(ret,
- Vector_CreatePyObject(i1, 2, NULL),
- Vector_CreatePyObject(i2, 2, NULL));
- }
-
- return ret;
+ const char *error_prefix = "intersect_sphere_sphere_2d";
+ PyObject *ret;
+ PyObject *py_v_a, *py_v_b;
+ float v_a[2], v_b[2];
+ float rad_a, rad_b;
+ float v_ab[2];
+ float dist;
+
+ if (!PyArg_ParseTuple(
+ args, "OfOf:intersect_sphere_sphere_2d", &py_v_a, &rad_a, &py_v_b, &rad_b)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(v_a, 2, 2, py_v_a, error_prefix) != -1) &&
+ (mathutils_array_parse(v_b, 2, 2, py_v_b, error_prefix) != -1)) == 0) {
+ return NULL;
+ }
+
+ ret = PyTuple_New(2);
+
+ sub_v2_v2v2(v_ab, v_b, v_a);
+ dist = len_v2(v_ab);
+
+ if (/* out of range */
+ (dist > rad_a + rad_b) ||
+ /* fully-contained in the other */
+ (dist < fabsf(rad_a - rad_b)) ||
+ /* co-incident */
+ (dist < FLT_EPSILON)) {
+ /* out of range */
+ PyTuple_SET_ITEMS(ret, Py_INCREF_RET(Py_None), Py_INCREF_RET(Py_None));
+ }
+ else {
+ const float dist_delta = ((rad_a * rad_a) - (rad_b * rad_b) + (dist * dist)) / (2.0f * dist);
+ const float h = powf(fabsf((rad_a * rad_a) - (dist_delta * dist_delta)), 0.5f);
+ float i_cent[2];
+ float i1[2], i2[2];
+
+ i_cent[0] = v_a[0] + ((v_ab[0] * dist_delta) / dist);
+ i_cent[1] = v_a[1] + ((v_ab[1] * dist_delta) / dist);
+
+ i1[0] = i_cent[0] + h * v_ab[1] / dist;
+ i1[1] = i_cent[1] - h * v_ab[0] / dist;
+
+ i2[0] = i_cent[0] - h * v_ab[1] / dist;
+ i2[1] = i_cent[1] + h * v_ab[0] / dist;
+
+ PyTuple_SET_ITEMS(ret, Vector_CreatePyObject(i1, 2, NULL), Vector_CreatePyObject(i2, 2, NULL));
+ }
+
+ return ret;
}
PyDoc_STRVAR(M_Geometry_normal_doc,
-".. function:: normal(vectors)\n"
-"\n"
-" Returns the normal of a 3D polygon.\n"
-"\n"
-" :arg vectors: Vectors to calculate normals with\n"
-" :type vectors: sequence of 3 or more 3d vector\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: normal(vectors)\n"
+ "\n"
+ " Returns the normal of a 3D polygon.\n"
+ "\n"
+ " :arg vectors: Vectors to calculate normals with\n"
+ " :type vectors: sequence of 3 or more 3d vector\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Geometry_normal(PyObject *UNUSED(self), PyObject *args)
{
- float (*coords)[3];
- int coords_len;
- float n[3];
- PyObject *ret = NULL;
+ float(*coords)[3];
+ int coords_len;
+ float n[3];
+ PyObject *ret = NULL;
- /* use */
- if (PyTuple_GET_SIZE(args) == 1) {
- args = PyTuple_GET_ITEM(args, 0);
- }
+ /* use */
+ if (PyTuple_GET_SIZE(args) == 1) {
+ args = PyTuple_GET_ITEM(args, 0);
+ }
- if ((coords_len = mathutils_array_parse_alloc_v((float **)&coords, 3 | MU_ARRAY_SPILL, args, "normal")) == -1) {
- return NULL;
- }
+ if ((coords_len = mathutils_array_parse_alloc_v(
+ (float **)&coords, 3 | MU_ARRAY_SPILL, args, "normal")) == -1) {
+ return NULL;
+ }
- if (coords_len < 3) {
- PyErr_SetString(PyExc_ValueError,
- "Expected 3 or more vectors");
- goto finally;
- }
+ if (coords_len < 3) {
+ PyErr_SetString(PyExc_ValueError, "Expected 3 or more vectors");
+ goto finally;
+ }
- normal_poly_v3(n, (const float (*)[3])coords, coords_len);
- ret = Vector_CreatePyObject(n, 3, NULL);
+ normal_poly_v3(n, (const float(*)[3])coords, coords_len);
+ ret = Vector_CreatePyObject(n, 3, NULL);
finally:
- PyMem_Free(coords);
- return ret;
+ PyMem_Free(coords);
+ return ret;
}
/* --------------------------------- AREA FUNCTIONS-------------------- */
PyDoc_STRVAR(M_Geometry_area_tri_doc,
-".. function:: area_tri(v1, v2, v3)\n"
-"\n"
-" Returns the area size of the 2D or 3D triangle defined.\n"
-"\n"
-" :arg v1: Point1\n"
-" :type v1: :class:`mathutils.Vector`\n"
-" :arg v2: Point2\n"
-" :type v2: :class:`mathutils.Vector`\n"
-" :arg v3: Point3\n"
-" :type v3: :class:`mathutils.Vector`\n"
-" :rtype: float\n"
-);
+ ".. function:: area_tri(v1, v2, v3)\n"
+ "\n"
+ " Returns the area size of the 2D or 3D triangle defined.\n"
+ "\n"
+ " :arg v1: Point1\n"
+ " :type v1: :class:`mathutils.Vector`\n"
+ " :arg v2: Point2\n"
+ " :type v2: :class:`mathutils.Vector`\n"
+ " :arg v3: Point3\n"
+ " :type v3: :class:`mathutils.Vector`\n"
+ " :rtype: float\n");
static PyObject *M_Geometry_area_tri(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "area_tri";
- PyObject *py_tri[3];
- float tri[3][3];
- int len;
-
- if (!PyArg_ParseTuple(
- args, "OOO:area_tri",
- UNPACK3_EX(&, py_tri, )))
- {
- return NULL;
- }
-
- if ((((len = mathutils_array_parse(tri[0], 2, 3, py_tri[0], error_prefix)) != -1) &&
- (mathutils_array_parse(tri[1], len, len, py_tri[1], error_prefix) != -1) &&
- (mathutils_array_parse(tri[2], len, len, py_tri[2], error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- return PyFloat_FromDouble((len == 3 ? area_tri_v3 : area_tri_v2)(UNPACK3(tri)));
+ const char *error_prefix = "area_tri";
+ PyObject *py_tri[3];
+ float tri[3][3];
+ int len;
+
+ if (!PyArg_ParseTuple(args, "OOO:area_tri", UNPACK3_EX(&, py_tri, ))) {
+ return NULL;
+ }
+
+ if ((((len = mathutils_array_parse(tri[0], 2, 3, py_tri[0], error_prefix)) != -1) &&
+ (mathutils_array_parse(tri[1], len, len, py_tri[1], error_prefix) != -1) &&
+ (mathutils_array_parse(tri[2], len, len, py_tri[2], error_prefix) != -1)) == 0) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble((len == 3 ? area_tri_v3 : area_tri_v2)(UNPACK3(tri)));
}
PyDoc_STRVAR(M_Geometry_volume_tetrahedron_doc,
-".. function:: volume_tetrahedron(v1, v2, v3, v4)\n"
-"\n"
-" Return the volume formed by a tetrahedron (points can be in any order).\n"
-"\n"
-" :arg v1: Point1\n"
-" :type v1: :class:`mathutils.Vector`\n"
-" :arg v2: Point2\n"
-" :type v2: :class:`mathutils.Vector`\n"
-" :arg v3: Point3\n"
-" :type v3: :class:`mathutils.Vector`\n"
-" :arg v4: Point4\n"
-" :type v4: :class:`mathutils.Vector`\n"
-" :rtype: float\n"
-);
+ ".. function:: volume_tetrahedron(v1, v2, v3, v4)\n"
+ "\n"
+ " Return the volume formed by a tetrahedron (points can be in any order).\n"
+ "\n"
+ " :arg v1: Point1\n"
+ " :type v1: :class:`mathutils.Vector`\n"
+ " :arg v2: Point2\n"
+ " :type v2: :class:`mathutils.Vector`\n"
+ " :arg v3: Point3\n"
+ " :type v3: :class:`mathutils.Vector`\n"
+ " :arg v4: Point4\n"
+ " :type v4: :class:`mathutils.Vector`\n"
+ " :rtype: float\n");
static PyObject *M_Geometry_volume_tetrahedron(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "volume_tetrahedron";
- PyObject *py_tet[4];
- float tet[4][3];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOO:volume_tetrahedron",
- UNPACK4_EX(&, py_tet, )))
- {
- return NULL;
- }
-
- for (i = 0; i < ARRAY_SIZE(tet); i++) {
- if (mathutils_array_parse(tet[i], 3, 3 | MU_ARRAY_SPILL, py_tet[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- return PyFloat_FromDouble(volume_tetrahedron_v3(UNPACK4(tet)));
+ const char *error_prefix = "volume_tetrahedron";
+ PyObject *py_tet[4];
+ float tet[4][3];
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OOOO:volume_tetrahedron", UNPACK4_EX(&, py_tet, ))) {
+ return NULL;
+ }
+
+ for (i = 0; i < ARRAY_SIZE(tet); i++) {
+ if (mathutils_array_parse(tet[i], 3, 3 | MU_ARRAY_SPILL, py_tet[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ return PyFloat_FromDouble(volume_tetrahedron_v3(UNPACK4(tet)));
}
-PyDoc_STRVAR(M_Geometry_intersect_line_line_2d_doc,
-".. function:: intersect_line_line_2d(lineA_p1, lineA_p2, lineB_p1, lineB_p2)\n"
-"\n"
-" Takes 2 segments (defined by 4 vectors) and returns a vector for their point of intersection or None.\n"
-"\n"
-" .. warning:: Despite its name, this function works on segments, and not on lines.\n"
-"\n"
-" :arg lineA_p1: First point of the first line\n"
-" :type lineA_p1: :class:`mathutils.Vector`\n"
-" :arg lineA_p2: Second point of the first line\n"
-" :type lineA_p2: :class:`mathutils.Vector`\n"
-" :arg lineB_p1: First point of the second line\n"
-" :type lineB_p1: :class:`mathutils.Vector`\n"
-" :arg lineB_p2: Second point of the second line\n"
-" :type lineB_p2: :class:`mathutils.Vector`\n"
-" :return: The point of intersection or None when not found\n"
-" :rtype: :class:`mathutils.Vector` or None\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_line_line_2d_doc,
+ ".. function:: intersect_line_line_2d(lineA_p1, lineA_p2, lineB_p1, lineB_p2)\n"
+ "\n"
+ " Takes 2 segments (defined by 4 vectors) and returns a vector for their point of "
+ "intersection or None.\n"
+ "\n"
+ " .. warning:: Despite its name, this function works on segments, and not on lines.\n"
+ "\n"
+ " :arg lineA_p1: First point of the first line\n"
+ " :type lineA_p1: :class:`mathutils.Vector`\n"
+ " :arg lineA_p2: Second point of the first line\n"
+ " :type lineA_p2: :class:`mathutils.Vector`\n"
+ " :arg lineB_p1: First point of the second line\n"
+ " :type lineB_p1: :class:`mathutils.Vector`\n"
+ " :arg lineB_p2: Second point of the second line\n"
+ " :type lineB_p2: :class:`mathutils.Vector`\n"
+ " :return: The point of intersection or None when not found\n"
+ " :rtype: :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_line_line_2d(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_line_line_2d";
- PyObject *py_lines[4];
- float lines[4][2];
- float vi[2];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOO:intersect_line_line_2d",
- UNPACK4_EX(&, py_lines, )))
- {
- return NULL;
- }
-
- for (i = 0; i < ARRAY_SIZE(lines); i++) {
- if (mathutils_array_parse(lines[i], 2, 2 | MU_ARRAY_SPILL, py_lines[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- if (isect_seg_seg_v2_point(UNPACK4(lines), vi) == 1) {
- return Vector_CreatePyObject(vi, 2, NULL);
- }
- else {
- Py_RETURN_NONE;
- }
+ const char *error_prefix = "intersect_line_line_2d";
+ PyObject *py_lines[4];
+ float lines[4][2];
+ float vi[2];
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OOOO:intersect_line_line_2d", UNPACK4_EX(&, py_lines, ))) {
+ return NULL;
+ }
+
+ for (i = 0; i < ARRAY_SIZE(lines); i++) {
+ if (mathutils_array_parse(lines[i], 2, 2 | MU_ARRAY_SPILL, py_lines[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ if (isect_seg_seg_v2_point(UNPACK4(lines), vi) == 1) {
+ return Vector_CreatePyObject(vi, 2, NULL);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-
-PyDoc_STRVAR(M_Geometry_intersect_line_plane_doc,
-".. function:: intersect_line_plane(line_a, line_b, plane_co, plane_no, no_flip=False)\n"
-"\n"
-" Calculate the intersection between a line (as 2 vectors) and a plane.\n"
-" Returns a vector for the intersection or None.\n"
-"\n"
-" :arg line_a: First point of the first line\n"
-" :type line_a: :class:`mathutils.Vector`\n"
-" :arg line_b: Second point of the first line\n"
-" :type line_b: :class:`mathutils.Vector`\n"
-" :arg plane_co: A point on the plane\n"
-" :type plane_co: :class:`mathutils.Vector`\n"
-" :arg plane_no: The direction the plane is facing\n"
-" :type plane_no: :class:`mathutils.Vector`\n"
-" :return: The point of intersection or None when not found\n"
-" :rtype: :class:`mathutils.Vector` or None\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_line_plane_doc,
+ ".. function:: intersect_line_plane(line_a, line_b, plane_co, plane_no, no_flip=False)\n"
+ "\n"
+ " Calculate the intersection between a line (as 2 vectors) and a plane.\n"
+ " Returns a vector for the intersection or None.\n"
+ "\n"
+ " :arg line_a: First point of the first line\n"
+ " :type line_a: :class:`mathutils.Vector`\n"
+ " :arg line_b: Second point of the first line\n"
+ " :type line_b: :class:`mathutils.Vector`\n"
+ " :arg plane_co: A point on the plane\n"
+ " :type plane_co: :class:`mathutils.Vector`\n"
+ " :arg plane_no: The direction the plane is facing\n"
+ " :type plane_no: :class:`mathutils.Vector`\n"
+ " :return: The point of intersection or None when not found\n"
+ " :rtype: :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_line_plane(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_line_plane";
- PyObject *py_line_a, *py_line_b, *py_plane_co, *py_plane_no;
- float line_a[3], line_b[3], plane_co[3], plane_no[3];
- float isect[3];
- bool no_flip = false;
-
- if (!PyArg_ParseTuple(
- args, "OOOO|O&:intersect_line_plane",
- &py_line_a, &py_line_b, &py_plane_co, &py_plane_no,
- PyC_ParseBool, &no_flip))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
- (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
- (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
- (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- /* TODO: implements no_flip */
- if (isect_line_plane_v3(isect, line_a, line_b, plane_co, plane_no) == 1) {
- return Vector_CreatePyObject(isect, 3, NULL);
- }
- else {
- Py_RETURN_NONE;
- }
+ const char *error_prefix = "intersect_line_plane";
+ PyObject *py_line_a, *py_line_b, *py_plane_co, *py_plane_no;
+ float line_a[3], line_b[3], plane_co[3], plane_no[3];
+ float isect[3];
+ bool no_flip = false;
+
+ if (!PyArg_ParseTuple(args,
+ "OOOO|O&:intersect_line_plane",
+ &py_line_a,
+ &py_line_b,
+ &py_plane_co,
+ &py_plane_no,
+ PyC_ParseBool,
+ &no_flip)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
+ (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
+ (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
+ (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+
+ /* TODO: implements no_flip */
+ if (isect_line_plane_v3(isect, line_a, line_b, plane_co, plane_no) == 1) {
+ return Vector_CreatePyObject(isect, 3, NULL);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-PyDoc_STRVAR(M_Geometry_intersect_plane_plane_doc,
-".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
-"\n"
-" Return the intersection between two planes\n"
-"\n"
-" :arg plane_a_co: Point on the first plane\n"
-" :type plane_a_co: :class:`mathutils.Vector`\n"
-" :arg plane_a_no: Normal of the first plane\n"
-" :type plane_a_no: :class:`mathutils.Vector`\n"
-" :arg plane_b_co: Point on the second plane\n"
-" :type plane_b_co: :class:`mathutils.Vector`\n"
-" :arg plane_b_no: Normal of the second plane\n"
-" :type plane_b_no: :class:`mathutils.Vector`\n"
-" :return: The line of the intersection represented as a point and a vector\n"
-" :rtype: tuple pair of :class:`mathutils.Vector` or None if the intersection can't be calculated\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_plane_plane_doc,
+ ".. function:: intersect_plane_plane(plane_a_co, plane_a_no, plane_b_co, plane_b_no)\n"
+ "\n"
+ " Return the intersection between two planes\n"
+ "\n"
+ " :arg plane_a_co: Point on the first plane\n"
+ " :type plane_a_co: :class:`mathutils.Vector`\n"
+ " :arg plane_a_no: Normal of the first plane\n"
+ " :type plane_a_no: :class:`mathutils.Vector`\n"
+ " :arg plane_b_co: Point on the second plane\n"
+ " :type plane_b_co: :class:`mathutils.Vector`\n"
+ " :arg plane_b_no: Normal of the second plane\n"
+ " :type plane_b_no: :class:`mathutils.Vector`\n"
+ " :return: The line of the intersection represented as a point and a vector\n"
+ " :rtype: tuple pair of :class:`mathutils.Vector` or None if the intersection can't be "
+ "calculated\n");
static PyObject *M_Geometry_intersect_plane_plane(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_plane_plane";
- PyObject *ret, *ret_co, *ret_no;
- PyObject *py_plane_a_co, *py_plane_a_no, *py_plane_b_co, *py_plane_b_no;
- float plane_a_co[3], plane_a_no[3], plane_b_co[3], plane_b_no[3];
- float plane_a[4], plane_b[4];
-
- float isect_co[3];
- float isect_no[3];
-
- if (!PyArg_ParseTuple(
- args, "OOOO:intersect_plane_plane",
- &py_plane_a_co, &py_plane_a_no, &py_plane_b_co, &py_plane_b_no))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(plane_a_co, 3, 3 | MU_ARRAY_SPILL, py_plane_a_co, error_prefix) != -1) &&
- (mathutils_array_parse(plane_a_no, 3, 3 | MU_ARRAY_SPILL, py_plane_a_no, error_prefix) != -1) &&
- (mathutils_array_parse(plane_b_co, 3, 3 | MU_ARRAY_SPILL, py_plane_b_co, error_prefix) != -1) &&
- (mathutils_array_parse(plane_b_no, 3, 3 | MU_ARRAY_SPILL, py_plane_b_no, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- plane_from_point_normal_v3(plane_a, plane_a_co, plane_a_no);
- plane_from_point_normal_v3(plane_b, plane_b_co, plane_b_no);
-
- if (isect_plane_plane_v3(
- plane_a, plane_b,
- isect_co, isect_no))
- {
- normalize_v3(isect_no);
-
- ret_co = Vector_CreatePyObject(isect_co, 3, NULL);
- ret_no = Vector_CreatePyObject(isect_no, 3, NULL);
- }
- else {
- ret_co = Py_INCREF_RET(Py_None);
- ret_no = Py_INCREF_RET(Py_None);
- }
-
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- ret_co,
- ret_no);
- return ret;
+ const char *error_prefix = "intersect_plane_plane";
+ PyObject *ret, *ret_co, *ret_no;
+ PyObject *py_plane_a_co, *py_plane_a_no, *py_plane_b_co, *py_plane_b_no;
+ float plane_a_co[3], plane_a_no[3], plane_b_co[3], plane_b_no[3];
+ float plane_a[4], plane_b[4];
+
+ float isect_co[3];
+ float isect_no[3];
+
+ if (!PyArg_ParseTuple(args,
+ "OOOO:intersect_plane_plane",
+ &py_plane_a_co,
+ &py_plane_a_no,
+ &py_plane_b_co,
+ &py_plane_b_no)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(plane_a_co, 3, 3 | MU_ARRAY_SPILL, py_plane_a_co, error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(plane_a_no, 3, 3 | MU_ARRAY_SPILL, py_plane_a_no, error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(plane_b_co, 3, 3 | MU_ARRAY_SPILL, py_plane_b_co, error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(plane_b_no, 3, 3 | MU_ARRAY_SPILL, py_plane_b_no, error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+
+ plane_from_point_normal_v3(plane_a, plane_a_co, plane_a_no);
+ plane_from_point_normal_v3(plane_b, plane_b_co, plane_b_no);
+
+ if (isect_plane_plane_v3(plane_a, plane_b, isect_co, isect_no)) {
+ normalize_v3(isect_no);
+
+ ret_co = Vector_CreatePyObject(isect_co, 3, NULL);
+ ret_no = Vector_CreatePyObject(isect_no, 3, NULL);
+ }
+ else {
+ ret_co = Py_INCREF_RET(Py_None);
+ ret_no = Py_INCREF_RET(Py_None);
+ }
+
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, ret_co, ret_no);
+ return ret;
}
-PyDoc_STRVAR(M_Geometry_intersect_line_sphere_doc,
-".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
-"\n"
-" Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
-" returns the intersection\n"
-"\n"
-" :arg line_a: First point of the line\n"
-" :type line_a: :class:`mathutils.Vector`\n"
-" :arg line_b: Second point of the line\n"
-" :type line_b: :class:`mathutils.Vector`\n"
-" :arg sphere_co: The center of the sphere\n"
-" :type sphere_co: :class:`mathutils.Vector`\n"
-" :arg sphere_radius: Radius of the sphere\n"
-" :type sphere_radius: sphere_radius\n"
-" :return: The intersection points as a pair of vectors or None when there is no intersection\n"
-" :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_line_sphere_doc,
+ ".. function:: intersect_line_sphere(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
+ "\n"
+ " Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
+ " returns the intersection\n"
+ "\n"
+ " :arg line_a: First point of the line\n"
+ " :type line_a: :class:`mathutils.Vector`\n"
+ " :arg line_b: Second point of the line\n"
+ " :type line_b: :class:`mathutils.Vector`\n"
+ " :arg sphere_co: The center of the sphere\n"
+ " :type sphere_co: :class:`mathutils.Vector`\n"
+ " :arg sphere_radius: Radius of the sphere\n"
+ " :type sphere_radius: sphere_radius\n"
+ " :return: The intersection points as a pair of vectors or None when there is no "
+ "intersection\n"
+ " :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_line_sphere(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_line_sphere";
- PyObject *py_line_a, *py_line_b, *py_sphere_co;
- float line_a[3], line_b[3], sphere_co[3];
- float sphere_radius;
- bool clip = true;
-
- float isect_a[3];
- float isect_b[3];
-
- if (!PyArg_ParseTuple(
- args, "OOOf|O&:intersect_line_sphere",
- &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius,
- PyC_ParseBool, &clip))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
- (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
- (mathutils_array_parse(sphere_co, 3, 3 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
- else {
- bool use_a = true;
- bool use_b = true;
- float lambda;
-
- PyObject *ret = PyTuple_New(2);
-
- switch (isect_line_sphere_v3(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
- case 1:
- if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_a = false; }
- use_b = false;
- break;
- case 2:
- if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_a = false; }
- if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_b = false; }
- break;
- default:
- use_a = false;
- use_b = false;
- break;
- }
-
- PyTuple_SET_ITEMS(ret,
- use_a ? Vector_CreatePyObject(isect_a, 3, NULL) : Py_INCREF_RET(Py_None),
- use_b ? Vector_CreatePyObject(isect_b, 3, NULL) : Py_INCREF_RET(Py_None));
-
- return ret;
- }
+ const char *error_prefix = "intersect_line_sphere";
+ PyObject *py_line_a, *py_line_b, *py_sphere_co;
+ float line_a[3], line_b[3], sphere_co[3];
+ float sphere_radius;
+ bool clip = true;
+
+ float isect_a[3];
+ float isect_b[3];
+
+ if (!PyArg_ParseTuple(args,
+ "OOOf|O&:intersect_line_sphere",
+ &py_line_a,
+ &py_line_b,
+ &py_sphere_co,
+ &sphere_radius,
+ PyC_ParseBool,
+ &clip)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(line_a, 3, 3 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
+ (mathutils_array_parse(line_b, 3, 3 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
+ (mathutils_array_parse(sphere_co, 3, 3 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+ else {
+ bool use_a = true;
+ bool use_b = true;
+ float lambda;
+
+ PyObject *ret = PyTuple_New(2);
+
+ switch (isect_line_sphere_v3(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
+ case 1:
+ if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_a = false;
+ }
+ use_b = false;
+ break;
+ case 2:
+ if (!(!clip || (((lambda = line_point_factor_v3(isect_a, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_a = false;
+ }
+ if (!(!clip || (((lambda = line_point_factor_v3(isect_b, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_b = false;
+ }
+ break;
+ default:
+ use_a = false;
+ use_b = false;
+ break;
+ }
+
+ PyTuple_SET_ITEMS(ret,
+ use_a ? Vector_CreatePyObject(isect_a, 3, NULL) : Py_INCREF_RET(Py_None),
+ use_b ? Vector_CreatePyObject(isect_b, 3, NULL) : Py_INCREF_RET(Py_None));
+
+ return ret;
+ }
}
/* keep in sync with M_Geometry_intersect_line_sphere */
-PyDoc_STRVAR(M_Geometry_intersect_line_sphere_2d_doc,
-".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
-"\n"
-" Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
-" returns the intersection\n"
-"\n"
-" :arg line_a: First point of the line\n"
-" :type line_a: :class:`mathutils.Vector`\n"
-" :arg line_b: Second point of the line\n"
-" :type line_b: :class:`mathutils.Vector`\n"
-" :arg sphere_co: The center of the sphere\n"
-" :type sphere_co: :class:`mathutils.Vector`\n"
-" :arg sphere_radius: Radius of the sphere\n"
-" :type sphere_radius: sphere_radius\n"
-" :return: The intersection points as a pair of vectors or None when there is no intersection\n"
-" :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_line_sphere_2d_doc,
+ ".. function:: intersect_line_sphere_2d(line_a, line_b, sphere_co, sphere_radius, clip=True)\n"
+ "\n"
+ " Takes a line (as 2 points) and a sphere (as a point and a radius) and\n"
+ " returns the intersection\n"
+ "\n"
+ " :arg line_a: First point of the line\n"
+ " :type line_a: :class:`mathutils.Vector`\n"
+ " :arg line_b: Second point of the line\n"
+ " :type line_b: :class:`mathutils.Vector`\n"
+ " :arg sphere_co: The center of the sphere\n"
+ " :type sphere_co: :class:`mathutils.Vector`\n"
+ " :arg sphere_radius: Radius of the sphere\n"
+ " :type sphere_radius: sphere_radius\n"
+ " :return: The intersection points as a pair of vectors or None when there is no "
+ "intersection\n"
+ " :rtype: A tuple pair containing :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_line_sphere_2d(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_line_sphere_2d";
- PyObject *py_line_a, *py_line_b, *py_sphere_co;
- float line_a[2], line_b[2], sphere_co[2];
- float sphere_radius;
- bool clip = true;
-
- float isect_a[2];
- float isect_b[2];
-
- if (!PyArg_ParseTuple(
- args, "OOOf|O&:intersect_line_sphere_2d",
- &py_line_a, &py_line_b, &py_sphere_co, &sphere_radius,
- PyC_ParseBool, &clip))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(line_a, 2, 2 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
- (mathutils_array_parse(line_b, 2, 2 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
- (mathutils_array_parse(sphere_co, 2, 2 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
- else {
- bool use_a = true;
- bool use_b = true;
- float lambda;
-
- PyObject *ret = PyTuple_New(2);
-
- switch (isect_line_sphere_v2(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
- case 1:
- if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_a = false; }
- use_b = false;
- break;
- case 2:
- if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_a = false; }
- if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a, line_b)) >= 0.0f) && (lambda <= 1.0f)))) { use_b = false; }
- break;
- default:
- use_a = false;
- use_b = false;
- break;
- }
-
- PyTuple_SET_ITEMS(ret,
- use_a ? Vector_CreatePyObject(isect_a, 2, NULL) : Py_INCREF_RET(Py_None),
- use_b ? Vector_CreatePyObject(isect_b, 2, NULL) : Py_INCREF_RET(Py_None));
-
- return ret;
- }
+ const char *error_prefix = "intersect_line_sphere_2d";
+ PyObject *py_line_a, *py_line_b, *py_sphere_co;
+ float line_a[2], line_b[2], sphere_co[2];
+ float sphere_radius;
+ bool clip = true;
+
+ float isect_a[2];
+ float isect_b[2];
+
+ if (!PyArg_ParseTuple(args,
+ "OOOf|O&:intersect_line_sphere_2d",
+ &py_line_a,
+ &py_line_b,
+ &py_sphere_co,
+ &sphere_radius,
+ PyC_ParseBool,
+ &clip)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(line_a, 2, 2 | MU_ARRAY_SPILL, py_line_a, error_prefix) != -1) &&
+ (mathutils_array_parse(line_b, 2, 2 | MU_ARRAY_SPILL, py_line_b, error_prefix) != -1) &&
+ (mathutils_array_parse(sphere_co, 2, 2 | MU_ARRAY_SPILL, py_sphere_co, error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+ else {
+ bool use_a = true;
+ bool use_b = true;
+ float lambda;
+
+ PyObject *ret = PyTuple_New(2);
+
+ switch (isect_line_sphere_v2(line_a, line_b, sphere_co, sphere_radius, isect_a, isect_b)) {
+ case 1:
+ if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_a = false;
+ }
+ use_b = false;
+ break;
+ case 2:
+ if (!(!clip || (((lambda = line_point_factor_v2(isect_a, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_a = false;
+ }
+ if (!(!clip || (((lambda = line_point_factor_v2(isect_b, line_a, line_b)) >= 0.0f) &&
+ (lambda <= 1.0f)))) {
+ use_b = false;
+ }
+ break;
+ default:
+ use_a = false;
+ use_b = false;
+ break;
+ }
+
+ PyTuple_SET_ITEMS(ret,
+ use_a ? Vector_CreatePyObject(isect_a, 2, NULL) : Py_INCREF_RET(Py_None),
+ use_b ? Vector_CreatePyObject(isect_b, 2, NULL) : Py_INCREF_RET(Py_None));
+
+ return ret;
+ }
}
-PyDoc_STRVAR(M_Geometry_intersect_point_line_doc,
-".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
-"\n"
-" Takes a point and a line and returns a tuple with the closest point on the line and its distance from the first point of the line as a percentage of the length of the line.\n"
-"\n"
-" :arg pt: Point\n"
-" :type pt: :class:`mathutils.Vector`\n"
-" :arg line_p1: First point of the line\n"
-" :type line_p1: :class:`mathutils.Vector`\n"
-" :arg line_p1: Second point of the line\n"
-" :type line_p1: :class:`mathutils.Vector`\n"
-" :rtype: (:class:`mathutils.Vector`, float)\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_point_line_doc,
+ ".. function:: intersect_point_line(pt, line_p1, line_p2)\n"
+ "\n"
+ " Takes a point and a line and returns a tuple with the closest point on the line and its "
+ "distance from the first point of the line as a percentage of the length of the line.\n"
+ "\n"
+ " :arg pt: Point\n"
+ " :type pt: :class:`mathutils.Vector`\n"
+ " :arg line_p1: First point of the line\n"
+ " :type line_p1: :class:`mathutils.Vector`\n"
+ " :arg line_p1: Second point of the line\n"
+ " :type line_p1: :class:`mathutils.Vector`\n"
+ " :rtype: (:class:`mathutils.Vector`, float)\n");
static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_point_line";
- PyObject *py_pt, *py_line_a, *py_line_b;
- float pt[3], pt_out[3], line_a[3], line_b[3];
- float lambda;
- PyObject *ret;
- int size = 2;
-
- if (!PyArg_ParseTuple(
- args, "OOO:intersect_point_line",
- &py_pt, &py_line_a, &py_line_b))
- {
- return NULL;
- }
-
- /* accept 2d verts */
- if ((((size = mathutils_array_parse(pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix)) != -1) &&
- (mathutils_array_parse(line_a, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_a, error_prefix) != -1) &&
- (mathutils_array_parse(line_b, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_b, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- /* do the calculation */
- lambda = closest_to_line_v3(pt_out, pt, line_a, line_b);
-
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- Vector_CreatePyObject(pt_out, size, NULL),
- PyFloat_FromDouble(lambda));
- return ret;
+ const char *error_prefix = "intersect_point_line";
+ PyObject *py_pt, *py_line_a, *py_line_b;
+ float pt[3], pt_out[3], line_a[3], line_b[3];
+ float lambda;
+ PyObject *ret;
+ int size = 2;
+
+ if (!PyArg_ParseTuple(args, "OOO:intersect_point_line", &py_pt, &py_line_a, &py_line_b)) {
+ return NULL;
+ }
+
+ /* accept 2d verts */
+ if ((((size = mathutils_array_parse(
+ pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix)) != -1) &&
+ (mathutils_array_parse(
+ line_a, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_a, error_prefix) != -1) &&
+ (mathutils_array_parse(
+ line_b, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_line_b, error_prefix) != -1)) == 0) {
+ return NULL;
+ }
+
+ /* do the calculation */
+ lambda = closest_to_line_v3(pt_out, pt, line_a, line_b);
+
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, Vector_CreatePyObject(pt_out, size, NULL), PyFloat_FromDouble(lambda));
+ return ret;
}
PyDoc_STRVAR(M_Geometry_intersect_point_tri_doc,
-".. function:: intersect_point_tri(pt, tri_p1, tri_p2, tri_p3)\n"
-"\n"
-" Takes 4 vectors: one is the point and the next 3 define the triangle.\n"
-"\n"
-" :arg pt: Point\n"
-" :type pt: :class:`mathutils.Vector`\n"
-" :arg tri_p1: First point of the triangle\n"
-" :type tri_p1: :class:`mathutils.Vector`\n"
-" :arg tri_p2: Second point of the triangle\n"
-" :type tri_p2: :class:`mathutils.Vector`\n"
-" :arg tri_p3: Third point of the triangle\n"
-" :type tri_p3: :class:`mathutils.Vector`\n"
-" :return: Point on the triangles plane or None if its outside the triangle\n"
-" :rtype: :class:`mathutils.Vector` or None\n"
-);
+ ".. function:: intersect_point_tri(pt, tri_p1, tri_p2, tri_p3)\n"
+ "\n"
+ " Takes 4 vectors: one is the point and the next 3 define the triangle.\n"
+ "\n"
+ " :arg pt: Point\n"
+ " :type pt: :class:`mathutils.Vector`\n"
+ " :arg tri_p1: First point of the triangle\n"
+ " :type tri_p1: :class:`mathutils.Vector`\n"
+ " :arg tri_p2: Second point of the triangle\n"
+ " :type tri_p2: :class:`mathutils.Vector`\n"
+ " :arg tri_p3: Third point of the triangle\n"
+ " :type tri_p3: :class:`mathutils.Vector`\n"
+ " :return: Point on the triangles plane or None if its outside the triangle\n"
+ " :rtype: :class:`mathutils.Vector` or None\n");
static PyObject *M_Geometry_intersect_point_tri(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_point_tri";
- PyObject *py_pt, *py_tri[3];
- float pt[3], tri[3][3];
- float vi[3];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOO:intersect_point_tri",
- &py_pt, UNPACK3_EX(&, py_tri, )))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix) == -1) {
- return NULL;
- }
- for (i = 0; i < ARRAY_SIZE(tri); i++) {
- if (mathutils_array_parse(tri[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_tri[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- if (isect_point_tri_v3(pt, UNPACK3(tri), vi)) {
- return Vector_CreatePyObject(vi, 3, NULL);
- }
- else {
- Py_RETURN_NONE;
- }
+ const char *error_prefix = "intersect_point_tri";
+ PyObject *py_pt, *py_tri[3];
+ float pt[3], tri[3][3];
+ float vi[3];
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OOOO:intersect_point_tri", &py_pt, UNPACK3_EX(&, py_tri, ))) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(pt, 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_pt, error_prefix) ==
+ -1) {
+ return NULL;
+ }
+ for (i = 0; i < ARRAY_SIZE(tri); i++) {
+ if (mathutils_array_parse(
+ tri[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_tri[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ if (isect_point_tri_v3(pt, UNPACK3(tri), vi)) {
+ return Vector_CreatePyObject(vi, 3, NULL);
+ }
+ else {
+ Py_RETURN_NONE;
+ }
}
-PyDoc_STRVAR(M_Geometry_intersect_point_tri_2d_doc,
-".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
-"\n"
-" Takes 4 vectors (using only the x and y coordinates): one is the point and the next 3 define the triangle. Returns 1 if the point is within the triangle, otherwise 0.\n"
-"\n"
-" :arg pt: Point\n"
-" :type pt: :class:`mathutils.Vector`\n"
-" :arg tri_p1: First point of the triangle\n"
-" :type tri_p1: :class:`mathutils.Vector`\n"
-" :arg tri_p2: Second point of the triangle\n"
-" :type tri_p2: :class:`mathutils.Vector`\n"
-" :arg tri_p3: Third point of the triangle\n"
-" :type tri_p3: :class:`mathutils.Vector`\n"
-" :rtype: int\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_intersect_point_tri_2d_doc,
+ ".. function:: intersect_point_tri_2d(pt, tri_p1, tri_p2, tri_p3)\n"
+ "\n"
+ " Takes 4 vectors (using only the x and y coordinates): one is the point and the next 3 "
+ "define the triangle. Returns 1 if the point is within the triangle, otherwise 0.\n"
+ "\n"
+ " :arg pt: Point\n"
+ " :type pt: :class:`mathutils.Vector`\n"
+ " :arg tri_p1: First point of the triangle\n"
+ " :type tri_p1: :class:`mathutils.Vector`\n"
+ " :arg tri_p2: Second point of the triangle\n"
+ " :type tri_p2: :class:`mathutils.Vector`\n"
+ " :arg tri_p3: Third point of the triangle\n"
+ " :type tri_p3: :class:`mathutils.Vector`\n"
+ " :rtype: int\n");
static PyObject *M_Geometry_intersect_point_tri_2d(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_point_tri_2d";
- PyObject *py_pt, *py_tri[3];
- float pt[2], tri[3][2];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOO:intersect_point_tri_2d",
- &py_pt, UNPACK3_EX(&, py_tri, )))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
- return NULL;
- }
- for (i = 0; i < ARRAY_SIZE(tri); i++) {
- if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- return PyLong_FromLong(isect_point_tri_v2(pt, UNPACK3(tri)));
+ const char *error_prefix = "intersect_point_tri_2d";
+ PyObject *py_pt, *py_tri[3];
+ float pt[2], tri[3][2];
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OOOO:intersect_point_tri_2d", &py_pt, UNPACK3_EX(&, py_tri, ))) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
+ return NULL;
+ }
+ for (i = 0; i < ARRAY_SIZE(tri); i++) {
+ if (mathutils_array_parse(tri[i], 2, 2 | MU_ARRAY_SPILL, py_tri[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ return PyLong_FromLong(isect_point_tri_v2(pt, UNPACK3(tri)));
}
PyDoc_STRVAR(M_Geometry_intersect_point_quad_2d_doc,
-".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
-"\n"
-" Takes 5 vectors (using only the x and y coordinates): one is the point and the next 4 define the quad,\n"
-" only the x and y are used from the vectors. Returns 1 if the point is within the quad, otherwise 0.\n"
-" Works only with convex quads without singular edges.\n"
-"\n"
-" :arg pt: Point\n"
-" :type pt: :class:`mathutils.Vector`\n"
-" :arg quad_p1: First point of the quad\n"
-" :type quad_p1: :class:`mathutils.Vector`\n"
-" :arg quad_p2: Second point of the quad\n"
-" :type quad_p2: :class:`mathutils.Vector`\n"
-" :arg quad_p3: Third point of the quad\n"
-" :type quad_p3: :class:`mathutils.Vector`\n"
-" :arg quad_p4: Fourth point of the quad\n"
-" :type quad_p4: :class:`mathutils.Vector`\n"
-" :rtype: int\n"
-);
+ ".. function:: intersect_point_quad_2d(pt, quad_p1, quad_p2, quad_p3, quad_p4)\n"
+ "\n"
+ " Takes 5 vectors (using only the x and y coordinates): one is the point and the "
+ "next 4 define the quad,\n"
+ " only the x and y are used from the vectors. Returns 1 if the point is within the "
+ "quad, otherwise 0.\n"
+ " Works only with convex quads without singular edges.\n"
+ "\n"
+ " :arg pt: Point\n"
+ " :type pt: :class:`mathutils.Vector`\n"
+ " :arg quad_p1: First point of the quad\n"
+ " :type quad_p1: :class:`mathutils.Vector`\n"
+ " :arg quad_p2: Second point of the quad\n"
+ " :type quad_p2: :class:`mathutils.Vector`\n"
+ " :arg quad_p3: Third point of the quad\n"
+ " :type quad_p3: :class:`mathutils.Vector`\n"
+ " :arg quad_p4: Fourth point of the quad\n"
+ " :type quad_p4: :class:`mathutils.Vector`\n"
+ " :rtype: int\n");
static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "intersect_point_quad_2d";
- PyObject *py_pt, *py_quad[4];
- float pt[2], quad[4][2];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOOO:intersect_point_quad_2d",
- &py_pt, UNPACK4_EX(&, py_quad, )))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
- return NULL;
- }
- for (i = 0; i < ARRAY_SIZE(quad); i++) {
- if (mathutils_array_parse(quad[i], 2, 2 | MU_ARRAY_SPILL, py_quad[i], error_prefix) == -1) {
- return NULL;
- }
- }
-
- return PyLong_FromLong(isect_point_quad_v2(pt, UNPACK4(quad)));
+ const char *error_prefix = "intersect_point_quad_2d";
+ PyObject *py_pt, *py_quad[4];
+ float pt[2], quad[4][2];
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OOOOO:intersect_point_quad_2d", &py_pt, UNPACK4_EX(&, py_quad, ))) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(pt, 2, 2 | MU_ARRAY_SPILL, py_pt, error_prefix) == -1) {
+ return NULL;
+ }
+ for (i = 0; i < ARRAY_SIZE(quad); i++) {
+ if (mathutils_array_parse(quad[i], 2, 2 | MU_ARRAY_SPILL, py_quad[i], error_prefix) == -1) {
+ return NULL;
+ }
+ }
+
+ return PyLong_FromLong(isect_point_quad_v2(pt, UNPACK4(quad)));
}
PyDoc_STRVAR(M_Geometry_distance_point_to_plane_doc,
-".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
-"\n"
-" Returns the signed distance between a point and a plane "
-" (negative when below the normal).\n"
-"\n"
-" :arg pt: Point\n"
-" :type pt: :class:`mathutils.Vector`\n"
-" :arg plane_co: A point on the plane\n"
-" :type plane_co: :class:`mathutils.Vector`\n"
-" :arg plane_no: The direction the plane is facing\n"
-" :type plane_no: :class:`mathutils.Vector`\n"
-" :rtype: float\n"
-);
+ ".. function:: distance_point_to_plane(pt, plane_co, plane_no)\n"
+ "\n"
+ " Returns the signed distance between a point and a plane "
+ " (negative when below the normal).\n"
+ "\n"
+ " :arg pt: Point\n"
+ " :type pt: :class:`mathutils.Vector`\n"
+ " :arg plane_co: A point on the plane\n"
+ " :type plane_co: :class:`mathutils.Vector`\n"
+ " :arg plane_no: The direction the plane is facing\n"
+ " :type plane_no: :class:`mathutils.Vector`\n"
+ " :rtype: float\n");
static PyObject *M_Geometry_distance_point_to_plane(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "distance_point_to_plane";
- PyObject *py_pt, *py_plane_co, *py_plane_no;
- float pt[3], plane_co[3], plane_no[3];
- float plane[4];
-
- if (!PyArg_ParseTuple(
- args, "OOO:distance_point_to_plane",
- &py_pt, &py_plane_co, &py_plane_no))
- {
- return NULL;
- }
-
- if (((mathutils_array_parse(pt, 3, 3 | MU_ARRAY_SPILL, py_pt, error_prefix) != -1) &&
- (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
- (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) != -1)) == 0)
- {
- return NULL;
- }
-
- plane_from_point_normal_v3(plane, plane_co, plane_no);
- return PyFloat_FromDouble(dist_signed_to_plane_v3(pt, plane));
+ const char *error_prefix = "distance_point_to_plane";
+ PyObject *py_pt, *py_plane_co, *py_plane_no;
+ float pt[3], plane_co[3], plane_no[3];
+ float plane[4];
+
+ if (!PyArg_ParseTuple(args, "OOO:distance_point_to_plane", &py_pt, &py_plane_co, &py_plane_no)) {
+ return NULL;
+ }
+
+ if (((mathutils_array_parse(pt, 3, 3 | MU_ARRAY_SPILL, py_pt, error_prefix) != -1) &&
+ (mathutils_array_parse(plane_co, 3, 3 | MU_ARRAY_SPILL, py_plane_co, error_prefix) != -1) &&
+ (mathutils_array_parse(plane_no, 3, 3 | MU_ARRAY_SPILL, py_plane_no, error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+
+ plane_from_point_normal_v3(plane, plane_co, plane_no);
+ return PyFloat_FromDouble(dist_signed_to_plane_v3(pt, plane));
}
-PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
-".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
-"\n"
-" Return a transformed point, the transformation is defined by 2 triangles.\n"
-"\n"
-" :arg point: The point to transform.\n"
-" :type point: :class:`mathutils.Vector`\n"
-" :arg tri_a1: source triangle vertex.\n"
-" :type tri_a1: :class:`mathutils.Vector`\n"
-" :arg tri_a2: source triangle vertex.\n"
-" :type tri_a2: :class:`mathutils.Vector`\n"
-" :arg tri_a3: source triangle vertex.\n"
-" :type tri_a3: :class:`mathutils.Vector`\n"
-" :arg tri_b1: target triangle vertex.\n"
-" :type tri_b1: :class:`mathutils.Vector`\n"
-" :arg tri_b2: target triangle vertex.\n"
-" :type tri_b2: :class:`mathutils.Vector`\n"
-" :arg tri_b3: target triangle vertex.\n"
-" :type tri_b3: :class:`mathutils.Vector`\n"
-" :return: The transformed point\n"
-" :rtype: :class:`mathutils.Vector`'s\n"
-);
+PyDoc_STRVAR(
+ M_Geometry_barycentric_transform_doc,
+ ".. function:: barycentric_transform(point, tri_a1, tri_a2, tri_a3, tri_b1, tri_b2, tri_b3)\n"
+ "\n"
+ " Return a transformed point, the transformation is defined by 2 triangles.\n"
+ "\n"
+ " :arg point: The point to transform.\n"
+ " :type point: :class:`mathutils.Vector`\n"
+ " :arg tri_a1: source triangle vertex.\n"
+ " :type tri_a1: :class:`mathutils.Vector`\n"
+ " :arg tri_a2: source triangle vertex.\n"
+ " :type tri_a2: :class:`mathutils.Vector`\n"
+ " :arg tri_a3: source triangle vertex.\n"
+ " :type tri_a3: :class:`mathutils.Vector`\n"
+ " :arg tri_b1: target triangle vertex.\n"
+ " :type tri_b1: :class:`mathutils.Vector`\n"
+ " :arg tri_b2: target triangle vertex.\n"
+ " :type tri_b2: :class:`mathutils.Vector`\n"
+ " :arg tri_b3: target triangle vertex.\n"
+ " :type tri_b3: :class:`mathutils.Vector`\n"
+ " :return: The transformed point\n"
+ " :rtype: :class:`mathutils.Vector`'s\n");
static PyObject *M_Geometry_barycentric_transform(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "barycentric_transform";
- PyObject *py_pt_src, *py_tri_src[3], *py_tri_dst[3];
- float pt_src[3], pt_dst[3], tri_src[3][3], tri_dst[3][3];
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OOOOOOO:barycentric_transform",
- &py_pt_src,
- UNPACK3_EX(&, py_tri_src, ),
- UNPACK3_EX(&, py_tri_dst, )))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(pt_src, 3, 3 | MU_ARRAY_SPILL, py_pt_src, error_prefix) == -1) {
- return NULL;
- }
- for (i = 0; i < ARRAY_SIZE(tri_src); i++) {
- if (((mathutils_array_parse(tri_src[i], 3, 3 | MU_ARRAY_SPILL, py_tri_src[i], error_prefix) != -1) &&
- (mathutils_array_parse(tri_dst[i], 3, 3 | MU_ARRAY_SPILL, py_tri_dst[i], error_prefix) != -1)) == 0)
- {
- return NULL;
- }
- }
-
- transform_point_by_tri_v3(
- pt_dst, pt_src,
- UNPACK3(tri_dst),
- UNPACK3(tri_src));
-
- return Vector_CreatePyObject(pt_dst, 3, NULL);
+ const char *error_prefix = "barycentric_transform";
+ PyObject *py_pt_src, *py_tri_src[3], *py_tri_dst[3];
+ float pt_src[3], pt_dst[3], tri_src[3][3], tri_dst[3][3];
+ int i;
+
+ if (!PyArg_ParseTuple(args,
+ "OOOOOOO:barycentric_transform",
+ &py_pt_src,
+ UNPACK3_EX(&, py_tri_src, ),
+ UNPACK3_EX(&, py_tri_dst, ))) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(pt_src, 3, 3 | MU_ARRAY_SPILL, py_pt_src, error_prefix) == -1) {
+ return NULL;
+ }
+ for (i = 0; i < ARRAY_SIZE(tri_src); i++) {
+ if (((mathutils_array_parse(tri_src[i], 3, 3 | MU_ARRAY_SPILL, py_tri_src[i], error_prefix) !=
+ -1) &&
+ (mathutils_array_parse(tri_dst[i], 3, 3 | MU_ARRAY_SPILL, py_tri_dst[i], error_prefix) !=
+ -1)) == 0) {
+ return NULL;
+ }
+ }
+
+ transform_point_by_tri_v3(pt_dst, pt_src, UNPACK3(tri_dst), UNPACK3(tri_src));
+
+ return Vector_CreatePyObject(pt_dst, 3, NULL);
}
PyDoc_STRVAR(M_Geometry_points_in_planes_doc,
-".. function:: points_in_planes(planes)\n"
-"\n"
-" Returns a list of points inside all planes given and a list of index values for the planes used.\n"
-"\n"
-" :arg planes: List of planes (4D vectors).\n"
-" :type planes: list of :class:`mathutils.Vector`\n"
-" :return: two lists, once containing the vertices inside the planes, another containing the plane indices used\n"
-" :rtype: pair of lists\n"
-);
+ ".. function:: points_in_planes(planes)\n"
+ "\n"
+ " Returns a list of points inside all planes given and a list of index values for "
+ "the planes used.\n"
+ "\n"
+ " :arg planes: List of planes (4D vectors).\n"
+ " :type planes: list of :class:`mathutils.Vector`\n"
+ " :return: two lists, once containing the vertices inside the planes, another "
+ "containing the plane indices used\n"
+ " :rtype: pair of lists\n");
/* note: this function could be optimized by some spatial structure */
static PyObject *M_Geometry_points_in_planes(PyObject *UNUSED(self), PyObject *args)
{
- PyObject *py_planes;
- float (*planes)[4];
- unsigned int planes_len;
-
- if (!PyArg_ParseTuple(
- args, "O:points_in_planes",
- &py_planes))
- {
- return NULL;
- }
-
- if ((planes_len = mathutils_array_parse_alloc_v((float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
- return NULL;
- }
- else {
- /* note, this could be refactored into plain C easy - py bits are noted */
- const float eps = 0.0001f;
- const unsigned int len = (unsigned int)planes_len;
- unsigned int i, j, k, l;
-
- float n1n2[3], n2n3[3], n3n1[3];
- float potentialVertex[3];
- char *planes_used = PyMem_Malloc(sizeof(char) * len);
-
- /* python */
- PyObject *py_verts = PyList_New(0);
- PyObject *py_plane_index = PyList_New(0);
-
- memset(planes_used, 0, sizeof(char) * len);
-
- for (i = 0; i < len; i++) {
- const float *N1 = planes[i];
- for (j = i + 1; j < len; j++) {
- const float *N2 = planes[j];
- cross_v3_v3v3(n1n2, N1, N2);
- if (len_squared_v3(n1n2) > eps) {
- for (k = j + 1; k < len; k++) {
- const float *N3 = planes[k];
- cross_v3_v3v3(n2n3, N2, N3);
- if (len_squared_v3(n2n3) > eps) {
- cross_v3_v3v3(n3n1, N3, N1);
- if (len_squared_v3(n3n1) > eps) {
- const float quotient = dot_v3v3(N1, n2n3);
- if (fabsf(quotient) > eps) {
- /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
- const float quotient_ninv = -1.0f / quotient;
- potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) + (n1n2[0] * N3[3])) * quotient_ninv;
- potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) + (n1n2[1] * N3[3])) * quotient_ninv;
- potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) + (n1n2[2] * N3[3])) * quotient_ninv;
- for (l = 0; l < len; l++) {
- const float *NP = planes[l];
- if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
- break;
- }
- }
-
- if (l == len) { /* ok */
- /* python */
- PyList_APPEND(py_verts, Vector_CreatePyObject(potentialVertex, 3, NULL));
- planes_used[i] = planes_used[j] = planes_used[k] = true;
- }
- }
- }
- }
- }
- }
- }
- }
-
- PyMem_Free(planes);
-
- /* now make a list of used planes */
- for (i = 0; i < len; i++) {
- if (planes_used[i]) {
- PyList_APPEND(py_plane_index, PyLong_FromLong(i));
- }
- }
- PyMem_Free(planes_used);
-
- {
- PyObject *ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- py_verts,
- py_plane_index);
- return ret;
- }
- }
+ PyObject *py_planes;
+ float(*planes)[4];
+ unsigned int planes_len;
+
+ if (!PyArg_ParseTuple(args, "O:points_in_planes", &py_planes)) {
+ return NULL;
+ }
+
+ if ((planes_len = mathutils_array_parse_alloc_v(
+ (float **)&planes, 4, py_planes, "points_in_planes")) == -1) {
+ return NULL;
+ }
+ else {
+ /* note, this could be refactored into plain C easy - py bits are noted */
+ const float eps = 0.0001f;
+ const unsigned int len = (unsigned int)planes_len;
+ unsigned int i, j, k, l;
+
+ float n1n2[3], n2n3[3], n3n1[3];
+ float potentialVertex[3];
+ char *planes_used = PyMem_Malloc(sizeof(char) * len);
+
+ /* python */
+ PyObject *py_verts = PyList_New(0);
+ PyObject *py_plane_index = PyList_New(0);
+
+ memset(planes_used, 0, sizeof(char) * len);
+
+ for (i = 0; i < len; i++) {
+ const float *N1 = planes[i];
+ for (j = i + 1; j < len; j++) {
+ const float *N2 = planes[j];
+ cross_v3_v3v3(n1n2, N1, N2);
+ if (len_squared_v3(n1n2) > eps) {
+ for (k = j + 1; k < len; k++) {
+ const float *N3 = planes[k];
+ cross_v3_v3v3(n2n3, N2, N3);
+ if (len_squared_v3(n2n3) > eps) {
+ cross_v3_v3v3(n3n1, N3, N1);
+ if (len_squared_v3(n3n1) > eps) {
+ const float quotient = dot_v3v3(N1, n2n3);
+ if (fabsf(quotient) > eps) {
+ /* potentialVertex = (n2n3 * N1[3] + n3n1 * N2[3] + n1n2 * N3[3]) * (-1.0 / quotient); */
+ const float quotient_ninv = -1.0f / quotient;
+ potentialVertex[0] = ((n2n3[0] * N1[3]) + (n3n1[0] * N2[3]) +
+ (n1n2[0] * N3[3])) *
+ quotient_ninv;
+ potentialVertex[1] = ((n2n3[1] * N1[3]) + (n3n1[1] * N2[3]) +
+ (n1n2[1] * N3[3])) *
+ quotient_ninv;
+ potentialVertex[2] = ((n2n3[2] * N1[3]) + (n3n1[2] * N2[3]) +
+ (n1n2[2] * N3[3])) *
+ quotient_ninv;
+ for (l = 0; l < len; l++) {
+ const float *NP = planes[l];
+ if ((dot_v3v3(NP, potentialVertex) + NP[3]) > 0.000001f) {
+ break;
+ }
+ }
+
+ if (l == len) { /* ok */
+ /* python */
+ PyList_APPEND(py_verts, Vector_CreatePyObject(potentialVertex, 3, NULL));
+ planes_used[i] = planes_used[j] = planes_used[k] = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ PyMem_Free(planes);
+
+ /* now make a list of used planes */
+ for (i = 0; i < len; i++) {
+ if (planes_used[i]) {
+ PyList_APPEND(py_plane_index, PyLong_FromLong(i));
+ }
+ }
+ PyMem_Free(planes_used);
+
+ {
+ PyObject *ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, py_verts, py_plane_index);
+ return ret;
+ }
+ }
}
#ifndef MATH_STANDALONE
PyDoc_STRVAR(M_Geometry_interpolate_bezier_doc,
-".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
-"\n"
-" Interpolate a bezier spline segment.\n"
-"\n"
-" :arg knot1: First bezier spline point.\n"
-" :type knot1: :class:`mathutils.Vector`\n"
-" :arg handle1: First bezier spline handle.\n"
-" :type handle1: :class:`mathutils.Vector`\n"
-" :arg handle2: Second bezier spline handle.\n"
-" :type handle2: :class:`mathutils.Vector`\n"
-" :arg knot2: Second bezier spline point.\n"
-" :type knot2: :class:`mathutils.Vector`\n"
-" :arg resolution: Number of points to return.\n"
-" :type resolution: int\n"
-" :return: The interpolated points\n"
-" :rtype: list of :class:`mathutils.Vector`'s\n"
-);
+ ".. function:: interpolate_bezier(knot1, handle1, handle2, knot2, resolution)\n"
+ "\n"
+ " Interpolate a bezier spline segment.\n"
+ "\n"
+ " :arg knot1: First bezier spline point.\n"
+ " :type knot1: :class:`mathutils.Vector`\n"
+ " :arg handle1: First bezier spline handle.\n"
+ " :type handle1: :class:`mathutils.Vector`\n"
+ " :arg handle2: Second bezier spline handle.\n"
+ " :type handle2: :class:`mathutils.Vector`\n"
+ " :arg knot2: Second bezier spline point.\n"
+ " :type knot2: :class:`mathutils.Vector`\n"
+ " :arg resolution: Number of points to return.\n"
+ " :type resolution: int\n"
+ " :return: The interpolated points\n"
+ " :rtype: list of :class:`mathutils.Vector`'s\n");
static PyObject *M_Geometry_interpolate_bezier(PyObject *UNUSED(self), PyObject *args)
{
- const char *error_prefix = "interpolate_bezier";
- PyObject *py_data[4];
- float data[4][4] = {{0.0f}};
- int resolu;
- int dims = 0;
- int i;
- float *coord_array, *fp;
- PyObject *list;
-
- if (!PyArg_ParseTuple(
- args, "OOOOi:interpolate_bezier",
- UNPACK4_EX(&, py_data, ), &resolu))
- {
- return NULL;
- }
-
- for (i = 0; i < 4; i++) {
- int dims_tmp;
- if ((dims_tmp = mathutils_array_parse(data[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_data[i], error_prefix)) == -1) {
- return NULL;
- }
- dims = max_ii(dims, dims_tmp);
- }
-
- if (resolu <= 1) {
- PyErr_SetString(PyExc_ValueError,
- "resolution must be 2 or over");
- return NULL;
- }
-
- coord_array = MEM_callocN(dims * (resolu) * sizeof(float), error_prefix);
- for (i = 0; i < dims; i++) {
- BKE_curve_forward_diff_bezier(UNPACK4_EX(, data, [i]), coord_array + i, resolu - 1, sizeof(float) * dims);
- }
-
- list = PyList_New(resolu);
- fp = coord_array;
- for (i = 0; i < resolu; i++, fp = fp + dims) {
- PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, NULL));
- }
- MEM_freeN(coord_array);
- return list;
+ const char *error_prefix = "interpolate_bezier";
+ PyObject *py_data[4];
+ float data[4][4] = {{0.0f}};
+ int resolu;
+ int dims = 0;
+ int i;
+ float *coord_array, *fp;
+ PyObject *list;
+
+ if (!PyArg_ParseTuple(args, "OOOOi:interpolate_bezier", UNPACK4_EX(&, py_data, ), &resolu)) {
+ return NULL;
+ }
+
+ for (i = 0; i < 4; i++) {
+ int dims_tmp;
+ if ((dims_tmp = mathutils_array_parse(
+ data[i], 2, 3 | MU_ARRAY_SPILL | MU_ARRAY_ZERO, py_data[i], error_prefix)) == -1) {
+ return NULL;
+ }
+ dims = max_ii(dims, dims_tmp);
+ }
+
+ if (resolu <= 1) {
+ PyErr_SetString(PyExc_ValueError, "resolution must be 2 or over");
+ return NULL;
+ }
+
+ coord_array = MEM_callocN(dims * (resolu) * sizeof(float), error_prefix);
+ for (i = 0; i < dims; i++) {
+ BKE_curve_forward_diff_bezier(
+ UNPACK4_EX(, data, [i]), coord_array + i, resolu - 1, sizeof(float) * dims);
+ }
+
+ list = PyList_New(resolu);
+ fp = coord_array;
+ for (i = 0; i < resolu; i++, fp = fp + dims) {
+ PyList_SET_ITEM(list, i, Vector_CreatePyObject(fp, dims, NULL));
+ }
+ MEM_freeN(coord_array);
+ return list;
}
-
PyDoc_STRVAR(M_Geometry_tessellate_polygon_doc,
-".. function:: tessellate_polygon(veclist_list)\n"
-"\n"
-" Takes a list of polylines (each point a vector) and returns the point indices for a polyline filled with triangles.\n"
-"\n"
-" :arg veclist_list: list of polylines\n"
-" :rtype: list\n"
-);
+ ".. function:: tessellate_polygon(veclist_list)\n"
+ "\n"
+ " Takes a list of polylines (each point a vector) and returns the point indices "
+ "for a polyline filled with triangles.\n"
+ "\n"
+ " :arg veclist_list: list of polylines\n"
+ " :rtype: list\n");
/* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject *polyLineSeq)
{
- PyObject *tri_list; /*return this list of tri's */
- PyObject *polyLine, *polyVec;
- int i, len_polylines, len_polypoints, ls_error = 0;
-
- /* display listbase */
- ListBase dispbase = {NULL, NULL};
- DispList *dl;
- float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
- int index, *dl_face, totpoints = 0;
-
- if (!PySequence_Check(polyLineSeq)) {
- PyErr_SetString(PyExc_TypeError,
- "expected a sequence of poly lines");
- return NULL;
- }
-
- len_polylines = PySequence_Size(polyLineSeq);
-
- for (i = 0; i < len_polylines; i++) {
- polyLine = PySequence_GetItem(polyLineSeq, i);
- if (!PySequence_Check(polyLine)) {
- BKE_displist_free(&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");
- return NULL;
- }
-
- len_polypoints = PySequence_Size(polyLine);
- if (len_polypoints > 0) { /* don't bother adding edges as polylines */
-#if 0
- 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");
- return NULL;
- }
-#endif
- dl = MEM_callocN(sizeof(DispList), "poly disp");
- BLI_addtail(&dispbase, dl);
- dl->type = DL_INDEX3;
- dl->nr = len_polypoints;
- dl->type = DL_POLY;
- dl->parts = 1; /* no faces, 1 edge loop */
- dl->col = 0; /* no material */
- dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
- dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
-
- for (index = 0; index < len_polypoints; index++, fp += 3) {
- polyVec = PySequence_GetItem(polyLine, index);
- if (VectorObject_Check(polyVec)) {
-
- if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1) {
- ls_error = 1;
- }
-
- fp[0] = ((VectorObject *)polyVec)->vec[0];
- fp[1] = ((VectorObject *)polyVec)->vec[1];
- if (((VectorObject *)polyVec)->size > 2) {
- fp[2] = ((VectorObject *)polyVec)->vec[2];
- }
- else {
- /* if its a 2d vector then set the z to be zero */
- fp[2] = 0.0f;
- }
- }
- else {
- ls_error = 1;
- }
-
- totpoints++;
- Py_DECREF(polyVec);
- }
- }
- Py_DECREF(polyLine);
- }
-
- if (ls_error) {
- BKE_displist_free(&dispbase); /* possible some dl was allocated */
- 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 */
- /* TODO, add normal arg */
- BKE_displist_fill(&dispbase, &dispbase, NULL, false);
-
- /* The faces are stored in a new DisplayList
- * that's added to the head of the listbase */
- dl = dispbase.first;
-
- tri_list = PyList_New(dl->parts);
- if (!tri_list) {
- BKE_displist_free(&dispbase);
- PyErr_SetString(PyExc_RuntimeError,
- "failed to make a new list");
- return NULL;
- }
-
- index = 0;
- dl_face = dl->index;
- while (index < dl->parts) {
- PyList_SET_ITEM(tri_list, index, PyC_Tuple_Pack_I32(dl_face[0], dl_face[1], dl_face[2]));
- dl_face += 3;
- index++;
- }
- BKE_displist_free(&dispbase);
- }
- else {
- /* no points, do this so scripts don't barf */
- BKE_displist_free(&dispbase); /* possible some dl was allocated */
- tri_list = PyList_New(0);
- }
-
- return tri_list;
+ PyObject *tri_list; /*return this list of tri's */
+ PyObject *polyLine, *polyVec;
+ int i, len_polylines, len_polypoints, ls_error = 0;
+
+ /* display listbase */
+ ListBase dispbase = {NULL, NULL};
+ DispList *dl;
+ float *fp; /*pointer to the array of malloced dl->verts to set the points from the vectors */
+ int index, *dl_face, totpoints = 0;
+
+ if (!PySequence_Check(polyLineSeq)) {
+ PyErr_SetString(PyExc_TypeError, "expected a sequence of poly lines");
+ return NULL;
+ }
+
+ len_polylines = PySequence_Size(polyLineSeq);
+
+ for (i = 0; i < len_polylines; i++) {
+ polyLine = PySequence_GetItem(polyLineSeq, i);
+ if (!PySequence_Check(polyLine)) {
+ BKE_displist_free(&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");
+ return NULL;
+ }
+
+ len_polypoints = PySequence_Size(polyLine);
+ if (len_polypoints > 0) { /* don't bother adding edges as polylines */
+# if 0
+ 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");
+ return NULL;
+ }
+# endif
+ dl = MEM_callocN(sizeof(DispList), "poly disp");
+ BLI_addtail(&dispbase, dl);
+ dl->type = DL_INDEX3;
+ dl->nr = len_polypoints;
+ dl->type = DL_POLY;
+ dl->parts = 1; /* no faces, 1 edge loop */
+ dl->col = 0; /* no material */
+ dl->verts = fp = MEM_callocN(sizeof(float) * 3 * len_polypoints, "dl verts");
+ dl->index = MEM_callocN(sizeof(int) * 3 * len_polypoints, "dl index");
+
+ for (index = 0; index < len_polypoints; index++, fp += 3) {
+ polyVec = PySequence_GetItem(polyLine, index);
+ if (VectorObject_Check(polyVec)) {
+
+ if (BaseMath_ReadCallback((VectorObject *)polyVec) == -1) {
+ ls_error = 1;
+ }
+
+ fp[0] = ((VectorObject *)polyVec)->vec[0];
+ fp[1] = ((VectorObject *)polyVec)->vec[1];
+ if (((VectorObject *)polyVec)->size > 2) {
+ fp[2] = ((VectorObject *)polyVec)->vec[2];
+ }
+ else {
+ /* if its a 2d vector then set the z to be zero */
+ fp[2] = 0.0f;
+ }
+ }
+ else {
+ ls_error = 1;
+ }
+
+ totpoints++;
+ Py_DECREF(polyVec);
+ }
+ }
+ Py_DECREF(polyLine);
+ }
+
+ if (ls_error) {
+ BKE_displist_free(&dispbase); /* possible some dl was allocated */
+ 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 */
+ /* TODO, add normal arg */
+ BKE_displist_fill(&dispbase, &dispbase, NULL, false);
+
+ /* The faces are stored in a new DisplayList
+ * that's added to the head of the listbase */
+ dl = dispbase.first;
+
+ tri_list = PyList_New(dl->parts);
+ if (!tri_list) {
+ BKE_displist_free(&dispbase);
+ PyErr_SetString(PyExc_RuntimeError, "failed to make a new list");
+ return NULL;
+ }
+
+ index = 0;
+ dl_face = dl->index;
+ while (index < dl->parts) {
+ PyList_SET_ITEM(tri_list, index, PyC_Tuple_Pack_I32(dl_face[0], dl_face[1], dl_face[2]));
+ dl_face += 3;
+ index++;
+ }
+ BKE_displist_free(&dispbase);
+ }
+ else {
+ /* no points, do this so scripts don't barf */
+ BKE_displist_free(&dispbase); /* possible some dl was allocated */
+ tri_list = PyList_New(0);
+ }
+
+ return tri_list;
}
-
static int boxPack_FromPyObject(PyObject *value, BoxPack **boxarray)
{
- Py_ssize_t len, i;
- PyObject *list_item, *item_1, *item_2;
- BoxPack *box;
-
-
- /* Error checking must already be done */
- if (!PyList_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "can only back a list of [x, y, w, h]");
- return -1;
- }
-
- len = PyList_GET_SIZE(value);
-
- *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
-
-
- for (i = 0; i < len; i++) {
- list_item = PyList_GET_ITEM(value, i);
- if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
- MEM_freeN(*boxarray);
- PyErr_SetString(PyExc_TypeError,
- "can only pack a list of [x, y, w, h]");
- return -1;
- }
-
- box = (*boxarray) + i;
-
- item_1 = PyList_GET_ITEM(list_item, 2);
- item_2 = PyList_GET_ITEM(list_item, 3);
-
- box->w = (float)PyFloat_AsDouble(item_1);
- box->h = (float)PyFloat_AsDouble(item_2);
- box->index = i;
-
- /* accounts for error case too and overwrites with own error */
- if (box->w < 0.0f || box->h < 0.0f) {
- MEM_freeN(*boxarray);
- PyErr_SetString(PyExc_TypeError,
- "error parsing width and height values from list: "
- "[x, y, w, h], not numbers or below zero");
- return -1;
- }
-
- /* verts will be added later */
- }
- return 0;
+ Py_ssize_t len, i;
+ PyObject *list_item, *item_1, *item_2;
+ BoxPack *box;
+
+ /* Error checking must already be done */
+ if (!PyList_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "can only back a list of [x, y, w, h]");
+ return -1;
+ }
+
+ len = PyList_GET_SIZE(value);
+
+ *boxarray = MEM_mallocN(len * sizeof(BoxPack), "BoxPack box");
+
+ for (i = 0; i < len; i++) {
+ list_item = PyList_GET_ITEM(value, i);
+ if (!PyList_Check(list_item) || PyList_GET_SIZE(list_item) < 4) {
+ MEM_freeN(*boxarray);
+ PyErr_SetString(PyExc_TypeError, "can only pack a list of [x, y, w, h]");
+ return -1;
+ }
+
+ box = (*boxarray) + i;
+
+ item_1 = PyList_GET_ITEM(list_item, 2);
+ item_2 = PyList_GET_ITEM(list_item, 3);
+
+ box->w = (float)PyFloat_AsDouble(item_1);
+ box->h = (float)PyFloat_AsDouble(item_2);
+ box->index = i;
+
+ /* accounts for error case too and overwrites with own error */
+ if (box->w < 0.0f || box->h < 0.0f) {
+ MEM_freeN(*boxarray);
+ PyErr_SetString(PyExc_TypeError,
+ "error parsing width and height values from list: "
+ "[x, y, w, h], not numbers or below zero");
+ return -1;
+ }
+
+ /* verts will be added later */
+ }
+ return 0;
}
static void boxPack_ToPyObject(PyObject *value, BoxPack **boxarray)
{
- Py_ssize_t len, i;
- PyObject *list_item;
- BoxPack *box;
-
- len = PyList_GET_SIZE(value);
-
- for (i = 0; i < len; i++) {
- box = (*boxarray) + i;
- list_item = PyList_GET_ITEM(value, box->index);
- PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
- PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
- }
- MEM_freeN(*boxarray);
+ Py_ssize_t len, i;
+ PyObject *list_item;
+ BoxPack *box;
+
+ len = PyList_GET_SIZE(value);
+
+ for (i = 0; i < len; i++) {
+ box = (*boxarray) + i;
+ list_item = PyList_GET_ITEM(value, box->index);
+ PyList_SET_ITEM(list_item, 0, PyFloat_FromDouble(box->x));
+ PyList_SET_ITEM(list_item, 1, PyFloat_FromDouble(box->y));
+ }
+ MEM_freeN(*boxarray);
}
PyDoc_STRVAR(M_Geometry_box_pack_2d_doc,
-".. function:: box_pack_2d(boxes)\n"
-"\n"
-" Returns the normal of the 3D tri or quad.\n"
-"\n"
-" :arg boxes: list of boxes, each box is a list where the first 4 items are [x, y, width, height, ...] other items are ignored.\n"
-" :type boxes: list\n"
-" :return: the width and height of the packed bounding box\n"
-" :rtype: tuple, pair of floats\n"
-);
+ ".. function:: box_pack_2d(boxes)\n"
+ "\n"
+ " Returns the normal of the 3D tri or quad.\n"
+ "\n"
+ " :arg boxes: list of boxes, each box is a list where the first 4 items are [x, y, "
+ "width, height, ...] other items are ignored.\n"
+ " :type boxes: list\n"
+ " :return: the width and height of the packed bounding box\n"
+ " :rtype: tuple, pair of floats\n");
static PyObject *M_Geometry_box_pack_2d(PyObject *UNUSED(self), PyObject *boxlist)
{
- float tot_width = 0.0f, tot_height = 0.0f;
- Py_ssize_t len;
-
- PyObject *ret;
-
- if (!PyList_Check(boxlist)) {
- PyErr_SetString(PyExc_TypeError,
- "expected a list of boxes [[x, y, w, h], ... ]");
- return NULL;
- }
-
- len = PyList_GET_SIZE(boxlist);
- if (len) {
- BoxPack *boxarray = NULL;
- if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
- return NULL; /* exception set */
- }
-
- /* Non Python function */
- BLI_box_pack_2d(boxarray, len, &tot_width, &tot_height);
-
- boxPack_ToPyObject(boxlist, &boxarray);
- }
-
- ret = PyTuple_New(2);
- PyTuple_SET_ITEMS(ret,
- PyFloat_FromDouble(tot_width),
- PyFloat_FromDouble(tot_height));
- return ret;
+ float tot_width = 0.0f, tot_height = 0.0f;
+ Py_ssize_t len;
+
+ PyObject *ret;
+
+ if (!PyList_Check(boxlist)) {
+ PyErr_SetString(PyExc_TypeError, "expected a list of boxes [[x, y, w, h], ... ]");
+ return NULL;
+ }
+
+ len = PyList_GET_SIZE(boxlist);
+ if (len) {
+ BoxPack *boxarray = NULL;
+ if (boxPack_FromPyObject(boxlist, &boxarray) == -1) {
+ return NULL; /* exception set */
+ }
+
+ /* Non Python function */
+ BLI_box_pack_2d(boxarray, len, &tot_width, &tot_height);
+
+ boxPack_ToPyObject(boxlist, &boxarray);
+ }
+
+ ret = PyTuple_New(2);
+ PyTuple_SET_ITEMS(ret, PyFloat_FromDouble(tot_width), PyFloat_FromDouble(tot_height));
+ return ret;
}
PyDoc_STRVAR(M_Geometry_box_fit_2d_doc,
-".. function:: box_fit_2d(points)\n"
-"\n"
-" Returns an angle that best fits the points to an axis aligned rectangle\n"
-"\n"
-" :arg points: list of 2d points.\n"
-" :type points: list\n"
-" :return: angle\n"
-" :rtype: float\n"
-);
+ ".. function:: box_fit_2d(points)\n"
+ "\n"
+ " Returns an angle that best fits the points to an axis aligned rectangle\n"
+ "\n"
+ " :arg points: list of 2d points.\n"
+ " :type points: list\n"
+ " :return: angle\n"
+ " :rtype: float\n");
static PyObject *M_Geometry_box_fit_2d(PyObject *UNUSED(self), PyObject *pointlist)
{
- float (*points)[2];
- Py_ssize_t len;
+ float(*points)[2];
+ Py_ssize_t len;
- float angle = 0.0f;
+ float angle = 0.0f;
- len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "box_fit_2d");
- if (len == -1) {
- return NULL;
- }
+ len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "box_fit_2d");
+ if (len == -1) {
+ return NULL;
+ }
- if (len) {
- /* Non Python function */
- angle = BLI_convexhull_aabb_fit_points_2d(points, len);
+ if (len) {
+ /* Non Python function */
+ angle = BLI_convexhull_aabb_fit_points_2d(points, len);
- PyMem_Free(points);
- }
+ PyMem_Free(points);
+ }
-
- return PyFloat_FromDouble(angle);
+ return PyFloat_FromDouble(angle);
}
PyDoc_STRVAR(M_Geometry_convex_hull_2d_doc,
-".. function:: convex_hull_2d(points)\n"
-"\n"
-" Returns a list of indices into the list given\n"
-"\n"
-" :arg points: list of 2d points.\n"
-" :type points: list\n"
-" :return: a list of indices\n"
-" :rtype: list of ints\n"
-);
+ ".. function:: convex_hull_2d(points)\n"
+ "\n"
+ " Returns a list of indices into the list given\n"
+ "\n"
+ " :arg points: list of 2d points.\n"
+ " :type points: list\n"
+ " :return: a list of indices\n"
+ " :rtype: list of ints\n");
static PyObject *M_Geometry_convex_hull_2d(PyObject *UNUSED(self), PyObject *pointlist)
{
- float (*points)[2];
- Py_ssize_t len;
-
- PyObject *ret;
+ float(*points)[2];
+ Py_ssize_t len;
- len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "convex_hull_2d");
- if (len == -1) {
- return NULL;
- }
+ PyObject *ret;
- if (len) {
- int *index_map;
- Py_ssize_t len_ret, i;
+ len = mathutils_array_parse_alloc_v(((float **)&points), 2, pointlist, "convex_hull_2d");
+ if (len == -1) {
+ return NULL;
+ }
- index_map = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
+ if (len) {
+ int *index_map;
+ Py_ssize_t len_ret, i;
- /* Non Python function */
- len_ret = BLI_convexhull_2d(points, len, index_map);
+ index_map = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
- ret = PyList_New(len_ret);
- for (i = 0; i < len_ret; i++) {
- PyList_SET_ITEM(ret, i, PyLong_FromLong(index_map[i]));
- }
+ /* Non Python function */
+ len_ret = BLI_convexhull_2d(points, len, index_map);
- MEM_freeN(index_map);
+ ret = PyList_New(len_ret);
+ for (i = 0; i < len_ret; i++) {
+ PyList_SET_ITEM(ret, i, PyLong_FromLong(index_map[i]));
+ }
- PyMem_Free(points);
- }
- else {
- ret = PyList_New(0);
- }
+ MEM_freeN(index_map);
+ PyMem_Free(points);
+ }
+ else {
+ ret = PyList_New(0);
+ }
- return ret;
+ return ret;
}
#endif /* MATH_STANDALONE */
-
static PyMethodDef M_Geometry_methods[] = {
- {"intersect_ray_tri", (PyCFunction) M_Geometry_intersect_ray_tri, METH_VARARGS, M_Geometry_intersect_ray_tri_doc},
- {"intersect_point_line", (PyCFunction) M_Geometry_intersect_point_line, METH_VARARGS, M_Geometry_intersect_point_line_doc},
- {"intersect_point_tri", (PyCFunction) M_Geometry_intersect_point_tri, METH_VARARGS, M_Geometry_intersect_point_tri_doc},
- {"intersect_point_tri_2d", (PyCFunction) M_Geometry_intersect_point_tri_2d, METH_VARARGS, M_Geometry_intersect_point_tri_2d_doc},
- {"intersect_point_quad_2d", (PyCFunction) M_Geometry_intersect_point_quad_2d, METH_VARARGS, M_Geometry_intersect_point_quad_2d_doc},
- {"intersect_line_line", (PyCFunction) M_Geometry_intersect_line_line, METH_VARARGS, M_Geometry_intersect_line_line_doc},
- {"intersect_line_line_2d", (PyCFunction) M_Geometry_intersect_line_line_2d, METH_VARARGS, M_Geometry_intersect_line_line_2d_doc},
- {"intersect_line_plane", (PyCFunction) M_Geometry_intersect_line_plane, METH_VARARGS, M_Geometry_intersect_line_plane_doc},
- {"intersect_plane_plane", (PyCFunction) M_Geometry_intersect_plane_plane, METH_VARARGS, M_Geometry_intersect_plane_plane_doc},
- {"intersect_line_sphere", (PyCFunction) M_Geometry_intersect_line_sphere, METH_VARARGS, M_Geometry_intersect_line_sphere_doc},
- {"intersect_line_sphere_2d", (PyCFunction) M_Geometry_intersect_line_sphere_2d, METH_VARARGS, M_Geometry_intersect_line_sphere_2d_doc},
- {"distance_point_to_plane", (PyCFunction) M_Geometry_distance_point_to_plane, METH_VARARGS, M_Geometry_distance_point_to_plane_doc},
- {"intersect_sphere_sphere_2d", (PyCFunction) M_Geometry_intersect_sphere_sphere_2d, METH_VARARGS, M_Geometry_intersect_sphere_sphere_2d_doc},
- {"area_tri", (PyCFunction) M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
- {"volume_tetrahedron", (PyCFunction) M_Geometry_volume_tetrahedron, METH_VARARGS, M_Geometry_volume_tetrahedron_doc},
- {"normal", (PyCFunction) M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
- {"barycentric_transform", (PyCFunction) M_Geometry_barycentric_transform, METH_VARARGS, M_Geometry_barycentric_transform_doc},
- {"points_in_planes", (PyCFunction) M_Geometry_points_in_planes, METH_VARARGS, M_Geometry_points_in_planes_doc},
+ {"intersect_ray_tri",
+ (PyCFunction)M_Geometry_intersect_ray_tri,
+ METH_VARARGS,
+ M_Geometry_intersect_ray_tri_doc},
+ {"intersect_point_line",
+ (PyCFunction)M_Geometry_intersect_point_line,
+ METH_VARARGS,
+ M_Geometry_intersect_point_line_doc},
+ {"intersect_point_tri",
+ (PyCFunction)M_Geometry_intersect_point_tri,
+ METH_VARARGS,
+ M_Geometry_intersect_point_tri_doc},
+ {"intersect_point_tri_2d",
+ (PyCFunction)M_Geometry_intersect_point_tri_2d,
+ METH_VARARGS,
+ M_Geometry_intersect_point_tri_2d_doc},
+ {"intersect_point_quad_2d",
+ (PyCFunction)M_Geometry_intersect_point_quad_2d,
+ METH_VARARGS,
+ M_Geometry_intersect_point_quad_2d_doc},
+ {"intersect_line_line",
+ (PyCFunction)M_Geometry_intersect_line_line,
+ METH_VARARGS,
+ M_Geometry_intersect_line_line_doc},
+ {"intersect_line_line_2d",
+ (PyCFunction)M_Geometry_intersect_line_line_2d,
+ METH_VARARGS,
+ M_Geometry_intersect_line_line_2d_doc},
+ {"intersect_line_plane",
+ (PyCFunction)M_Geometry_intersect_line_plane,
+ METH_VARARGS,
+ M_Geometry_intersect_line_plane_doc},
+ {"intersect_plane_plane",
+ (PyCFunction)M_Geometry_intersect_plane_plane,
+ METH_VARARGS,
+ M_Geometry_intersect_plane_plane_doc},
+ {"intersect_line_sphere",
+ (PyCFunction)M_Geometry_intersect_line_sphere,
+ METH_VARARGS,
+ M_Geometry_intersect_line_sphere_doc},
+ {"intersect_line_sphere_2d",
+ (PyCFunction)M_Geometry_intersect_line_sphere_2d,
+ METH_VARARGS,
+ M_Geometry_intersect_line_sphere_2d_doc},
+ {"distance_point_to_plane",
+ (PyCFunction)M_Geometry_distance_point_to_plane,
+ METH_VARARGS,
+ M_Geometry_distance_point_to_plane_doc},
+ {"intersect_sphere_sphere_2d",
+ (PyCFunction)M_Geometry_intersect_sphere_sphere_2d,
+ METH_VARARGS,
+ M_Geometry_intersect_sphere_sphere_2d_doc},
+ {"area_tri", (PyCFunction)M_Geometry_area_tri, METH_VARARGS, M_Geometry_area_tri_doc},
+ {"volume_tetrahedron",
+ (PyCFunction)M_Geometry_volume_tetrahedron,
+ METH_VARARGS,
+ M_Geometry_volume_tetrahedron_doc},
+ {"normal", (PyCFunction)M_Geometry_normal, METH_VARARGS, M_Geometry_normal_doc},
+ {"barycentric_transform",
+ (PyCFunction)M_Geometry_barycentric_transform,
+ METH_VARARGS,
+ M_Geometry_barycentric_transform_doc},
+ {"points_in_planes",
+ (PyCFunction)M_Geometry_points_in_planes,
+ METH_VARARGS,
+ M_Geometry_points_in_planes_doc},
#ifndef MATH_STANDALONE
- {"interpolate_bezier", (PyCFunction) M_Geometry_interpolate_bezier, METH_VARARGS, M_Geometry_interpolate_bezier_doc},
- {"tessellate_polygon", (PyCFunction) M_Geometry_tessellate_polygon, METH_O, M_Geometry_tessellate_polygon_doc},
- {"convex_hull_2d", (PyCFunction) M_Geometry_convex_hull_2d, METH_O, M_Geometry_convex_hull_2d_doc},
- {"box_fit_2d", (PyCFunction) M_Geometry_box_fit_2d, METH_O, M_Geometry_box_fit_2d_doc},
- {"box_pack_2d", (PyCFunction) M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
+ {"interpolate_bezier",
+ (PyCFunction)M_Geometry_interpolate_bezier,
+ METH_VARARGS,
+ M_Geometry_interpolate_bezier_doc},
+ {"tessellate_polygon",
+ (PyCFunction)M_Geometry_tessellate_polygon,
+ METH_O,
+ M_Geometry_tessellate_polygon_doc},
+ {"convex_hull_2d",
+ (PyCFunction)M_Geometry_convex_hull_2d,
+ METH_O,
+ M_Geometry_convex_hull_2d_doc},
+ {"box_fit_2d", (PyCFunction)M_Geometry_box_fit_2d, METH_O, M_Geometry_box_fit_2d_doc},
+ {"box_pack_2d", (PyCFunction)M_Geometry_box_pack_2d, METH_O, M_Geometry_box_pack_2d_doc},
#endif
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_Geometry_module_def = {
- PyModuleDef_HEAD_INIT,
- "mathutils.geometry", /* m_name */
- M_Geometry_doc, /* m_doc */
- 0, /* m_size */
- M_Geometry_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils.geometry", /* m_name */
+ M_Geometry_doc, /* m_doc */
+ 0, /* m_size */
+ M_Geometry_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
/*----------------------------MODULE INIT-------------------------*/
PyMODINIT_FUNC PyInit_mathutils_geometry(void)
{
- PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
- return submodule;
+ PyObject *submodule = PyModule_Create(&M_Geometry_module_def);
+ return submodule;
}
diff --git a/source/blender/python/mathutils/mathutils_interpolate.c b/source/blender/python/mathutils/mathutils_interpolate.c
index 792f8b1f065..6abb66899d5 100644
--- a/source/blender/python/mathutils/mathutils_interpolate.c
+++ b/source/blender/python/mathutils/mathutils_interpolate.c
@@ -18,7 +18,6 @@
* \ingroup pymathutils
*/
-
#include <Python.h>
#include "mathutils.h"
@@ -32,105 +31,100 @@
#endif
/*-------------------------DOC STRINGS ---------------------------*/
-PyDoc_STRVAR(M_Interpolate_doc,
-"The Blender interpolate module"
-);
+PyDoc_STRVAR(M_Interpolate_doc, "The Blender interpolate module");
/* ---------------------------------WEIGHT CALCULATION ----------------------- */
#ifndef MATH_STANDALONE
PyDoc_STRVAR(M_Interpolate_poly_3d_calc_doc,
-".. function:: poly_3d_calc(veclist, pt)\n"
-"\n"
-" Calculate barycentric weights for a point on a polygon.\n"
-"\n"
-" :arg veclist: list of vectors\n"
-" :arg pt: point"
-" :rtype: list of per-vector weights\n"
-);
+ ".. function:: poly_3d_calc(veclist, pt)\n"
+ "\n"
+ " Calculate barycentric weights for a point on a polygon.\n"
+ "\n"
+ " :arg veclist: list of vectors\n"
+ " :arg pt: point"
+ " :rtype: list of per-vector weights\n");
static PyObject *M_Interpolate_poly_3d_calc(PyObject *UNUSED(self), PyObject *args)
{
- float fp[3];
- float (*vecs)[3];
- Py_ssize_t len;
-
- PyObject *point, *veclist, *ret;
- int i;
-
- if (!PyArg_ParseTuple(
- args, "OO!:poly_3d_calc",
- &veclist,
- &vector_Type, &point))
- {
- return NULL;
- }
-
- if (BaseMath_ReadCallback((VectorObject *)point) == -1) {
- return NULL;
- }
-
- fp[0] = ((VectorObject *)point)->vec[0];
- fp[1] = ((VectorObject *)point)->vec[1];
- if (((VectorObject *)point)->size > 2) {
- fp[2] = ((VectorObject *)point)->vec[2];
- }
- else {
- /* if its a 2d vector then set the z to be zero */
- fp[2] = 0.0f;
- }
-
- len = mathutils_array_parse_alloc_v(((float **)&vecs), 3, veclist, __func__);
- if (len == -1) {
- return NULL;
- }
-
- if (len) {
- float *weights = MEM_mallocN(sizeof(float) * len, __func__);
-
- interp_weights_poly_v3(weights, vecs, len, fp);
-
- ret = PyList_New(len);
- for (i = 0; i < len; i++) {
- PyList_SET_ITEM(ret, i, PyFloat_FromDouble(weights[i]));
- }
-
- MEM_freeN(weights);
-
- PyMem_Free(vecs);
- }
- else {
- ret = PyList_New(0);
- }
-
- return ret;
+ float fp[3];
+ float(*vecs)[3];
+ Py_ssize_t len;
+
+ PyObject *point, *veclist, *ret;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "OO!:poly_3d_calc", &veclist, &vector_Type, &point)) {
+ return NULL;
+ }
+
+ if (BaseMath_ReadCallback((VectorObject *)point) == -1) {
+ return NULL;
+ }
+
+ fp[0] = ((VectorObject *)point)->vec[0];
+ fp[1] = ((VectorObject *)point)->vec[1];
+ if (((VectorObject *)point)->size > 2) {
+ fp[2] = ((VectorObject *)point)->vec[2];
+ }
+ else {
+ /* if its a 2d vector then set the z to be zero */
+ fp[2] = 0.0f;
+ }
+
+ len = mathutils_array_parse_alloc_v(((float **)&vecs), 3, veclist, __func__);
+ if (len == -1) {
+ return NULL;
+ }
+
+ if (len) {
+ float *weights = MEM_mallocN(sizeof(float) * len, __func__);
+
+ interp_weights_poly_v3(weights, vecs, len, fp);
+
+ ret = PyList_New(len);
+ for (i = 0; i < len; i++) {
+ PyList_SET_ITEM(ret, i, PyFloat_FromDouble(weights[i]));
+ }
+
+ MEM_freeN(weights);
+
+ PyMem_Free(vecs);
+ }
+ else {
+ ret = PyList_New(0);
+ }
+
+ return ret;
}
#endif /* MATH_STANDALONE */
-
static PyMethodDef M_Interpolate_methods[] = {
#ifndef MATH_STANDALONE
- {"poly_3d_calc", (PyCFunction) M_Interpolate_poly_3d_calc, METH_VARARGS, M_Interpolate_poly_3d_calc_doc},
+ {"poly_3d_calc",
+ (PyCFunction)M_Interpolate_poly_3d_calc,
+ METH_VARARGS,
+ M_Interpolate_poly_3d_calc_doc},
#endif
- {NULL, NULL, 0, NULL},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_Interpolate_module_def = {
- PyModuleDef_HEAD_INIT,
- "mathutils.interpolate", /* m_name */
- M_Interpolate_doc, /* m_doc */
- 0, /* m_size */
- M_Interpolate_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils.interpolate", /* m_name */
+ M_Interpolate_doc, /* m_doc */
+ 0, /* m_size */
+ M_Interpolate_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
/*----------------------------MODULE INIT-------------------------*/
PyMODINIT_FUNC PyInit_mathutils_interpolate(void)
{
- PyObject *submodule = PyModule_Create(&M_Interpolate_module_def);
- return submodule;
+ PyObject *submodule = PyModule_Create(&M_Interpolate_module_def);
+ return submodule;
}
diff --git a/source/blender/python/mathutils/mathutils_kdtree.c b/source/blender/python/mathutils/mathutils_kdtree.c
index b1cda85f6ea..b8a7f4d8708 100644
--- a/source/blender/python/mathutils/mathutils_kdtree.c
+++ b/source/blender/python/mathutils/mathutils_kdtree.c
@@ -32,61 +32,58 @@
#include "../generic/python_utildefines.h"
#include "mathutils.h"
-#include "mathutils_kdtree.h" /* own include */
+#include "mathutils_kdtree.h" /* own include */
#include "BLI_strict_flags.h"
typedef struct {
- PyObject_HEAD
- KDTree_3d *obj;
- unsigned int maxsize;
- unsigned int count;
- unsigned int count_balance; /* size when we last balanced */
+ PyObject_HEAD KDTree_3d *obj;
+ unsigned int maxsize;
+ unsigned int count;
+ unsigned int count_balance; /* size when we last balanced */
} PyKDTree;
-
/* -------------------------------------------------------------------- */
/* Utility helper functions */
static void kdtree_nearest_to_py_tuple(const KDTreeNearest_3d *nearest, PyObject *py_retval)
{
- BLI_assert(nearest->index >= 0);
- BLI_assert(PyTuple_GET_SIZE(py_retval) == 3);
+ BLI_assert(nearest->index >= 0);
+ BLI_assert(PyTuple_GET_SIZE(py_retval) == 3);
- PyTuple_SET_ITEMS(py_retval,
- Vector_CreatePyObject((float *)nearest->co, 3, NULL),
- PyLong_FromLong(nearest->index),
- PyFloat_FromDouble(nearest->dist));
+ PyTuple_SET_ITEMS(py_retval,
+ Vector_CreatePyObject((float *)nearest->co, 3, NULL),
+ PyLong_FromLong(nearest->index),
+ PyFloat_FromDouble(nearest->dist));
}
static PyObject *kdtree_nearest_to_py(const KDTreeNearest_3d *nearest)
{
- PyObject *py_retval;
+ PyObject *py_retval;
- py_retval = PyTuple_New(3);
+ py_retval = PyTuple_New(3);
- kdtree_nearest_to_py_tuple(nearest, py_retval);
+ kdtree_nearest_to_py_tuple(nearest, py_retval);
- return py_retval;
+ return py_retval;
}
static PyObject *kdtree_nearest_to_py_and_check(const KDTreeNearest_3d *nearest)
{
- PyObject *py_retval;
+ PyObject *py_retval;
- py_retval = PyTuple_New(3);
+ py_retval = PyTuple_New(3);
- if (nearest->index != -1) {
- kdtree_nearest_to_py_tuple(nearest, py_retval);
- }
- else {
- PyC_Tuple_Fill(py_retval, Py_None);
- }
+ if (nearest->index != -1) {
+ kdtree_nearest_to_py_tuple(nearest, py_retval);
+ }
+ else {
+ PyC_Tuple_Fill(py_retval, Py_None);
+ }
- return py_retval;
+ return py_retval;
}
-
/* -------------------------------------------------------------------- */
/* KDTree */
@@ -95,395 +92,376 @@ static PyObject *kdtree_nearest_to_py_and_check(const KDTreeNearest_3d *nearest)
static int PyKDTree__tp_init(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
- unsigned int maxsize;
- const char *keywords[] = {"size", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, "I:KDTree", (char **)keywords,
- &maxsize))
- {
- return -1;
- }
-
- if (UINT_IS_NEG(maxsize)) {
- PyErr_SetString(PyExc_ValueError, "negative 'size' given");
- return -1;
- }
-
- self->obj = BLI_kdtree_3d_new(maxsize);
- self->maxsize = maxsize;
- self->count = 0;
- self->count_balance = 0;
-
- return 0;
+ unsigned int maxsize;
+ const char *keywords[] = {"size", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "I:KDTree", (char **)keywords, &maxsize)) {
+ return -1;
+ }
+
+ if (UINT_IS_NEG(maxsize)) {
+ PyErr_SetString(PyExc_ValueError, "negative 'size' given");
+ return -1;
+ }
+
+ self->obj = BLI_kdtree_3d_new(maxsize);
+ self->maxsize = maxsize;
+ self->count = 0;
+ self->count_balance = 0;
+
+ return 0;
}
static void PyKDTree__tp_dealloc(PyKDTree *self)
{
- BLI_kdtree_3d_free(self->obj);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ BLI_kdtree_3d_free(self->obj);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
PyDoc_STRVAR(py_kdtree_insert_doc,
-".. method:: insert(co, index)\n"
-"\n"
-" Insert a point into the KDTree.\n"
-"\n"
-" :arg co: Point 3d position.\n"
-" :type co: float triplet\n"
-" :arg index: The index of the point.\n"
-" :type index: int\n"
-);
+ ".. method:: insert(co, index)\n"
+ "\n"
+ " Insert a point into the KDTree.\n"
+ "\n"
+ " :arg co: Point 3d position.\n"
+ " :type co: float triplet\n"
+ " :arg index: The index of the point.\n"
+ " :type index: int\n");
static PyObject *py_kdtree_insert(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
- PyObject *py_co;
- float co[3];
- int index;
- const char *keywords[] = {"co", "index", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *) "Oi:insert", (char **)keywords,
- &py_co, &index))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(co, 3, 3, py_co, "insert: invalid 'co' arg") == -1) {
- return NULL;
- }
-
- if (index < 0) {
- PyErr_SetString(PyExc_ValueError, "negative index given");
- return NULL;
- }
-
- if (self->count >= self->maxsize) {
- PyErr_SetString(PyExc_RuntimeError, "Trying to insert more items than KDTree has room for");
- return NULL;
- }
-
- BLI_kdtree_3d_insert(self->obj, index, co);
- self->count++;
-
- Py_RETURN_NONE;
+ PyObject *py_co;
+ float co[3];
+ int index;
+ const char *keywords[] = {"co", "index", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kwargs, (char *)"Oi:insert", (char **)keywords, &py_co, &index)) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(co, 3, 3, py_co, "insert: invalid 'co' arg") == -1) {
+ return NULL;
+ }
+
+ if (index < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative index given");
+ return NULL;
+ }
+
+ if (self->count >= self->maxsize) {
+ PyErr_SetString(PyExc_RuntimeError, "Trying to insert more items than KDTree has room for");
+ return NULL;
+ }
+
+ BLI_kdtree_3d_insert(self->obj, index, co);
+ self->count++;
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(py_kdtree_balance_doc,
-".. method:: balance()\n"
-"\n"
-" Balance the tree.\n"
-"\n"
-".. note::\n"
-"\n"
-" This builds the entire tree, avoid calling after each insertion.\n"
-);
+ ".. method:: balance()\n"
+ "\n"
+ " Balance the tree.\n"
+ "\n"
+ ".. note::\n"
+ "\n"
+ " This builds the entire tree, avoid calling after each insertion.\n");
static PyObject *py_kdtree_balance(PyKDTree *self)
{
- BLI_kdtree_3d_balance(self->obj);
- self->count_balance = self->count;
- Py_RETURN_NONE;
+ BLI_kdtree_3d_balance(self->obj);
+ self->count_balance = self->count;
+ Py_RETURN_NONE;
}
struct PyKDTree_NearestData {
- PyObject *py_filter;
- bool is_error;
+ PyObject *py_filter;
+ bool is_error;
};
static int py_find_nearest_cb(void *user_data, int index, const float co[3], float dist_sq)
{
- UNUSED_VARS(co, dist_sq);
-
- struct PyKDTree_NearestData *data = user_data;
-
- PyObject *py_args = PyTuple_New(1);
- PyTuple_SET_ITEM(py_args, 0, PyLong_FromLong(index));
- PyObject *result = PyObject_CallObject(data->py_filter, py_args);
- Py_DECREF(py_args);
-
- if (result) {
- bool use_node;
- int ok = PyC_ParseBool(result, &use_node);
- Py_DECREF(result);
- if (ok) {
- return (int)use_node;
- }
- }
-
- data->is_error = true;
- return -1;
+ UNUSED_VARS(co, dist_sq);
+
+ struct PyKDTree_NearestData *data = user_data;
+
+ PyObject *py_args = PyTuple_New(1);
+ PyTuple_SET_ITEM(py_args, 0, PyLong_FromLong(index));
+ PyObject *result = PyObject_CallObject(data->py_filter, py_args);
+ Py_DECREF(py_args);
+
+ if (result) {
+ bool use_node;
+ int ok = PyC_ParseBool(result, &use_node);
+ Py_DECREF(result);
+ if (ok) {
+ return (int)use_node;
+ }
+ }
+
+ data->is_error = true;
+ return -1;
}
PyDoc_STRVAR(py_kdtree_find_doc,
-".. method:: find(co, filter=None)\n"
-"\n"
-" Find nearest point to ``co``.\n"
-"\n"
-" :arg co: 3d coordinates.\n"
-" :type co: float triplet\n"
-" :arg filter: function which takes an index and returns True for indices to include in the search.\n"
-" :type filter: callable\n"
-" :return: Returns (:class:`Vector`, index, distance).\n"
-" :rtype: :class:`tuple`\n"
-);
+ ".. method:: find(co, filter=None)\n"
+ "\n"
+ " Find nearest point to ``co``.\n"
+ "\n"
+ " :arg co: 3d coordinates.\n"
+ " :type co: float triplet\n"
+ " :arg filter: function which takes an index and returns True for indices to "
+ "include in the search.\n"
+ " :type filter: callable\n"
+ " :return: Returns (:class:`Vector`, index, distance).\n"
+ " :rtype: :class:`tuple`\n");
static PyObject *py_kdtree_find(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
- PyObject *py_co, *py_filter = NULL;
- float co[3];
- KDTreeNearest_3d nearest;
- const char *keywords[] = {"co", "filter", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *) "O|O:find", (char **)keywords,
- &py_co, &py_filter))
- {
- return NULL;
- }
-
- if (mathutils_array_parse(co, 3, 3, py_co, "find: invalid 'co' arg") == -1) {
- return NULL;
- }
-
- if (self->count != self->count_balance) {
- PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find()");
- return NULL;
- }
-
- nearest.index = -1;
-
- if (py_filter == NULL) {
- BLI_kdtree_3d_find_nearest(self->obj, co, &nearest);
- }
- else {
- struct PyKDTree_NearestData data = {0};
-
- data.py_filter = py_filter;
- data.is_error = false;
-
- BLI_kdtree_3d_find_nearest_cb(
- self->obj, co,
- py_find_nearest_cb, &data,
- &nearest);
-
- if (data.is_error) {
- return NULL;
- }
- }
-
- return kdtree_nearest_to_py_and_check(&nearest);
+ PyObject *py_co, *py_filter = NULL;
+ float co[3];
+ KDTreeNearest_3d nearest;
+ const char *keywords[] = {"co", "filter", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kwargs, (char *)"O|O:find", (char **)keywords, &py_co, &py_filter)) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(co, 3, 3, py_co, "find: invalid 'co' arg") == -1) {
+ return NULL;
+ }
+
+ if (self->count != self->count_balance) {
+ PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find()");
+ return NULL;
+ }
+
+ nearest.index = -1;
+
+ if (py_filter == NULL) {
+ BLI_kdtree_3d_find_nearest(self->obj, co, &nearest);
+ }
+ else {
+ struct PyKDTree_NearestData data = {0};
+
+ data.py_filter = py_filter;
+ data.is_error = false;
+
+ BLI_kdtree_3d_find_nearest_cb(self->obj, co, py_find_nearest_cb, &data, &nearest);
+
+ if (data.is_error) {
+ return NULL;
+ }
+ }
+
+ return kdtree_nearest_to_py_and_check(&nearest);
}
PyDoc_STRVAR(py_kdtree_find_n_doc,
-".. method:: find_n(co, n)\n"
-"\n"
-" Find nearest ``n`` points to ``co``.\n"
-"\n"
-" :arg co: 3d coordinates.\n"
-" :type co: float triplet\n"
-" :arg n: Number of points to find.\n"
-" :type n: int\n"
-" :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
-" :rtype: :class:`list`\n"
-);
+ ".. method:: find_n(co, n)\n"
+ "\n"
+ " Find nearest ``n`` points to ``co``.\n"
+ "\n"
+ " :arg co: 3d coordinates.\n"
+ " :type co: float triplet\n"
+ " :arg n: Number of points to find.\n"
+ " :type n: int\n"
+ " :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
+ " :rtype: :class:`list`\n");
static PyObject *py_kdtree_find_n(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
- PyObject *py_list;
- PyObject *py_co;
- float co[3];
- KDTreeNearest_3d *nearest;
- unsigned int n;
- int i, found;
- const char *keywords[] = {"co", "n", NULL};
+ PyObject *py_list;
+ PyObject *py_co;
+ float co[3];
+ KDTreeNearest_3d *nearest;
+ unsigned int n;
+ int i, found;
+ const char *keywords[] = {"co", "n", NULL};
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *) "OI:find_n", (char **)keywords,
- &py_co, &n))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kwargs, (char *)"OI:find_n", (char **)keywords, &py_co, &n)) {
+ return NULL;
+ }
- if (mathutils_array_parse(co, 3, 3, py_co, "find_n: invalid 'co' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(co, 3, 3, py_co, "find_n: invalid 'co' arg") == -1) {
+ return NULL;
+ }
- if (UINT_IS_NEG(n)) {
- PyErr_SetString(PyExc_RuntimeError, "negative 'n' given");
- return NULL;
- }
+ if (UINT_IS_NEG(n)) {
+ PyErr_SetString(PyExc_RuntimeError, "negative 'n' given");
+ return NULL;
+ }
- if (self->count != self->count_balance) {
- PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_n()");
- return NULL;
- }
+ if (self->count != self->count_balance) {
+ PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_n()");
+ return NULL;
+ }
- nearest = MEM_mallocN(sizeof(KDTreeNearest_3d) * n, __func__);
+ nearest = MEM_mallocN(sizeof(KDTreeNearest_3d) * n, __func__);
- found = BLI_kdtree_3d_find_nearest_n(self->obj, co, nearest, n);
+ found = BLI_kdtree_3d_find_nearest_n(self->obj, co, nearest, n);
- py_list = PyList_New(found);
+ py_list = PyList_New(found);
- for (i = 0; i < found; i++) {
- PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
- }
+ for (i = 0; i < found; i++) {
+ PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
+ }
- MEM_freeN(nearest);
+ MEM_freeN(nearest);
- return py_list;
+ return py_list;
}
PyDoc_STRVAR(py_kdtree_find_range_doc,
-".. method:: find_range(co, radius)\n"
-"\n"
-" Find all points within ``radius`` of ``co``.\n"
-"\n"
-" :arg co: 3d coordinates.\n"
-" :type co: float triplet\n"
-" :arg radius: Distance to search for points.\n"
-" :type radius: float\n"
-" :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
-" :rtype: :class:`list`\n"
-);
+ ".. method:: find_range(co, radius)\n"
+ "\n"
+ " Find all points within ``radius`` of ``co``.\n"
+ "\n"
+ " :arg co: 3d coordinates.\n"
+ " :type co: float triplet\n"
+ " :arg radius: Distance to search for points.\n"
+ " :type radius: float\n"
+ " :return: Returns a list of tuples (:class:`Vector`, index, distance).\n"
+ " :rtype: :class:`list`\n");
static PyObject *py_kdtree_find_range(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
- PyObject *py_list;
- PyObject *py_co;
- float co[3];
- KDTreeNearest_3d *nearest = NULL;
- float radius;
- int i, found;
+ PyObject *py_list;
+ PyObject *py_co;
+ float co[3];
+ KDTreeNearest_3d *nearest = NULL;
+ float radius;
+ int i, found;
- const char *keywords[] = {"co", "radius", NULL};
+ const char *keywords[] = {"co", "radius", NULL};
- if (!PyArg_ParseTupleAndKeywords(
- args, kwargs, (char *) "Of:find_range", (char **)keywords,
- &py_co, &radius))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kwargs, (char *)"Of:find_range", (char **)keywords, &py_co, &radius)) {
+ return NULL;
+ }
- if (mathutils_array_parse(co, 3, 3, py_co, "find_range: invalid 'co' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(co, 3, 3, py_co, "find_range: invalid 'co' arg") == -1) {
+ return NULL;
+ }
- if (radius < 0.0f) {
- PyErr_SetString(PyExc_RuntimeError, "negative radius given");
- return NULL;
- }
+ if (radius < 0.0f) {
+ PyErr_SetString(PyExc_RuntimeError, "negative radius given");
+ return NULL;
+ }
- if (self->count != self->count_balance) {
- PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_range()");
- return NULL;
- }
+ if (self->count != self->count_balance) {
+ PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_range()");
+ return NULL;
+ }
- found = BLI_kdtree_3d_range_search(self->obj, co, &nearest, radius);
+ found = BLI_kdtree_3d_range_search(self->obj, co, &nearest, radius);
- py_list = PyList_New(found);
+ py_list = PyList_New(found);
- for (i = 0; i < found; i++) {
- PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
- }
+ for (i = 0; i < found; i++) {
+ PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
+ }
- if (nearest) {
- MEM_freeN(nearest);
- }
+ if (nearest) {
+ MEM_freeN(nearest);
+ }
- return py_list;
+ return py_list;
}
-
static PyMethodDef PyKDTree_methods[] = {
- {"insert", (PyCFunction)py_kdtree_insert, METH_VARARGS | METH_KEYWORDS, py_kdtree_insert_doc},
- {"balance", (PyCFunction)py_kdtree_balance, METH_NOARGS, py_kdtree_balance_doc},
- {"find", (PyCFunction)py_kdtree_find, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_doc},
- {"find_n", (PyCFunction)py_kdtree_find_n, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_n_doc},
- {"find_range", (PyCFunction)py_kdtree_find_range, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_range_doc},
- {NULL, NULL, 0, NULL},
+ {"insert", (PyCFunction)py_kdtree_insert, METH_VARARGS | METH_KEYWORDS, py_kdtree_insert_doc},
+ {"balance", (PyCFunction)py_kdtree_balance, METH_NOARGS, py_kdtree_balance_doc},
+ {"find", (PyCFunction)py_kdtree_find, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_doc},
+ {"find_n", (PyCFunction)py_kdtree_find_n, METH_VARARGS | METH_KEYWORDS, py_kdtree_find_n_doc},
+ {"find_range",
+ (PyCFunction)py_kdtree_find_range,
+ METH_VARARGS | METH_KEYWORDS,
+ py_kdtree_find_range_doc},
+ {NULL, NULL, 0, NULL},
};
PyDoc_STRVAR(py_KDtree_doc,
-"KdTree(size) -> new kd-tree initialized to hold ``size`` items.\n"
-"\n"
-".. note::\n"
-"\n"
-" :class:`KDTree.balance` must have been called before using any of the ``find`` methods.\n"
-);
+ "KdTree(size) -> new kd-tree initialized to hold ``size`` items.\n"
+ "\n"
+ ".. note::\n"
+ "\n"
+ " :class:`KDTree.balance` must have been called before using any of the ``find`` "
+ "methods.\n");
PyTypeObject PyKDTree_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "KDTree", /* tp_name */
- sizeof(PyKDTree), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)PyKDTree__tp_dealloc, /* tp_dealloc */
- NULL, /* tp_print */
- NULL, /* tp_getattr */
- NULL, /* tp_setattr */
- NULL, /* tp_compare */
- NULL, /* tp_repr */
- NULL, /* tp_as_number */
- NULL, /* tp_as_sequence */
- NULL, /* tp_as_mapping */
- NULL, /* tp_hash */
- NULL, /* tp_call */
- NULL, /* tp_str */
- NULL, /* tp_getattro */
- NULL, /* tp_setattro */
- NULL, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- py_KDtree_doc, /* Documentation string */
- NULL, /* tp_traverse */
- NULL, /* tp_clear */
- NULL, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- NULL, /* tp_iter */
- NULL, /* tp_iternext */
- (struct PyMethodDef *)PyKDTree_methods, /* tp_methods */
- NULL, /* tp_members */
- NULL, /* tp_getset */
- NULL, /* tp_base */
- NULL, /* tp_dict */
- NULL, /* tp_descr_get */
- NULL, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)PyKDTree__tp_init, /* tp_init */
- (allocfunc)PyType_GenericAlloc, /* tp_alloc */
- (newfunc)PyType_GenericNew, /* tp_new */
- (freefunc)0, /* tp_free */
- NULL, /* tp_is_gc */
- NULL, /* tp_bases */
- NULL, /* tp_mro */
- NULL, /* tp_cache */
- NULL, /* tp_subclasses */
- NULL, /* tp_weaklist */
- (destructor)NULL, /* tp_del */
+ PyVarObject_HEAD_INIT(NULL, 0) "KDTree", /* tp_name */
+ sizeof(PyKDTree), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)PyKDTree__tp_dealloc, /* tp_dealloc */
+ NULL, /* tp_print */
+ NULL, /* tp_getattr */
+ NULL, /* tp_setattr */
+ NULL, /* tp_compare */
+ NULL, /* tp_repr */
+ NULL, /* tp_as_number */
+ NULL, /* tp_as_sequence */
+ NULL, /* tp_as_mapping */
+ NULL, /* tp_hash */
+ NULL, /* tp_call */
+ NULL, /* tp_str */
+ NULL, /* tp_getattro */
+ NULL, /* tp_setattro */
+ NULL, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ py_KDtree_doc, /* Documentation string */
+ NULL, /* tp_traverse */
+ NULL, /* tp_clear */
+ NULL, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ NULL, /* tp_iter */
+ NULL, /* tp_iternext */
+ (struct PyMethodDef *)PyKDTree_methods, /* tp_methods */
+ NULL, /* tp_members */
+ NULL, /* tp_getset */
+ NULL, /* tp_base */
+ NULL, /* tp_dict */
+ NULL, /* tp_descr_get */
+ NULL, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)PyKDTree__tp_init, /* tp_init */
+ (allocfunc)PyType_GenericAlloc, /* tp_alloc */
+ (newfunc)PyType_GenericNew, /* tp_new */
+ (freefunc)0, /* tp_free */
+ NULL, /* tp_is_gc */
+ NULL, /* tp_bases */
+ NULL, /* tp_mro */
+ NULL, /* tp_cache */
+ NULL, /* tp_subclasses */
+ NULL, /* tp_weaklist */
+ (destructor)NULL, /* tp_del */
};
-PyDoc_STRVAR(py_kdtree_doc,
-"Generic 3-dimentional kd-tree to perform spatial searches."
-);
+PyDoc_STRVAR(py_kdtree_doc, "Generic 3-dimentional kd-tree to perform spatial searches.");
static struct PyModuleDef kdtree_moduledef = {
- PyModuleDef_HEAD_INIT,
- "mathutils.kdtree", /* m_name */
- py_kdtree_doc, /* m_doc */
- 0, /* m_size */
- NULL, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils.kdtree", /* m_name */
+ py_kdtree_doc, /* m_doc */
+ 0, /* m_size */
+ NULL, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
PyMODINIT_FUNC PyInit_mathutils_kdtree(void)
{
- PyObject *m = PyModule_Create(&kdtree_moduledef);
+ PyObject *m = PyModule_Create(&kdtree_moduledef);
- if (m == NULL) {
- return NULL;
- }
+ if (m == NULL) {
+ return NULL;
+ }
- /* Register the 'KDTree' class */
- if (PyType_Ready(&PyKDTree_Type)) {
- return NULL;
- }
- PyModule_AddObject(m, "KDTree", (PyObject *) &PyKDTree_Type);
+ /* Register the 'KDTree' class */
+ if (PyType_Ready(&PyKDTree_Type)) {
+ return NULL;
+ }
+ PyModule_AddObject(m, "KDTree", (PyObject *)&PyKDTree_Type);
- return m;
+ return m;
}
diff --git a/source/blender/python/mathutils/mathutils_kdtree.h b/source/blender/python/mathutils/mathutils_kdtree.h
index 4a4e1740ad8..99411997282 100644
--- a/source/blender/python/mathutils/mathutils_kdtree.h
+++ b/source/blender/python/mathutils/mathutils_kdtree.h
@@ -14,7 +14,6 @@
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-
/** \file
* \ingroup mathutils
*/
diff --git a/source/blender/python/mathutils/mathutils_noise.c b/source/blender/python/mathutils/mathutils_noise.c
index 04cadb9b592..b890295d32f 100644
--- a/source/blender/python/mathutils/mathutils_noise.c
+++ b/source/blender/python/mathutils/mathutils_noise.c
@@ -21,7 +21,6 @@
* blenders noise functions.
*/
-
/************************/
/* Blender Noise Module */
/************************/
@@ -88,13 +87,13 @@
/* Period parameters */
#define N 624
#define M 397
-#define MATRIX_A 0x9908b0dfUL /* constant vector a */
-#define UMASK 0x80000000UL /* most significant w-r bits */
-#define LMASK 0x7fffffffUL /* least significant r bits */
-#define MIXBITS(u, v) (((u) & UMASK) | ((v) & LMASK))
-#define TWIST(u, v) ((MIXBITS(u, v) >> 1) ^ ((v) & 1UL ? MATRIX_A : 0UL))
+#define MATRIX_A 0x9908b0dfUL /* constant vector a */
+#define UMASK 0x80000000UL /* most significant w-r bits */
+#define LMASK 0x7fffffffUL /* least significant r bits */
+#define MIXBITS(u, v) (((u)&UMASK) | ((v)&LMASK))
+#define TWIST(u, v) ((MIXBITS(u, v) >> 1) ^ ((v)&1UL ? MATRIX_A : 0UL))
-static unsigned long state[N]; /* the array for the state vector */
+static unsigned long state[N]; /* the array for the state vector */
static int left = 1;
static int initf = 0;
static unsigned long *next;
@@ -103,86 +102,84 @@ static float state_offset_vector[3 * 3];
/* initializes state[N] with a seed */
static void init_genrand(unsigned long s)
{
- int j;
- state[0] = s & 0xffffffffUL;
- for (j = 1; j < N; j++) {
- state[j] =
- (1812433253UL *
- (state[j - 1] ^ (state[j - 1] >> 30)) + j);
- /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
- /* In the previous versions, MSBs of the seed affect */
- /* only MSBs of the array state[]. */
- /* 2002/01/09 modified by Makoto Matsumoto */
- state[j] &= 0xffffffffUL; /* for >32 bit machines */
- }
- left = 1;
- initf = 1;
-
- /* update vector offset */
- {
- const unsigned long *state_offset = &state[N - ARRAY_SIZE(state_offset_vector)];
- const float range = 32; /* range in both pos/neg direction */
- for (j = 0; j < ARRAY_SIZE(state_offset_vector); j++, state_offset++) {
- /* overflow is fine here */
- state_offset_vector[j] = (float)(int)(*state_offset) * (1.0f / (INT_MAX / range));
- }
- }
+ int j;
+ state[0] = s & 0xffffffffUL;
+ for (j = 1; j < N; j++) {
+ state[j] = (1812433253UL * (state[j - 1] ^ (state[j - 1] >> 30)) + j);
+ /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
+ /* In the previous versions, MSBs of the seed affect */
+ /* only MSBs of the array state[]. */
+ /* 2002/01/09 modified by Makoto Matsumoto */
+ state[j] &= 0xffffffffUL; /* for >32 bit machines */
+ }
+ left = 1;
+ initf = 1;
+
+ /* update vector offset */
+ {
+ const unsigned long *state_offset = &state[N - ARRAY_SIZE(state_offset_vector)];
+ const float range = 32; /* range in both pos/neg direction */
+ for (j = 0; j < ARRAY_SIZE(state_offset_vector); j++, state_offset++) {
+ /* overflow is fine here */
+ state_offset_vector[j] = (float)(int)(*state_offset) * (1.0f / (INT_MAX / range));
+ }
+ }
}
static void next_state(void)
{
- unsigned long *p = state;
- int j;
+ unsigned long *p = state;
+ int j;
- /* if init_genrand() has not been called, */
- /* a default initial seed is used */
- if (initf == 0) {
- init_genrand(5489UL);
- }
+ /* if init_genrand() has not been called, */
+ /* a default initial seed is used */
+ if (initf == 0) {
+ init_genrand(5489UL);
+ }
- left = N;
- next = state;
+ left = N;
+ next = state;
- for (j = N - M + 1; --j; p++) {
- *p = p[M] ^ TWIST(p[0], p[1]);
- }
+ for (j = N - M + 1; --j; p++) {
+ *p = p[M] ^ TWIST(p[0], p[1]);
+ }
- for (j = M; --j; p++) {
- *p = p[M - N] ^ TWIST(p[0], p[1]);
- }
+ for (j = M; --j; p++) {
+ *p = p[M - N] ^ TWIST(p[0], p[1]);
+ }
- *p = p[M - N] ^ TWIST(p[0], state[0]);
+ *p = p[M - N] ^ TWIST(p[0], state[0]);
}
/*------------------------------------------------------------*/
static void setRndSeed(int seed)
{
- if (seed == 0) {
- init_genrand(time(NULL));
- }
- else {
- init_genrand(seed);
- }
+ if (seed == 0) {
+ init_genrand(time(NULL));
+ }
+ else {
+ init_genrand(seed);
+ }
}
/* float number in range [0, 1) using the mersenne twister rng */
static float frand(void)
{
- unsigned long y;
+ unsigned long y;
- if (--left == 0) {
- next_state();
- }
- y = *next++;
+ if (--left == 0) {
+ next_state();
+ }
+ y = *next++;
- /* Tempering */
- y ^= (y >> 11);
- y ^= (y << 7) & 0x9d2c5680UL;
- y ^= (y << 15) & 0xefc60000UL;
- y ^= (y >> 18);
+ /* Tempering */
+ y ^= (y >> 11);
+ y ^= (y << 7) & 0x9d2c5680UL;
+ y ^= (y << 15) & 0xefc60000UL;
+ y ^= (y >> 18);
- return (float) y / 4294967296.f;
+ return (float)y / 4294967296.f;
}
/*------------------------------------------------------------*/
@@ -190,898 +187,960 @@ static float frand(void)
/*------------------------------------------------------------*/
#define BPY_NOISE_BASIS_ENUM_DOC \
-" :arg noise_basis: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', 'VORONOI_F1', 'VORONOI_F2', " \
- "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', " \
- "'CELLNOISE'].\n" \
-" :type noise_basis: string\n" \
+ " :arg noise_basis: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', " \
+ "'VORONOI_F1', 'VORONOI_F2', " \
+ "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', " \
+ "'CELLNOISE'].\n" \
+ " :type noise_basis: string\n"
#define BPY_NOISE_METRIC_ENUM_DOC \
-" :arg distance_metric: Enumerator in ['DISTANCE', 'DISTANCE_SQUARED', 'MANHATTAN', 'CHEBYCHEV', " \
- "'MINKOVSKY', 'MINKOVSKY_HALF', 'MINKOVSKY_FOUR'].\n" \
-" :type distance_metric: string\n" \
+ " :arg distance_metric: Enumerator in ['DISTANCE', 'DISTANCE_SQUARED', 'MANHATTAN', " \
+ "'CHEBYCHEV', " \
+ "'MINKOVSKY', 'MINKOVSKY_HALF', 'MINKOVSKY_FOUR'].\n" \
+ " :type distance_metric: string\n"
/* Noise basis enum */
#define DEFAULT_NOISE_TYPE TEX_STDPERLIN
static PyC_FlagSet bpy_noise_types[] = {
- {TEX_BLENDER, "BLENDER"},
- {TEX_STDPERLIN, "PERLIN_ORIGINAL"},
- {TEX_NEWPERLIN, "PERLIN_NEW"},
- {TEX_VORONOI_F1, "VORONOI_F1"},
- {TEX_VORONOI_F2, "VORONOI_F2"},
- {TEX_VORONOI_F3, "VORONOI_F3"},
- {TEX_VORONOI_F4, "VORONOI_F4"},
- {TEX_VORONOI_F2F1, "VORONOI_F2F1"},
- {TEX_VORONOI_CRACKLE, "VORONOI_CRACKLE"},
- {TEX_CELLNOISE, "CELLNOISE"},
- {0, NULL},
+ {TEX_BLENDER, "BLENDER"},
+ {TEX_STDPERLIN, "PERLIN_ORIGINAL"},
+ {TEX_NEWPERLIN, "PERLIN_NEW"},
+ {TEX_VORONOI_F1, "VORONOI_F1"},
+ {TEX_VORONOI_F2, "VORONOI_F2"},
+ {TEX_VORONOI_F3, "VORONOI_F3"},
+ {TEX_VORONOI_F4, "VORONOI_F4"},
+ {TEX_VORONOI_F2F1, "VORONOI_F2F1"},
+ {TEX_VORONOI_CRACKLE, "VORONOI_CRACKLE"},
+ {TEX_CELLNOISE, "CELLNOISE"},
+ {0, NULL},
};
/* Metric basis enum */
#define DEFAULT_METRIC_TYPE TEX_DISTANCE
static PyC_FlagSet bpy_noise_metrics[] = {
- {TEX_DISTANCE, "DISTANCE"},
- {TEX_DISTANCE_SQUARED, "DISTANCE_SQUARED"},
- {TEX_MANHATTAN, "MANHATTAN"},
- {TEX_CHEBYCHEV, "CHEBYCHEV"},
- {TEX_MINKOVSKY, "MINKOVSKY"},
- {TEX_MINKOVSKY_HALF, "MINKOVSKY_HALF"},
- {TEX_MINKOVSKY_FOUR, "MINKOVSKY_FOUR"},
- {0, NULL},
+ {TEX_DISTANCE, "DISTANCE"},
+ {TEX_DISTANCE_SQUARED, "DISTANCE_SQUARED"},
+ {TEX_MANHATTAN, "MANHATTAN"},
+ {TEX_CHEBYCHEV, "CHEBYCHEV"},
+ {TEX_MINKOVSKY, "MINKOVSKY"},
+ {TEX_MINKOVSKY_HALF, "MINKOVSKY_HALF"},
+ {TEX_MINKOVSKY_FOUR, "MINKOVSKY_FOUR"},
+ {0, NULL},
};
/* Fills an array of length size with random numbers in the range (-1, 1)*/
static void rand_vn(float *array_tar, const int size)
{
- float *array_pt = array_tar + (size - 1);
- int i = size;
- while (i--) { *(array_pt--) = 2.0f * frand() - 1.0f; }
+ float *array_pt = array_tar + (size - 1);
+ int i = size;
+ while (i--) {
+ *(array_pt--) = 2.0f * frand() - 1.0f;
+ }
}
/* Fills an array of length 3 with noise values */
static void noise_vector(float x, float y, float z, int nb, float v[3])
{
- /* Simply evaluate noise at 3 different positions */
- const float *ofs = state_offset_vector;
- for (int j = 0; j < 3; j++) {
- v[j] = (2.0f * BLI_gNoise(1.0f, x + ofs[0], y + ofs[1], z + ofs[2], 0, nb) - 1.0f);
- ofs += 3;
- }
+ /* Simply evaluate noise at 3 different positions */
+ const float *ofs = state_offset_vector;
+ for (int j = 0; j < 3; j++) {
+ v[j] = (2.0f * BLI_gNoise(1.0f, x + ofs[0], y + ofs[1], z + ofs[2], 0, nb) - 1.0f);
+ ofs += 3;
+ }
}
/* Returns a turbulence value for a given position (x, y, z) */
static float turb(
- float x, float y, float z, int oct, int hard, int nb,
- float ampscale, float freqscale)
+ float x, float y, float z, int oct, int hard, int nb, float ampscale, float freqscale)
{
- float amp, out, t;
- int i;
- amp = 1.f;
- out = (float)(2.0f * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0f);
- if (hard) {
- out = fabsf(out);
- }
- for (i = 1; i < oct; i++) {
- amp *= ampscale;
- x *= freqscale;
- y *= freqscale;
- z *= freqscale;
- t = (float)(amp * (2.0f * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0f));
- if (hard) {
- t = fabsf(t);
- }
- out += t;
- }
- return out;
+ float amp, out, t;
+ int i;
+ amp = 1.f;
+ out = (float)(2.0f * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0f);
+ if (hard) {
+ out = fabsf(out);
+ }
+ for (i = 1; i < oct; i++) {
+ amp *= ampscale;
+ x *= freqscale;
+ y *= freqscale;
+ z *= freqscale;
+ t = (float)(amp * (2.0f * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0f));
+ if (hard) {
+ t = fabsf(t);
+ }
+ out += t;
+ }
+ return out;
}
/* Fills an array of length 3 with the turbulence vector for a given
* position (x, y, z) */
-static void vTurb(
- float x, float y, float z, int oct, int hard, int nb,
- float ampscale, float freqscale, float v[3])
+static void vTurb(float x,
+ float y,
+ float z,
+ int oct,
+ int hard,
+ int nb,
+ float ampscale,
+ float freqscale,
+ float v[3])
{
- float amp, t[3];
- int i;
- amp = 1.f;
- noise_vector(x, y, z, nb, v);
- if (hard) {
- v[0] = fabsf(v[0]);
- v[1] = fabsf(v[1]);
- v[2] = fabsf(v[2]);
- }
- for (i = 1; i < oct; i++) {
- amp *= ampscale;
- x *= freqscale;
- y *= freqscale;
- z *= freqscale;
- noise_vector(x, y, z, nb, t);
- if (hard) {
- t[0] = fabsf(t[0]);
- t[1] = fabsf(t[1]);
- t[2] = fabsf(t[2]);
- }
- v[0] += amp * t[0];
- v[1] += amp * t[1];
- v[2] += amp * t[2];
- }
+ float amp, t[3];
+ int i;
+ amp = 1.f;
+ noise_vector(x, y, z, nb, v);
+ if (hard) {
+ v[0] = fabsf(v[0]);
+ v[1] = fabsf(v[1]);
+ v[2] = fabsf(v[2]);
+ }
+ for (i = 1; i < oct; i++) {
+ amp *= ampscale;
+ x *= freqscale;
+ y *= freqscale;
+ z *= freqscale;
+ noise_vector(x, y, z, nb, t);
+ if (hard) {
+ t[0] = fabsf(t[0]);
+ t[1] = fabsf(t[1]);
+ t[2] = fabsf(t[2]);
+ }
+ v[0] += amp * t[0];
+ v[1] += amp * t[1];
+ v[2] += amp * t[2];
+ }
}
/*-------------------------DOC STRINGS ---------------------------*/
-PyDoc_STRVAR(M_Noise_doc,
-"The Blender noise module"
-);
+PyDoc_STRVAR(M_Noise_doc, "The Blender noise module");
/*------------------------------------------------------------*/
/* Python Functions */
/*------------------------------------------------------------*/
PyDoc_STRVAR(M_Noise_random_doc,
-".. function:: random()\n"
-"\n"
-" Returns a random number in the range [0, 1).\n"
-"\n"
-" :return: The random number.\n"
-" :rtype: float\n"
-);
+ ".. function:: random()\n"
+ "\n"
+ " Returns a random number in the range [0, 1).\n"
+ "\n"
+ " :return: The random number.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_random(PyObject *UNUSED(self))
{
- return PyFloat_FromDouble(frand());
+ return PyFloat_FromDouble(frand());
}
PyDoc_STRVAR(M_Noise_random_unit_vector_doc,
-".. function:: random_unit_vector(size=3)\n"
-"\n"
-" Returns a unit vector with random entries.\n"
-"\n"
-" :arg size: The size of the vector to be produced, in the range [2, 4].\n"
-" :type size: int\n"
-" :return: The random unit vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: random_unit_vector(size=3)\n"
+ "\n"
+ " Returns a unit vector with random entries.\n"
+ "\n"
+ " :arg size: The size of the vector to be produced, in the range [2, 4].\n"
+ " :type size: int\n"
+ " :return: The random unit vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Noise_random_unit_vector(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"size", NULL};
- float vec[4] = {0.0f, 0.0f, 0.0f, 0.0f};
- float norm = 2.0f;
- int size = 3;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "|$i:random_unit_vector", (char **)kwlist,
- &size))
- {
- return NULL;
- }
-
- if (size > 4 || size < 2) {
- PyErr_SetString(PyExc_ValueError, "Vector(): invalid size");
- return NULL;
- }
-
- while (norm == 0.0f || norm > 1.0f) {
- rand_vn(vec, size);
- norm = normalize_vn(vec, size);
- }
-
- return Vector_CreatePyObject(vec, size, NULL);
+ static const char *kwlist[] = {"size", NULL};
+ float vec[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ float norm = 2.0f;
+ int size = 3;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|$i:random_unit_vector", (char **)kwlist, &size)) {
+ return NULL;
+ }
+
+ if (size > 4 || size < 2) {
+ PyErr_SetString(PyExc_ValueError, "Vector(): invalid size");
+ return NULL;
+ }
+
+ while (norm == 0.0f || norm > 1.0f) {
+ rand_vn(vec, size);
+ norm = normalize_vn(vec, size);
+ }
+
+ return Vector_CreatePyObject(vec, size, NULL);
}
PyDoc_STRVAR(M_Noise_random_vector_doc,
-".. function:: random_vector(size=3)\n"
-"\n"
-" Returns a vector with random entries in the range (-1, 1).\n"
-"\n"
-" :arg size: The size of the vector to be produced.\n"
-" :type size: int\n"
-" :return: The random vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: random_vector(size=3)\n"
+ "\n"
+ " Returns a vector with random entries in the range (-1, 1).\n"
+ "\n"
+ " :arg size: The size of the vector to be produced.\n"
+ " :type size: int\n"
+ " :return: The random vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Noise_random_vector(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"size", NULL};
- float *vec = NULL;
- int size = 3;
+ static const char *kwlist[] = {"size", NULL};
+ float *vec = NULL;
+ int size = 3;
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "|$i:random_vector", (char **)kwlist,
- &size))
- {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|$i:random_vector", (char **)kwlist, &size)) {
+ return NULL;
+ }
- if (size < 2) {
- PyErr_SetString(PyExc_ValueError, "Vector(): invalid size");
- return NULL;
- }
+ if (size < 2) {
+ PyErr_SetString(PyExc_ValueError, "Vector(): invalid size");
+ return NULL;
+ }
- vec = PyMem_New(float, size);
+ vec = PyMem_New(float, size);
- rand_vn(vec, size);
+ rand_vn(vec, size);
- return Vector_CreatePyObject_alloc(vec, size, NULL);
+ return Vector_CreatePyObject_alloc(vec, size, NULL);
}
PyDoc_STRVAR(M_Noise_seed_set_doc,
-".. function:: seed_set(seed)\n"
-"\n"
-" Sets the random seed used for random_unit_vector, and random.\n"
-"\n"
-" :arg seed: Seed used for the random generator.\n"
-" When seed is zero, the current time will be used instead.\n"
-" :type seed: int\n"
-);
+ ".. function:: seed_set(seed)\n"
+ "\n"
+ " Sets the random seed used for random_unit_vector, and random.\n"
+ "\n"
+ " :arg seed: Seed used for the random generator.\n"
+ " When seed is zero, the current time will be used instead.\n"
+ " :type seed: int\n");
static PyObject *M_Noise_seed_set(PyObject *UNUSED(self), PyObject *args)
{
- int s;
- if (!PyArg_ParseTuple(args, "i:seed_set", &s)) {
- return NULL;
- }
- setRndSeed(s);
- Py_RETURN_NONE;
+ int s;
+ if (!PyArg_ParseTuple(args, "i:seed_set", &s)) {
+ return NULL;
+ }
+ setRndSeed(s);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(M_Noise_noise_doc,
-".. function:: noise(position, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns noise value from the noise basis at the position specified.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The noise value.\n"
-" :rtype: float\n"
-);
+ ".. function:: noise(position, noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns noise value from the noise basis at the position specified.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The noise value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_noise(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "O|$s:noise", (char **)kwlist,
- &value, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "noise") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "noise: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble((2.0f * BLI_gNoise(1.0f, vec[0], vec[1], vec[2], 0, noise_basis_enum) - 1.0f));
+ static const char *kwlist[] = {"", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "O|$s:noise", (char **)kwlist, &value, &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(bpy_noise_types, noise_basis_str, &noise_basis_enum, "noise") ==
+ -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "noise: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ (2.0f * BLI_gNoise(1.0f, vec[0], vec[1], vec[2], 0, noise_basis_enum) - 1.0f));
}
PyDoc_STRVAR(M_Noise_noise_vector_doc,
-".. function:: noise_vector(position, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns the noise vector from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The noise vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: noise_vector(position, noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns the noise vector from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The noise vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Noise_noise_vector(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "noise_basis", NULL};
- PyObject *value;
- float vec[3], r_vec[3];
- const char *noise_basis_str = NULL;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "O|$s:noise_vector", (char **)kwlist,
- &value, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "noise_vector") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "noise_vector: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- noise_vector(vec[0], vec[1], vec[2], noise_basis_enum, r_vec);
-
- return Vector_CreatePyObject(r_vec, 3, NULL);
+ static const char *kwlist[] = {"", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3], r_vec[3];
+ const char *noise_basis_str = NULL;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "O|$s:noise_vector", (char **)kwlist, &value, &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "noise_vector") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "noise_vector: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ noise_vector(vec[0], vec[1], vec[2], noise_basis_enum, r_vec);
+
+ return Vector_CreatePyObject(r_vec, 3, NULL);
}
PyDoc_STRVAR(M_Noise_turbulence_doc,
-".. function:: turbulence(position, octaves, hard, noise_basis='PERLIN_ORIGINAL', amplitude_scale=0.5, frequency_scale=2.0)\n"
-"\n"
-" Returns the turbulence value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-" :arg hard: Specifies whether returned turbulence is hard (sharp transitions) or soft (smooth transitions).\n"
-" :type hard: boolean\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :arg amplitude_scale: The amplitude scaling factor.\n"
-" :type amplitude_scale: float\n"
-" :arg frequency_scale: The frequency scaling factor\n"
-" :type frequency_scale: float\n"
-" :return: The turbulence value.\n"
-" :rtype: float\n"
-);
+ ".. function:: turbulence(position, octaves, hard, noise_basis='PERLIN_ORIGINAL', "
+ "amplitude_scale=0.5, frequency_scale=2.0)\n"
+ "\n"
+ " Returns the turbulence value from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n"
+ " :arg hard: Specifies whether returned turbulence is hard (sharp transitions) or "
+ "soft (smooth transitions).\n"
+ " :type hard: boolean\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :arg amplitude_scale: The amplitude scaling factor.\n"
+ " :type amplitude_scale: float\n"
+ " :arg frequency_scale: The frequency scaling factor\n"
+ " :type frequency_scale: float\n"
+ " :return: The turbulence value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_turbulence(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "noise_basis", "amplitude_scale", "frequency_scale", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- int oct, hd, noise_basis_enum = DEFAULT_NOISE_TYPE;
- float as = 0.5f, fs = 2.0f;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Oii|$sff:turbulence", (char **)kwlist,
- &value, &oct, &hd, &noise_basis_str, &as, &fs))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "turbulence") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "turbulence: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(turb(vec[0], vec[1], vec[2], oct, hd, noise_basis_enum, as, fs));
+ static const char *kwlist[] = {
+ "", "", "", "noise_basis", "amplitude_scale", "frequency_scale", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ int oct, hd, noise_basis_enum = DEFAULT_NOISE_TYPE;
+ float as = 0.5f, fs = 2.0f;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Oii|$sff:turbulence",
+ (char **)kwlist,
+ &value,
+ &oct,
+ &hd,
+ &noise_basis_str,
+ &as,
+ &fs)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "turbulence") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "turbulence: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(turb(vec[0], vec[1], vec[2], oct, hd, noise_basis_enum, as, fs));
}
PyDoc_STRVAR(M_Noise_turbulence_vector_doc,
-".. function:: turbulence_vector(position, octaves, hard, noise_basis='PERLIN_ORIGINAL', amplitude_scale=0.5, frequency_scale=2.0)\n"
-"\n"
-" Returns the turbulence vector from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-" :arg hard: Specifies whether returned turbulence is hard (sharp transitions) or soft (smooth transitions).\n"
-" :type hard: :boolean\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :arg amplitude_scale: The amplitude scaling factor.\n"
-" :type amplitude_scale: float\n"
-" :arg frequency_scale: The frequency scaling factor\n"
-" :type frequency_scale: float\n"
-" :return: The turbulence vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: turbulence_vector(position, octaves, hard, "
+ "noise_basis='PERLIN_ORIGINAL', amplitude_scale=0.5, frequency_scale=2.0)\n"
+ "\n"
+ " Returns the turbulence vector from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n"
+ " :arg hard: Specifies whether returned turbulence is hard (sharp transitions) or "
+ "soft (smooth transitions).\n"
+ " :type hard: :boolean\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :arg amplitude_scale: The amplitude scaling factor.\n"
+ " :type amplitude_scale: float\n"
+ " :arg frequency_scale: The frequency scaling factor\n"
+ " :type frequency_scale: float\n"
+ " :return: The turbulence vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Noise_turbulence_vector(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "noise_basis", "amplitude_scale", "frequency_scale", NULL};
- PyObject *value;
- float vec[3], r_vec[3];
- const char *noise_basis_str = NULL;
- int oct, hd, noise_basis_enum = DEFAULT_NOISE_TYPE;
- float as = 0.5f, fs = 2.0f;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Oii|$sff:turbulence_vector", (char **)kwlist,
- &value, &oct, &hd, &noise_basis_str, &as, &fs))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "turbulence_vector") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "turbulence_vector: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- vTurb(vec[0], vec[1], vec[2], oct, hd, noise_basis_enum, as, fs, r_vec);
-
- return Vector_CreatePyObject(r_vec, 3, NULL);
+ static const char *kwlist[] = {
+ "", "", "", "noise_basis", "amplitude_scale", "frequency_scale", NULL};
+ PyObject *value;
+ float vec[3], r_vec[3];
+ const char *noise_basis_str = NULL;
+ int oct, hd, noise_basis_enum = DEFAULT_NOISE_TYPE;
+ float as = 0.5f, fs = 2.0f;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Oii|$sff:turbulence_vector",
+ (char **)kwlist,
+ &value,
+ &oct,
+ &hd,
+ &noise_basis_str,
+ &as,
+ &fs)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "turbulence_vector") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "turbulence_vector: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ vTurb(vec[0], vec[1], vec[2], oct, hd, noise_basis_enum, as, fs, r_vec);
+
+ return Vector_CreatePyObject(r_vec, 3, NULL);
}
/* F. Kenton Musgrave's fractal functions */
-PyDoc_STRVAR(M_Noise_fractal_doc,
-".. function:: fractal(position, H, lacunarity, octaves, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns the fractal Brownian motion (fBm) noise value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg H: The fractal increment factor.\n"
-" :type H: float\n"
-" :arg lacunarity: The gap between successive frequencies.\n"
-" :type lacunarity: float\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The fractal Brownian motion noise value.\n"
-" :rtype: float\n"
-);
+PyDoc_STRVAR(
+ M_Noise_fractal_doc,
+ ".. function:: fractal(position, H, lacunarity, octaves, noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns the fractal Brownian motion (fBm) noise value from the noise basis at the "
+ "specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg H: The fractal increment factor.\n"
+ " :type H: float\n"
+ " :arg lacunarity: The gap between successive frequencies.\n"
+ " :type lacunarity: float\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The fractal Brownian motion noise value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_fractal(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- float H, lac, oct;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Offf|$s:fractal", (char **)kwlist,
- &value, &H, &lac, &oct, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "fractal") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "fractal: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_fBm(vec[0], vec[1], vec[2], H, lac, oct, noise_basis_enum));
+ static const char *kwlist[] = {"", "", "", "", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ float H, lac, oct;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Offf|$s:fractal",
+ (char **)kwlist,
+ &value,
+ &H,
+ &lac,
+ &oct,
+ &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "fractal") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "fractal: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(mg_fBm(vec[0], vec[1], vec[2], H, lac, oct, noise_basis_enum));
}
-PyDoc_STRVAR(M_Noise_multi_fractal_doc,
-".. function:: multi_fractal(position, H, lacunarity, octaves, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns multifractal noise value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg H: The fractal increment factor.\n"
-" :type H: float\n"
-" :arg lacunarity: The gap between successive frequencies.\n"
-" :type lacunarity: float\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The multifractal noise value.\n"
-" :rtype: float\n"
-);
+PyDoc_STRVAR(
+ M_Noise_multi_fractal_doc,
+ ".. function:: multi_fractal(position, H, lacunarity, octaves, "
+ "noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns multifractal noise value from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg H: The fractal increment factor.\n"
+ " :type H: float\n"
+ " :arg lacunarity: The gap between successive frequencies.\n"
+ " :type lacunarity: float\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The multifractal noise value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_multi_fractal(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- float H, lac, oct;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Offf|$s:multi_fractal", (char **)kwlist,
- &value, &H, &lac, &oct, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "multi_fractal") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "multi_fractal: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_MultiFractal(vec[0], vec[1], vec[2], H, lac, oct, noise_basis_enum));
+ static const char *kwlist[] = {"", "", "", "", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ float H, lac, oct;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Offf|$s:multi_fractal",
+ (char **)kwlist,
+ &value,
+ &H,
+ &lac,
+ &oct,
+ &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "multi_fractal") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "multi_fractal: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ mg_MultiFractal(vec[0], vec[1], vec[2], H, lac, oct, noise_basis_enum));
}
PyDoc_STRVAR(M_Noise_variable_lacunarity_doc,
-".. function:: variable_lacunarity(position, distortion, noise_type1='PERLIN_ORIGINAL', noise_type2='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns variable lacunarity noise value, a distorted variety of noise, from noise type 1 distorted by noise type 2 at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg distortion: The amount of distortion.\n"
-" :type distortion: float\n"
-" :arg noise_type1: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', 'VORONOI_F1', 'VORONOI_F2', " \
- "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', " \
- "'CELLNOISE'].\n"
-" :type noise_type1: string\n"
-" :arg noise_type2: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', 'VORONOI_F1', 'VORONOI_F2', " \
- "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', " \
- "'CELLNOISE'].\n"
-" :type noise_type2: string\n"
-" :return: The variable lacunarity noise value.\n"
-" :rtype: float\n"
-);
+ ".. function:: variable_lacunarity(position, distortion, "
+ "noise_type1='PERLIN_ORIGINAL', noise_type2='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns variable lacunarity noise value, a distorted variety of noise, from "
+ "noise type 1 distorted by noise type 2 at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg distortion: The amount of distortion.\n"
+ " :type distortion: float\n"
+ " :arg noise_type1: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', "
+ "'VORONOI_F1', 'VORONOI_F2', "
+ "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', "
+ "'CELLNOISE'].\n"
+ " :type noise_type1: string\n"
+ " :arg noise_type2: Enumerator in ['BLENDER', 'PERLIN_ORIGINAL', 'PERLIN_NEW', "
+ "'VORONOI_F1', 'VORONOI_F2', "
+ "'VORONOI_F3', 'VORONOI_F4', 'VORONOI_F2F1', 'VORONOI_CRACKLE', "
+ "'CELLNOISE'].\n"
+ " :type noise_type2: string\n"
+ " :return: The variable lacunarity noise value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_variable_lacunarity(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "noise_type1", "noise_type2", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_type1_str = NULL, *noise_type2_str = NULL;
- float d;
- int noise_type1_enum = DEFAULT_NOISE_TYPE, noise_type2_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Of|$ss:variable_lacunarity", (char **)kwlist,
- &value, &d, &noise_type1_str, &noise_type2_str))
- {
- return NULL;
- }
-
- if (!noise_type1_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_type1_str, &noise_type1_enum, "variable_lacunarity") == -1)
- {
- return NULL;
- }
-
- if (!noise_type2_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_type2_str, &noise_type2_enum, "variable_lacunarity") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "variable_lacunarity: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_VLNoise(vec[0], vec[1], vec[2], d, noise_type1_enum, noise_type2_enum));
+ static const char *kwlist[] = {"", "", "noise_type1", "noise_type2", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_type1_str = NULL, *noise_type2_str = NULL;
+ float d;
+ int noise_type1_enum = DEFAULT_NOISE_TYPE, noise_type2_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Of|$ss:variable_lacunarity",
+ (char **)kwlist,
+ &value,
+ &d,
+ &noise_type1_str,
+ &noise_type2_str)) {
+ return NULL;
+ }
+
+ if (!noise_type1_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_type1_str, &noise_type1_enum, "variable_lacunarity") == -1) {
+ return NULL;
+ }
+
+ if (!noise_type2_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_type2_str, &noise_type2_enum, "variable_lacunarity") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "variable_lacunarity: invalid 'position' arg") ==
+ -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ mg_VLNoise(vec[0], vec[1], vec[2], d, noise_type1_enum, noise_type2_enum));
}
-PyDoc_STRVAR(M_Noise_hetero_terrain_doc,
-".. function:: hetero_terrain(position, H, lacunarity, octaves, offset, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns the heterogeneous terrain value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg H: The fractal dimension of the roughest areas.\n"
-" :type H: float\n"
-" :arg lacunarity: The gap between successive frequencies.\n"
-" :type lacunarity: float\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-" :arg offset: The height of the terrain above 'sea level'.\n"
-" :type offset: float\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The heterogeneous terrain value.\n"
-" :rtype: float\n"
-);
+PyDoc_STRVAR(
+ M_Noise_hetero_terrain_doc,
+ ".. function:: hetero_terrain(position, H, lacunarity, octaves, offset, "
+ "noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns the heterogeneous terrain value from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg H: The fractal dimension of the roughest areas.\n"
+ " :type H: float\n"
+ " :arg lacunarity: The gap between successive frequencies.\n"
+ " :type lacunarity: float\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n"
+ " :arg offset: The height of the terrain above 'sea level'.\n"
+ " :type offset: float\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The heterogeneous terrain value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_hetero_terrain(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "", "", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- float H, lac, oct, ofs;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Offff|$s:hetero_terrain", (char **)kwlist,
- &value, &H, &lac, &oct, &ofs, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "hetero_terrain") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "hetero_terrain: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_HeteroTerrain(vec[0], vec[1], vec[2], H, lac, oct, ofs, noise_basis_enum));
+ static const char *kwlist[] = {"", "", "", "", "", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ float H, lac, oct, ofs;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Offff|$s:hetero_terrain",
+ (char **)kwlist,
+ &value,
+ &H,
+ &lac,
+ &oct,
+ &ofs,
+ &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "hetero_terrain") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "hetero_terrain: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ mg_HeteroTerrain(vec[0], vec[1], vec[2], H, lac, oct, ofs, noise_basis_enum));
}
-PyDoc_STRVAR(M_Noise_hybrid_multi_fractal_doc,
-".. function:: hybrid_multi_fractal(position, H, lacunarity, octaves, offset, gain, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns hybrid multifractal value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg H: The fractal dimension of the roughest areas.\n"
-" :type H: float\n"
-" :arg lacunarity: The gap between successive frequencies.\n"
-" :type lacunarity: float\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-" :arg offset: The height of the terrain above 'sea level'.\n"
-" :type offset: float\n"
-" :arg gain: Scaling applied to the values.\n"
-" :type gain: float\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The hybrid multifractal value.\n"
-" :rtype: float\n"
-);
+PyDoc_STRVAR(
+ M_Noise_hybrid_multi_fractal_doc,
+ ".. function:: hybrid_multi_fractal(position, H, lacunarity, octaves, offset, gain, "
+ "noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns hybrid multifractal value from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg H: The fractal dimension of the roughest areas.\n"
+ " :type H: float\n"
+ " :arg lacunarity: The gap between successive frequencies.\n"
+ " :type lacunarity: float\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n"
+ " :arg offset: The height of the terrain above 'sea level'.\n"
+ " :type offset: float\n"
+ " :arg gain: Scaling applied to the values.\n"
+ " :type gain: float\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The hybrid multifractal value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_hybrid_multi_fractal(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "", "", "", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- float H, lac, oct, ofs, gn;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Offfff|$s:hybrid_multi_fractal", (char **)kwlist,
- &value, &H, &lac, &oct, &ofs, &gn, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "hybrid_multi_fractal") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "hybrid_multi_fractal: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_HybridMultiFractal(vec[0], vec[1], vec[2], H, lac, oct, ofs, gn, noise_basis_enum));
+ static const char *kwlist[] = {"", "", "", "", "", "", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ float H, lac, oct, ofs, gn;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Offfff|$s:hybrid_multi_fractal",
+ (char **)kwlist,
+ &value,
+ &H,
+ &lac,
+ &oct,
+ &ofs,
+ &gn,
+ &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "hybrid_multi_fractal") ==
+ -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "hybrid_multi_fractal: invalid 'position' arg") ==
+ -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ mg_HybridMultiFractal(vec[0], vec[1], vec[2], H, lac, oct, ofs, gn, noise_basis_enum));
}
-PyDoc_STRVAR(M_Noise_ridged_multi_fractal_doc,
-".. function:: ridged_multi_fractal(position, H, lacunarity, octaves, offset, gain, noise_basis='PERLIN_ORIGINAL')\n"
-"\n"
-" Returns ridged multifractal value from the noise basis at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :arg H: The fractal dimension of the roughest areas.\n"
-" :type H: float\n"
-" :arg lacunarity: The gap between successive frequencies.\n"
-" :type lacunarity: float\n"
-" :arg octaves: The number of different noise frequencies used.\n"
-" :type octaves: int\n"
-" :arg offset: The height of the terrain above 'sea level'.\n"
-" :type offset: float\n"
-" :arg gain: Scaling applied to the values.\n"
-" :type gain: float\n"
-BPY_NOISE_BASIS_ENUM_DOC
-" :return: The ridged multifractal value.\n"
-" :rtype: float\n"
-);
+PyDoc_STRVAR(
+ M_Noise_ridged_multi_fractal_doc,
+ ".. function:: ridged_multi_fractal(position, H, lacunarity, octaves, offset, gain, "
+ "noise_basis='PERLIN_ORIGINAL')\n"
+ "\n"
+ " Returns ridged multifractal value from the noise basis at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :arg H: The fractal dimension of the roughest areas.\n"
+ " :type H: float\n"
+ " :arg lacunarity: The gap between successive frequencies.\n"
+ " :type lacunarity: float\n"
+ " :arg octaves: The number of different noise frequencies used.\n"
+ " :type octaves: int\n"
+ " :arg offset: The height of the terrain above 'sea level'.\n"
+ " :type offset: float\n"
+ " :arg gain: Scaling applied to the values.\n"
+ " :type gain: float\n" BPY_NOISE_BASIS_ENUM_DOC
+ " :return: The ridged multifractal value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_ridged_multi_fractal(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "", "", "", "", "", "noise_basis", NULL};
- PyObject *value;
- float vec[3];
- const char *noise_basis_str = NULL;
- float H, lac, oct, ofs, gn;
- int noise_basis_enum = DEFAULT_NOISE_TYPE;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "Offfff|$s:ridged_multi_fractal", (char **)kwlist,
- &value, &H, &lac, &oct, &ofs, &gn, &noise_basis_str))
- {
- return NULL;
- }
-
- if (!noise_basis_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_types, noise_basis_str, &noise_basis_enum, "ridged_multi_fractal") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "ridged_multi_fractal: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- return PyFloat_FromDouble(mg_RidgedMultiFractal(vec[0], vec[1], vec[2], H, lac, oct, ofs, gn, noise_basis_enum));
+ static const char *kwlist[] = {"", "", "", "", "", "", "noise_basis", NULL};
+ PyObject *value;
+ float vec[3];
+ const char *noise_basis_str = NULL;
+ float H, lac, oct, ofs, gn;
+ int noise_basis_enum = DEFAULT_NOISE_TYPE;
+
+ if (!PyArg_ParseTupleAndKeywords(args,
+ kw,
+ "Offfff|$s:ridged_multi_fractal",
+ (char **)kwlist,
+ &value,
+ &H,
+ &lac,
+ &oct,
+ &ofs,
+ &gn,
+ &noise_basis_str)) {
+ return NULL;
+ }
+
+ if (!noise_basis_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(
+ bpy_noise_types, noise_basis_str, &noise_basis_enum, "ridged_multi_fractal") ==
+ -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "ridged_multi_fractal: invalid 'position' arg") ==
+ -1) {
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(
+ mg_RidgedMultiFractal(vec[0], vec[1], vec[2], H, lac, oct, ofs, gn, noise_basis_enum));
}
PyDoc_STRVAR(M_Noise_voronoi_doc,
-".. function:: voronoi(position, distance_metric='DISTANCE', exponent=2.5)\n"
-"\n"
-" Returns a list of distances to the four closest features and their locations.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-BPY_NOISE_METRIC_ENUM_DOC
-" :arg exponent: The exponent for Minkowski distance metric.\n"
-" :type exponent: float\n"
-" :return: A list of distances to the four closest features and their locations.\n"
-" :rtype: list of four floats, list of four :class:`mathutils.Vector` types\n"
-);
+ ".. function:: voronoi(position, distance_metric='DISTANCE', exponent=2.5)\n"
+ "\n"
+ " Returns a list of distances to the four closest features and their locations.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n" BPY_NOISE_METRIC_ENUM_DOC
+ " :arg exponent: The exponent for Minkowski distance metric.\n"
+ " :type exponent: float\n"
+ " :return: A list of distances to the four closest features and their locations.\n"
+ " :rtype: list of four floats, list of four :class:`mathutils.Vector` types\n");
static PyObject *M_Noise_voronoi(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"", "distance_metric", "exponent", NULL};
- PyObject *value;
- PyObject *list;
- PyObject *ret;
- float vec[3];
- const char *metric_str = NULL;
- float da[4], pa[12];
- int metric_enum = DEFAULT_METRIC_TYPE;
- float me = 2.5f; /* default minkowski exponent */
-
- int i;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "O|$sf:voronoi", (char **)kwlist,
- &value, &metric_str, &me))
- {
- return NULL;
- }
-
- if (!metric_str) {
- /* pass through */
- }
- else if (PyC_FlagSet_ValueFromID(
- bpy_noise_metrics, metric_str, &metric_enum, "voronoi") == -1)
- {
- return NULL;
- }
-
- if (mathutils_array_parse(vec, 3, 3, value, "voronoi: invalid 'position' arg") == -1) {
- return NULL;
- }
-
- list = PyList_New(4);
-
- voronoi(vec[0], vec[1], vec[2], da, pa, me, metric_enum);
-
- for (i = 0; i < 4; i++) {
- PyObject *v = Vector_CreatePyObject(pa + 3 * i, 3, NULL);
- PyList_SET_ITEM(list, i, v);
- }
-
- ret = Py_BuildValue("[[ffff]O]", da[0], da[1], da[2], da[3], list);
- Py_DECREF(list);
- return ret;
+ static const char *kwlist[] = {"", "distance_metric", "exponent", NULL};
+ PyObject *value;
+ PyObject *list;
+ PyObject *ret;
+ float vec[3];
+ const char *metric_str = NULL;
+ float da[4], pa[12];
+ int metric_enum = DEFAULT_METRIC_TYPE;
+ float me = 2.5f; /* default minkowski exponent */
+
+ int i;
+
+ if (!PyArg_ParseTupleAndKeywords(
+ args, kw, "O|$sf:voronoi", (char **)kwlist, &value, &metric_str, &me)) {
+ return NULL;
+ }
+
+ if (!metric_str) {
+ /* pass through */
+ }
+ else if (PyC_FlagSet_ValueFromID(bpy_noise_metrics, metric_str, &metric_enum, "voronoi") == -1) {
+ return NULL;
+ }
+
+ if (mathutils_array_parse(vec, 3, 3, value, "voronoi: invalid 'position' arg") == -1) {
+ return NULL;
+ }
+
+ list = PyList_New(4);
+
+ voronoi(vec[0], vec[1], vec[2], da, pa, me, metric_enum);
+
+ for (i = 0; i < 4; i++) {
+ PyObject *v = Vector_CreatePyObject(pa + 3 * i, 3, NULL);
+ PyList_SET_ITEM(list, i, v);
+ }
+
+ ret = Py_BuildValue("[[ffff]O]", da[0], da[1], da[2], da[3], list);
+ Py_DECREF(list);
+ return ret;
}
PyDoc_STRVAR(M_Noise_cell_doc,
-".. function:: cell(position)\n"
-"\n"
-" Returns cell noise value at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :return: The cell noise value.\n"
-" :rtype: float\n"
-);
+ ".. function:: cell(position)\n"
+ "\n"
+ " Returns cell noise value at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :return: The cell noise value.\n"
+ " :rtype: float\n");
static PyObject *M_Noise_cell(PyObject *UNUSED(self), PyObject *args)
{
- PyObject *value;
- float vec[3];
+ PyObject *value;
+ float vec[3];
- if (!PyArg_ParseTuple(args, "O:cell", &value)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O:cell", &value)) {
+ return NULL;
+ }
- if (mathutils_array_parse(vec, 3, 3, value, "cell: invalid 'position' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(vec, 3, 3, value, "cell: invalid 'position' arg") == -1) {
+ return NULL;
+ }
- return PyFloat_FromDouble(cellNoise(vec[0], vec[1], vec[2]));
+ return PyFloat_FromDouble(cellNoise(vec[0], vec[1], vec[2]));
}
PyDoc_STRVAR(M_Noise_cell_vector_doc,
-".. function:: cell_vector(position)\n"
-"\n"
-" Returns cell noise vector at the specified position.\n"
-"\n"
-" :arg position: The position to evaluate the selected noise function.\n"
-" :type position: :class:`mathutils.Vector`\n"
-" :return: The cell noise vector.\n"
-" :rtype: :class:`mathutils.Vector`\n"
-);
+ ".. function:: cell_vector(position)\n"
+ "\n"
+ " Returns cell noise vector at the specified position.\n"
+ "\n"
+ " :arg position: The position to evaluate the selected noise function.\n"
+ " :type position: :class:`mathutils.Vector`\n"
+ " :return: The cell noise vector.\n"
+ " :rtype: :class:`mathutils.Vector`\n");
static PyObject *M_Noise_cell_vector(PyObject *UNUSED(self), PyObject *args)
{
- PyObject *value;
- float vec[3], r_vec[3];
+ PyObject *value;
+ float vec[3], r_vec[3];
- if (!PyArg_ParseTuple(args, "O:cell_vector", &value)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "O:cell_vector", &value)) {
+ return NULL;
+ }
- if (mathutils_array_parse(vec, 3, 3, value, "cell_vector: invalid 'position' arg") == -1) {
- return NULL;
- }
+ if (mathutils_array_parse(vec, 3, 3, value, "cell_vector: invalid 'position' arg") == -1) {
+ return NULL;
+ }
- cellNoiseV(vec[0], vec[1], vec[2], r_vec);
- return Vector_CreatePyObject(r_vec, 3, NULL);
+ cellNoiseV(vec[0], vec[1], vec[2], r_vec);
+ return Vector_CreatePyObject(r_vec, 3, NULL);
}
static PyMethodDef M_Noise_methods[] = {
- {"seed_set", (PyCFunction) M_Noise_seed_set, METH_VARARGS, M_Noise_seed_set_doc},
- {"random", (PyCFunction) M_Noise_random, METH_NOARGS, M_Noise_random_doc},
- {"random_unit_vector", (PyCFunction) M_Noise_random_unit_vector, METH_VARARGS | METH_KEYWORDS, M_Noise_random_unit_vector_doc},
- {"random_vector", (PyCFunction) M_Noise_random_vector, METH_VARARGS | METH_KEYWORDS, M_Noise_random_vector_doc},
- {"noise", (PyCFunction) M_Noise_noise, METH_VARARGS | METH_KEYWORDS, M_Noise_noise_doc},
- {"noise_vector", (PyCFunction) M_Noise_noise_vector, METH_VARARGS | METH_KEYWORDS, M_Noise_noise_vector_doc},
- {"turbulence", (PyCFunction) M_Noise_turbulence, METH_VARARGS | METH_KEYWORDS, M_Noise_turbulence_doc},
- {"turbulence_vector", (PyCFunction) M_Noise_turbulence_vector, METH_VARARGS | METH_KEYWORDS, M_Noise_turbulence_vector_doc},
- {"fractal", (PyCFunction) M_Noise_fractal, METH_VARARGS | METH_KEYWORDS, M_Noise_fractal_doc},
- {"multi_fractal", (PyCFunction) M_Noise_multi_fractal, METH_VARARGS | METH_KEYWORDS, M_Noise_multi_fractal_doc},
- {"variable_lacunarity", (PyCFunction) M_Noise_variable_lacunarity, METH_VARARGS | METH_KEYWORDS, M_Noise_variable_lacunarity_doc},
- {"hetero_terrain", (PyCFunction) M_Noise_hetero_terrain, METH_VARARGS | METH_KEYWORDS, M_Noise_hetero_terrain_doc},
- {"hybrid_multi_fractal", (PyCFunction) M_Noise_hybrid_multi_fractal, METH_VARARGS | METH_KEYWORDS, M_Noise_hybrid_multi_fractal_doc},
- {"ridged_multi_fractal", (PyCFunction) M_Noise_ridged_multi_fractal, METH_VARARGS | METH_KEYWORDS, M_Noise_ridged_multi_fractal_doc},
- {"voronoi", (PyCFunction) M_Noise_voronoi, METH_VARARGS | METH_KEYWORDS, M_Noise_voronoi_doc},
- {"cell", (PyCFunction) M_Noise_cell, METH_VARARGS, M_Noise_cell_doc},
- {"cell_vector", (PyCFunction) M_Noise_cell_vector, METH_VARARGS, M_Noise_cell_vector_doc},
- {NULL, NULL, 0, NULL},
+ {"seed_set", (PyCFunction)M_Noise_seed_set, METH_VARARGS, M_Noise_seed_set_doc},
+ {"random", (PyCFunction)M_Noise_random, METH_NOARGS, M_Noise_random_doc},
+ {"random_unit_vector",
+ (PyCFunction)M_Noise_random_unit_vector,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_random_unit_vector_doc},
+ {"random_vector",
+ (PyCFunction)M_Noise_random_vector,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_random_vector_doc},
+ {"noise", (PyCFunction)M_Noise_noise, METH_VARARGS | METH_KEYWORDS, M_Noise_noise_doc},
+ {"noise_vector",
+ (PyCFunction)M_Noise_noise_vector,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_noise_vector_doc},
+ {"turbulence",
+ (PyCFunction)M_Noise_turbulence,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_turbulence_doc},
+ {"turbulence_vector",
+ (PyCFunction)M_Noise_turbulence_vector,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_turbulence_vector_doc},
+ {"fractal", (PyCFunction)M_Noise_fractal, METH_VARARGS | METH_KEYWORDS, M_Noise_fractal_doc},
+ {"multi_fractal",
+ (PyCFunction)M_Noise_multi_fractal,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_multi_fractal_doc},
+ {"variable_lacunarity",
+ (PyCFunction)M_Noise_variable_lacunarity,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_variable_lacunarity_doc},
+ {"hetero_terrain",
+ (PyCFunction)M_Noise_hetero_terrain,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_hetero_terrain_doc},
+ {"hybrid_multi_fractal",
+ (PyCFunction)M_Noise_hybrid_multi_fractal,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_hybrid_multi_fractal_doc},
+ {"ridged_multi_fractal",
+ (PyCFunction)M_Noise_ridged_multi_fractal,
+ METH_VARARGS | METH_KEYWORDS,
+ M_Noise_ridged_multi_fractal_doc},
+ {"voronoi", (PyCFunction)M_Noise_voronoi, METH_VARARGS | METH_KEYWORDS, M_Noise_voronoi_doc},
+ {"cell", (PyCFunction)M_Noise_cell, METH_VARARGS, M_Noise_cell_doc},
+ {"cell_vector", (PyCFunction)M_Noise_cell_vector, METH_VARARGS, M_Noise_cell_vector_doc},
+ {NULL, NULL, 0, NULL},
};
static struct PyModuleDef M_Noise_module_def = {
- PyModuleDef_HEAD_INIT,
- "mathutils.noise", /* m_name */
- M_Noise_doc, /* m_doc */
- 0, /* m_size */
- M_Noise_methods, /* m_methods */
- NULL, /* m_reload */
- NULL, /* m_traverse */
- NULL, /* m_clear */
- NULL, /* m_free */
+ PyModuleDef_HEAD_INIT,
+ "mathutils.noise", /* m_name */
+ M_Noise_doc, /* m_doc */
+ 0, /* m_size */
+ M_Noise_methods, /* m_methods */
+ NULL, /* m_reload */
+ NULL, /* m_traverse */
+ NULL, /* m_clear */
+ NULL, /* m_free */
};
/*----------------------------MODULE INIT-------------------------*/
PyMODINIT_FUNC PyInit_mathutils_noise(void)
{
- PyObject *submodule = PyModule_Create(&M_Noise_module_def);
+ PyObject *submodule = PyModule_Create(&M_Noise_module_def);
- /* use current time as seed for random number generator by default */
- setRndSeed(0);
+ /* use current time as seed for random number generator by default */
+ setRndSeed(0);
- return submodule;
+ return submodule;
}