Add Chromium-only Blender WebEngine parity work

This commit is contained in:
mes123456
2026-08-12 04:47:48 -04:00
commit 9fd26010f6
18225 changed files with 11622124 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
# SPDX-FileCopyrightText: 2023 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later
set(INC
.
)
set(INC_SYS
)
set(SRC
mathutils.cc
mathutils_Color.cc
mathutils_Euler.cc
mathutils_Matrix.cc
mathutils_Quaternion.cc
mathutils_Vector.cc
mathutils_bvhtree.cc
mathutils_geometry.cc
mathutils_interpolate.cc
mathutils_kdtree.cc
mathutils_noise.cc
mathutils.hh
mathutils_Color.hh
mathutils_Euler.hh
mathutils_Matrix.hh
mathutils_Quaternion.hh
mathutils_Vector.hh
mathutils_bvhtree.hh
mathutils_geometry.hh
mathutils_interpolate.hh
mathutils_kdtree.hh
mathutils_noise.hh
)
set(LIB
PRIVATE bf::blenkernel
PRIVATE bf::blenlib
PRIVATE bf::bmesh
PRIVATE bf::depsgraph
PRIVATE bf::dna
PRIVATE bf::imbuf
PRIVATE bf::intern::guardedalloc
bf_python_ext
PRIVATE bf::dependencies::optional::python
)
blender_add_lib(bf_python_mathutils "${SRC}" "${INC}" "${INC_SYS}" "${LIB}")

View File

@@ -0,0 +1,900 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.hh"
#include "BLI_math_matrix.h"
#include "BLI_math_rotation.h"
#include "BLI_utildefines.h"
#include "../generic/py_capi_utils.hh"
#ifndef MATH_STANDALONE
# include "BLI_dynstr.h"
#endif
namespace blender {
PyDoc_STRVAR(
/* Wrap. */
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"
"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,
const int array_num,
PyObject *value_fast,
const char *error_prefix)
{
/* Could be allowed but hints at errors, since we would typically want to avoid
* converting to a FAST sequence for an empty `array`. */
BLI_assert(array_num > 0);
PyObject *item;
PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
for (int i = 0; i < array_num; 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);
return -1;
}
}
return array_num;
}
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(nullptr, 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 mathutils_array_parse(
float *array, int array_num_min, int array_num_max, PyObject *value, const char *error_prefix)
{
const uint flag = array_num_max;
int num;
array_num_max &= ~MU_ARRAY_FLAGS;
#if 1 /* approx 6x speedup for mathutils types */
if ((num = VectorObject_Check(value) ? (reinterpret_cast<VectorObject *>(value))->vec_num : 0) ||
(num = EulerObject_Check(value) ? 3 : 0) || (num = QuaternionObject_Check(value) ? 4 : 0) ||
(num = ColorObject_Check(value) ? 3 : 0))
{
if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
return -1;
}
if (flag & MU_ARRAY_SPILL) {
CLAMP_MAX(num, array_num_max);
}
if (num > array_num_max || num < array_num_min) {
if (array_num_max == array_num_min) {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence length is %d, expected %d",
error_prefix,
num,
array_num_max);
}
else {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence length is %d, expected [%d - %d]",
error_prefix,
num,
array_num_min,
array_num_max);
}
return -1;
}
memcpy(array, (reinterpret_cast<const BaseMathObject *>(value))->data, num * sizeof(float));
}
else
#endif
{
PyObject *value_fast = nullptr;
/* non list/tuple cases */
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
num = PySequence_Fast_GET_SIZE(value_fast);
if (flag & MU_ARRAY_SPILL) {
CLAMP_MAX(num, array_num_max);
}
if (num > array_num_max || num < array_num_min) {
if (array_num_max == array_num_min) {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence length is %d, expected %d",
error_prefix,
num,
array_num_max);
}
else {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence length is %d, expected [%d - %d]",
error_prefix,
num,
array_num_min,
array_num_max);
}
Py_DECREF(value_fast);
return -1;
}
if (num != 0) {
num = mathutils_array_parse_fast(array, num, value_fast, error_prefix);
}
Py_DECREF(value_fast);
}
if (num != -1) {
if (flag & MU_ARRAY_ZERO) {
const int array_num_left = array_num_max - num;
if (array_num_left) {
memset(&array[num], 0, sizeof(float) * array_num_left);
}
}
}
return num;
}
int mathutils_array_parse_alloc(float **array,
int array_num_min,
PyObject *value,
const char *error_prefix)
{
int num;
#if 1 /* approx 6x speedup for mathutils types */
if ((num = VectorObject_Check(value) ? (reinterpret_cast<VectorObject *>(value))->vec_num : 0) ||
(num = EulerObject_Check(value) ? 3 : 0) || (num = QuaternionObject_Check(value) ? 4 : 0) ||
(num = ColorObject_Check(value) ? 3 : 0))
{
if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
return -1;
}
if (num < array_num_min) {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence size is %d, expected >= %d",
error_prefix,
num,
array_num_min);
return -1;
}
*array = static_cast<float *>(PyMem_Malloc(num * sizeof(float)));
memcpy(*array, (reinterpret_cast<const BaseMathObject *>(value))->data, num * sizeof(float));
return num;
}
#endif
PyObject *value_fast = nullptr;
// *array = nullptr;
int ret;
/* non list/tuple cases */
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
num = PySequence_Fast_GET_SIZE(value_fast);
if (num < array_num_min) {
Py_DECREF(value_fast);
PyErr_Format(PyExc_ValueError,
"%.200s: sequence size is %d, expected >= %d",
error_prefix,
num,
array_num_min);
return -1;
}
*array = static_cast<float *>(PyMem_Malloc(num * sizeof(float)));
ret = (num != 0) ? mathutils_array_parse_fast(*array, num, value_fast, error_prefix) : 0;
Py_DECREF(value_fast);
if (ret == -1) {
PyMem_Free(*array);
}
return ret;
}
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, num;
/* non list/tuple cases */
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
num = PySequence_Fast_GET_SIZE(value_fast);
if (num != 0) {
PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
float *fp;
array_dim &= ~MU_ARRAY_FLAGS;
fp = *array = static_cast<float *>(PyMem_Malloc(num * array_dim * sizeof(float)));
for (i = 0; i < num; 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 = nullptr;
num = -1;
break;
}
}
}
Py_DECREF(value_fast);
return num;
}
int mathutils_int_array_parse(int *array, int array_dim, PyObject *value, const char *error_prefix)
{
int size, i;
PyObject *value_fast, **value_fast_items, *item;
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
if ((size = PySequence_Fast_GET_SIZE(value_fast)) != array_dim) {
PyErr_Format(PyExc_ValueError,
"%.200s: sequence size is %d, expected %d",
error_prefix,
size,
array_dim);
Py_DECREF(value_fast);
return -1;
}
value_fast_items = PySequence_Fast_ITEMS(value_fast);
i = size;
while (i > 0) {
i--;
if (((array[i] = PyC_Long_AsI32(item = value_fast_items[i])) == -1) && PyErr_Occurred()) {
PyErr_Format(PyExc_TypeError, "%.200s: sequence index %d expected an int", error_prefix, i);
size = -1;
break;
}
}
Py_DECREF(value_fast);
return size;
}
int mathutils_array_parse_alloc_vi(int **array,
int array_dim,
PyObject *value,
const char *error_prefix)
{
PyObject *value_fast;
int i, size;
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return -1;
}
size = PySequence_Fast_GET_SIZE(value_fast);
if (size != 0) {
PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
int *ip;
ip = *array = static_cast<int *>(PyMem_Malloc(size * array_dim * sizeof(int)));
for (i = 0; i < size; i++, ip += array_dim) {
PyObject *item = value_fast_items[i];
if (mathutils_int_array_parse(ip, array_dim, item, error_prefix) == -1) {
PyMem_Free(*array);
*array = nullptr;
size = -1;
break;
}
}
}
Py_DECREF(value_fast);
return size;
}
bool mathutils_array_parse_alloc_viseq(PyObject *value,
const char *error_prefix,
Array<Vector<int>> &r_data)
{
PyObject *value_fast;
if (!(value_fast = PySequence_Fast(value, error_prefix))) {
/* PySequence_Fast sets the error */
return false;
}
const int size = PySequence_Fast_GET_SIZE(value_fast);
if (size != 0) {
PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
r_data.reinitialize(size);
for (const int64_t i : r_data.index_range()) {
PyObject *subseq = value_fast_items[i];
const int subseq_len = int(PySequence_Size(subseq));
if (subseq_len == -1) {
PyErr_Format(
PyExc_ValueError, "%.200s: sequence expected to have subsequences", error_prefix);
Py_DECREF(value_fast);
return false;
}
r_data[i].resize(subseq_len);
MutableSpan<int> group = r_data[i];
if (mathutils_int_array_parse(group.data(), group.size(), subseq, error_prefix) == -1) {
Py_DECREF(value_fast);
return false;
}
}
}
Py_DECREF(value_fast);
return true;
}
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;
}
eulO_to_mat3(rmat,
(reinterpret_cast<const EulerObject *>(value))->eul,
(reinterpret_cast<const EulerObject *>(value))->order);
return 0;
}
if (QuaternionObject_Check(value)) {
if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
return -1;
}
float tquat[4];
normalize_qt_qt(tquat, (reinterpret_cast<const QuaternionObject *>(value))->quat);
quat_to_mat3(rmat, tquat);
return 0;
}
if (MatrixObject_Check(value)) {
if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
return -1;
}
if ((reinterpret_cast<MatrixObject *>(value))->row_num < 3 ||
(reinterpret_cast<MatrixObject *>(value))->col_num < 3)
{
PyErr_Format(
PyExc_ValueError, "%.200s: matrix must have minimum 3x3 dimensions", error_prefix);
return -1;
}
matrix_as_3x3(rmat, reinterpret_cast<MatrixObject *>(value));
normalize_m3(rmat);
return 0;
}
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 */
/* XXX We may want to use 'safer' BLI's compare_ff_relative ultimately?
* LomontRRDCompare4() is an optimized version of Dawson's AlmostEqual2sComplement()
* (see [1] and [2]).
* Dawson himself now claims this is not a 'safe' thing to do
* (pushing ULP method beyond its limits),
* an recommends using work from [3] instead, which is done in BLI func...
*
* [1] http://www.randydillon.org/Papers/2007/everfast.htm
* [2] http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
* [3] https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
* instead.
*/
#define SIGNMASK(i) (-int((uint(i)) >> 31))
int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
{
/* solid, fast routine across all platforms
* with constant time behavior */
const int ai = *reinterpret_cast<const int *>(&af);
const int bi = *reinterpret_cast<const int *>(&bf);
const int test = SIGNMASK(ai ^ bi);
int diff, v1, v2;
BLI_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;
}
#ifndef MATH_STANDALONE
PyObject *mathutils_dynstr_to_py(DynStr *ds)
{
const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
char *ds_buf = static_cast<char *>(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
/* Mathutils Callbacks */
/* For mathutils internal use only,
* eventually should re-alloc but to start with we only have a few users. */
#define MATHUTILS_TOT_CB 17
static Mathutils_Callback *mathutils_callbacks[MATHUTILS_TOT_CB] = {nullptr};
uchar Mathutils_RegisterCallback(Mathutils_Callback *cb)
{
uchar 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);
mathutils_callbacks[i] = cb;
return i;
}
int _BaseMathObject_CheckCallback(BaseMathObject *self)
{
Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
if (LIKELY(cb->check(self) != -1)) {
return 0;
}
return -1;
}
int _BaseMathObject_ReadCallback(BaseMathObject *self)
{
/* NOTE: use macros to check for nullptr. */
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;
}
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;
}
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;
}
void _BaseMathObject_RaiseFrozenExc(const BaseMathObject *self)
{
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);
}
int _BaseMathObject_ResizeOkOrRaiseExc(BaseMathObject *self, const char *error_prefix)
{
if (UNLIKELY(self->flag & BASE_MATH_FLAG_IS_FROZEN)) {
PyErr_Format(PyExc_ValueError, "%s: cannot resize frozen data", error_prefix);
return -1;
}
if (UNLIKELY(self->flag & BASE_MATH_FLAG_IS_WRAP)) {
PyErr_Format(PyExc_ValueError, "%s: cannot resize wrapped data", error_prefix);
return -1;
}
if (UNLIKELY(self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW)) {
PyErr_Format(PyExc_BufferError,
"%s: cannot resize data while exported to buffer protocol",
error_prefix);
return -1;
}
if (UNLIKELY(self->cb_user)) {
PyErr_Format(PyExc_ValueError, "%s: cannot resize owned data", error_prefix);
return -1;
}
return 0;
}
int _BaseMathObject_RaiseBufferViewExc(BaseMathObject *self, Py_buffer *view, int flags)
{
if (UNLIKELY(view == nullptr)) {
PyErr_SetString(PyExc_BufferError, "null view in get-buffer is obsolete");
return -1;
}
if (UNLIKELY(self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW)) {
PyErr_SetString(PyExc_BufferError,
"Data is already exported via buffer protocol, "
"multiple simultaneous exports are not allowed.");
return -1;
}
if (flags & PyBUF_WRITABLE) {
if (UNLIKELY(BaseMath_WriteCallback(self) == -1)) {
return -1;
}
if (UNLIKELY(self->flag & BASE_MATH_FLAG_IS_FROZEN)) {
PyErr_SetString(PyExc_BufferError, "Data is frozen, cannot get a writable buffer");
return -1;
}
}
return 0;
}
/* #BaseMathObject generic functions for all mathutils types. */
char BaseMathObject_owner_doc[] =
"The item this is wrapping or None (read-only).\n"
"\n"
":type: Any";
PyObject *BaseMathObject_owner_get(BaseMathObject *self, void * /*closure*/)
{
PyObject *ret = self->cb_user ? self->cb_user : Py_None;
return Py_NewRef(ret);
}
char BaseMathObject_is_wrapped_doc[] =
"True when this object wraps external data (read-only).\n\n:type: bool";
PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void * /*closure*/)
{
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: bool";
PyObject *BaseMathObject_is_frozen_get(BaseMathObject *self, void * /*closure*/)
{
return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_FROZEN) != 0);
}
char BaseMathObject_is_valid_doc[] = "True when the owner of this data is valid.\n\n:type: bool";
PyObject *BaseMathObject_is_valid_get(BaseMathObject *self, void * /*closure*/)
{
return PyBool_FromLong(BaseMath_CheckCallback(self) == 0);
}
char BaseMathObject_freeze_doc[] =
".. method:: 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"
" :rtype: Self\n";
PyObject *BaseMathObject_freeze(BaseMathObject *self)
{
if ((self->flag & BASE_MATH_FLAG_IS_WRAP) || (self->cb_user != nullptr)) {
PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped/owned data");
return nullptr;
}
if (self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW) {
PyErr_SetString(PyExc_BufferError, "Cannot freeze data while exported to buffer protocol");
return nullptr;
}
self->flag |= BASE_MATH_FLAG_IS_FROZEN;
return Py_NewRef(self);
}
int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->cb_user);
return 0;
}
int BaseMathObject_clear(BaseMathObject *self)
{
Py_CLEAR(self->cb_user);
return 0;
}
/** Only to validate assumptions when debugging. */
#ifndef NDEBUG
static bool BaseMathObject_is_tracked(BaseMathObject *self)
{
PyObject *cb_user = self->cb_user;
self->cb_user = reinterpret_cast<PyObject *>(uintptr_t(-1));
bool is_tracked = PyObject_GC_IsTracked(reinterpret_cast<PyObject *>(self));
self->cb_user = cb_user;
return is_tracked;
}
#endif /* !NDEBUG */
void BaseMathObject_dealloc(BaseMathObject *self)
{
/* only free non wrapped */
if ((self->flag & BASE_MATH_FLAG_IS_WRAP) == 0) {
PyMem_Free(self->data);
}
if (self->cb_user) {
BLI_assert(BaseMathObject_is_tracked(self) == true);
PyObject_GC_UnTrack(self);
BaseMathObject_clear(self);
}
else if (!BaseMathObject_CheckExact(self)) {
/* Subclassed types get an extra track (in Pythons internal `subtype_dealloc` function). */
BLI_assert(BaseMathObject_is_tracked(self) == true);
PyObject_GC_UnTrack(self);
BLI_assert(BaseMathObject_is_tracked(self) == false);
}
Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); /* breaks sub-types. */
}
int BaseMathObject_is_gc(BaseMathObject *self)
{
return self->cb_user != nullptr;
}
PyObject *_BaseMathObject_new_impl(PyTypeObject *root_type, PyTypeObject *base_type)
{
PyObject *obj;
if (ELEM(base_type, nullptr, root_type)) {
obj = _PyObject_GC_New(root_type);
if (obj) {
BLI_assert(BaseMathObject_is_tracked((BaseMathObject *)obj) == false);
}
}
else {
/* Calls Generic allocation function which always tracks
* (because `root_type` is flagged for GC). */
obj = base_type->tp_alloc(base_type, 0);
if (obj) {
BLI_assert(BaseMathObject_is_tracked((BaseMathObject *)obj) == true);
PyObject_GC_UnTrack(obj);
BLI_assert(BaseMathObject_is_tracked((BaseMathObject *)obj) == false);
}
}
return obj;
}
/*----------------------------MODULE INIT-------------------------*/
static PyMethodDef M_Mathutils_methods[] = {
{nullptr, nullptr, 0, nullptr},
};
static PyModuleDef M_Mathutils_module_def = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "mathutils",
/*m_doc*/ M_Mathutils_doc,
/*m_size*/ 0,
/*m_methods*/ M_Mathutils_methods,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
} // namespace blender
/* submodules only */
#include "mathutils_geometry.hh"
#include "mathutils_interpolate.hh"
#ifndef MATH_STANDALONE
# include "mathutils_bvhtree.hh"
# include "mathutils_kdtree.hh"
# include "mathutils_noise.hh"
#endif
namespace blender {
PyMODINIT_FUNC PyInit_mathutils()
{
PyObject *mod;
PyObject *submodule;
PyObject *sys_modules = PyImport_GetModuleDict();
if (PyType_Ready(&vector_Type) < 0) {
return nullptr;
}
if (PyType_Ready(&matrix_Type) < 0) {
return nullptr;
}
if (PyType_Ready(&matrix_access_Type) < 0) {
return nullptr;
}
if (PyType_Ready(&euler_Type) < 0) {
return nullptr;
}
if (PyType_Ready(&quaternion_Type) < 0) {
return nullptr;
}
if (PyType_Ready(&color_Type) < 0) {
return nullptr;
}
mod = PyModule_Create(&M_Mathutils_module_def);
/* each type has its own new() function */
PyModule_AddType(mod, &vector_Type);
PyModule_AddType(mod, &matrix_Type);
PyModule_AddType(mod, &matrix_access_Type);
PyModule_AddType(mod, &euler_Type);
PyModule_AddType(mod, &quaternion_Type);
PyModule_AddType(mod, &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. */
PyC_Module_AddToSysModules(sys_modules, submodule);
PyModule_AddObject(mod, "interpolate", (submodule = PyInit_mathutils_interpolate()));
/* XXX, python doesn't do imports with this usefully yet
* 'from mathutils.geometry import PolyFill'
* ...fails without this. */
PyC_Module_AddToSysModules(sys_modules, submodule);
#ifndef MATH_STANDALONE
/* Noise submodule */
PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
PyC_Module_AddToSysModules(sys_modules, submodule);
/* BVHTree submodule */
PyModule_AddObject(mod, "bvhtree", (submodule = PyInit_mathutils_bvhtree()));
PyC_Module_AddToSysModules(sys_modules, submodule);
/* KDTree<float3> submodule */
PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree()));
PyC_Module_AddToSysModules(sys_modules, 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);
return mod;
}
} // namespace blender

View File

@@ -0,0 +1,290 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
/* Can cast different mathutils types to this, use for generic functions. */
#include "BLI_array.hh"
#include "BLI_vector.hh"
namespace blender {
struct DynStr;
extern char BaseMathObject_is_wrapped_doc[];
extern char BaseMathObject_is_frozen_doc[];
extern char BaseMathObject_is_valid_doc[];
extern char BaseMathObject_owner_doc[];
[[nodiscard]] PyObject *_BaseMathObject_new_impl(PyTypeObject *root_type, PyTypeObject *base_type);
#define BASE_MATH_NEW(struct_name, root_type, base_type) \
((struct_name *)_BaseMathObject_new_impl(&root_type, base_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),
/**
* When set, prevents calling freeze() and resize() while using the buffer protocol.
*
* \note `memoryview` & `np.frombuffer` pass the `PyBUF_FORMAT | PyBUF_INDIRECT` flags,
* and the object can be mutated, so `PyBUF_WRITABLE` can't be handled.
* That's why it's always necessary to check for write access.
*/
BASE_MATH_FLAG_HAS_BUFFER_VIEW = (1 << 2),
};
#define BASE_MATH_FLAG_DEFAULT 0
#define BASE_MATH_MEMBERS(_data) \
/** Array of data (alias), wrapped status depends on wrapped status. */ \
PyObject_HEAD \
float *_data; \
/** If this vector references another object, otherwise NULL, *Note* this owns its reference */ \
PyObject *cb_user; \
/** Which user functions do we adhere to, RNA, etc */ \
unsigned char cb_type; \
/** Sub-type: location, rotation... \
* to avoid defining many new functions for every attribute of the same type */ \
unsigned char cb_subtype; \
/** Wrapped data type. */ \
unsigned char flag
struct BaseMathObject {
BASE_MATH_MEMBERS(data);
};
} // namespace blender
/* types */
#include "mathutils_Color.hh" // IWYU pragma: export
#include "mathutils_Euler.hh" // IWYU pragma: export
#include "mathutils_Matrix.hh" // IWYU pragma: export
#include "mathutils_Quaternion.hh" // IWYU pragma: export
#include "mathutils_Vector.hh" // IWYU pragma: export
namespace blender {
/* avoid checking all types */
#define BaseMathObject_CheckExact(v) (Py_TYPE(v)->tp_dealloc == (destructor)BaseMathObject_dealloc)
[[nodiscard]] PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *);
[[nodiscard]] PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *);
[[nodiscard]] PyObject *BaseMathObject_is_frozen_get(BaseMathObject *self, void *);
[[nodiscard]] PyObject *BaseMathObject_is_valid_get(BaseMathObject *self, void *);
extern char BaseMathObject_freeze_doc[];
[[nodiscard]] PyObject *BaseMathObject_freeze(BaseMathObject *self);
int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg);
int BaseMathObject_clear(BaseMathObject *self);
void BaseMathObject_dealloc(BaseMathObject *self);
int BaseMathObject_is_gc(BaseMathObject *self);
PyMODINIT_FUNC PyInit_mathutils();
[[nodiscard]] int EXPP_FloatsAreEqual(float af, float bf, int maxDiff);
[[nodiscard]] int EXPP_VectorsAreEqual(const float *vecA,
const float *vecB,
int size,
int floatSteps);
/** Checks the user is still valid. */
using BaseMathCheckFunc = int (*)(BaseMathObject *);
/** Gets the vector from the user. */
using BaseMathGetFunc = int (*)(BaseMathObject *, int);
/** Sets the users vector values once its modified. */
using BaseMathSetFunc = int (*)(BaseMathObject *, int);
/** Same as #BaseMathGetFunc but only for an index. */
using BaseMathGetIndexFunc = int (*)(BaseMathObject *, int, int);
/** Same as #BaseMathSetFunc but only for an index. */
using BaseMathSetIndexFunc = int (*)(BaseMathObject *, int, int);
struct Mathutils_Callback {
BaseMathCheckFunc check;
BaseMathGetFunc get;
BaseMathSetFunc set;
BaseMathGetIndexFunc get_index;
BaseMathSetIndexFunc set_index;
};
[[nodiscard]] unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb);
[[nodiscard]] int _BaseMathObject_CheckCallback(BaseMathObject *self);
[[nodiscard]] int _BaseMathObject_ReadCallback(BaseMathObject *self);
[[nodiscard]] int _BaseMathObject_WriteCallback(BaseMathObject *self);
[[nodiscard]] int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index);
[[nodiscard]] int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index);
/** To implement #BaseMath_Prepare_ForResize. */
[[nodiscard]] int _BaseMathObject_ResizeOkOrRaiseExc(BaseMathObject *self,
const char *error_prefix);
[[nodiscard]] int _BaseMathObject_RaiseBufferViewExc(BaseMathObject *self,
Py_buffer *view,
int flags);
void _BaseMathObject_RaiseFrozenExc(const BaseMathObject *self);
void _BaseMathObject_RaiseNotFrozenExc(const BaseMathObject *self);
/* since this is called so often avoid where possible */
#define BaseMath_CheckCallback(_self) \
(((_self)->cb_user ? _BaseMathObject_CheckCallback((BaseMathObject *)_self) : 0))
#define BaseMath_ReadCallback(_self) \
(((_self)->cb_user ? _BaseMathObject_ReadCallback((BaseMathObject *)_self) : 0))
#define BaseMath_WriteCallback(_self) \
(((_self)->cb_user ? _BaseMathObject_WriteCallback((BaseMathObject *)_self) : 0))
#define BaseMath_ReadIndexCallback(_self, _index) \
(((_self)->cb_user ? _BaseMathObject_ReadIndexCallback((BaseMathObject *)_self, _index) : 0))
#define BaseMath_WriteIndexCallback(_self, _index) \
(((_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)))
#define BaseMath_ReadIndexCallback_ForWrite(_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)
#define BaseMathObject_Prepare_ForHash(_self) \
(UNLIKELY(((_self)->flag & BASE_MATH_FLAG_IS_FROZEN) == 0) ? \
(_BaseMathObject_RaiseNotFrozenExc((BaseMathObject *)_self), -1) : \
0)
/**
* Helper to de-duplicate checks for in-place resizing.
* \return -1 and set an exception if the vector `_self` cannot be resized.
*/
#define BaseMathObject_Prepare_ForResize(_self, error_prefix) \
_BaseMathObject_ResizeOkOrRaiseExc((BaseMathObject *)_self, error_prefix)
/**
* Ensure #BASE_MATH_FLAG_HAS_BUFFER_VIEW is supported.
* \param _view: The `view` argument forwarded from #PyBufferProcs::bf_getbuffer.
* \param _flags: The `flags` argument forwarded from #PyBufferProcs::bf_getbuffer.
* \return -1 and set an exception if the vector `_self` does not support buffer access.
*/
#define BaseMath_Prepare_ForBufferAccess(_self, _view, _flags) \
_BaseMathObject_RaiseBufferViewExc((BaseMathObject *)_self, _view, _flags)
/* utility func */
/**
* Helper function.
* \return length of `value`, -1 on error.
*/
[[nodiscard]] int mathutils_array_parse(
float *array, int array_num_min, int array_num_max, PyObject *value, const char *error_prefix);
/**
* \return -1 is returned on error and no allocation is made.
*/
[[nodiscard]] int mathutils_array_parse_alloc(float **array,
int array_num_min,
PyObject *value,
const char *error_prefix);
/**
* Parse an array of vectors.
*/
[[nodiscard]] int mathutils_array_parse_alloc_v(float **array,
int array_dim,
PyObject *value,
const char *error_prefix);
/**
* Parse an sequence array_dim integers into array.
*/
[[nodiscard]] int mathutils_int_array_parse(int *array,
int array_dim,
PyObject *value,
const char *error_prefix);
/**
* Parse sequence of array_dim sequences of integers and return allocated result.
*/
[[nodiscard]] int mathutils_array_parse_alloc_vi(int **array,
int array_dim,
PyObject *value,
const char *error_prefix);
/**
* Parse sequence of variable-length sequences of integers and fill r_data with their values.
*/
[[nodiscard]] bool mathutils_array_parse_alloc_viseq(PyObject *value,
const char *error_prefix,
Array<Vector<int>> &r_data);
[[nodiscard]] int mathutils_any_to_rotmat(float rmat[3][3],
PyObject *value,
const char *error_prefix);
/**
* Returns true when a slice does *not* address every element of an `array_num`.
*/
[[nodiscard]] inline bool mathutils_slice_is_subset(Py_ssize_t start,
Py_ssize_t step,
Py_ssize_t slice_length,
Py_ssize_t array_num)
{
return !((slice_length == array_num) &&
/* All forward `[:]`. */
((start == 0 && step == 1) ||
/* All reverse `[::-1]`. */
(start == array_num - 1 && step == -1)));
}
/**
* helper function that returns a Python `__hash__`.
*
* \note consistent with the equivalent tuple of floats (CPython's `tuplehash`)
*/
[[nodiscard]] Py_hash_t mathutils_array_hash(const float *array, size_t array_len);
/** Zero remaining unused elements of the array. */
#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_FLAGS (MU_ARRAY_ZERO | MU_ARRAY_SPILL)
/**
* Column vector multiplication (Matrix * Vector).
* <pre>
* [1][4][7] [a]
* [2][5][8] * [b]
* [3][6][9] [c]
* </pre>
*
* \note Vector/Matrix multiplication is not commutative.
* \note Assume read callbacks have been done first.
*/
[[nodiscard]] int column_vector_multiplication(float r_vec[4],
VectorObject *vec,
MatrixObject *mat);
#ifndef MATH_STANDALONE
/* dynstr as python string utility functions, frees 'ds'! */
[[nodiscard]] PyObject *mathutils_dynstr_to_py(struct DynStr *ds);
#endif
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pymathutils
*/
#pragma once
#include <Python.h>
#include "mathutils.hh"
namespace blender {
extern PyTypeObject color_Type;
#define ColorObject_Check(v) PyObject_TypeCheck((v), &color_Type)
#define ColorObject_CheckExact(v) (Py_TYPE(v) == &color_Type)
struct ColorObject {
BASE_MATH_MEMBERS(col);
};
/* struct data contains a pointer to the actual data that the
* object uses. It can use either PyMem allocated data (which will
* be stored in py_data) or be a wrapper for data allocated through
* Blender (stored in blend_data). This is an either/or struct not both. */
/* Prototypes. */
[[nodiscard]] PyObject *Color_CreatePyObject(const float col[3], PyTypeObject *base_type);
[[nodiscard]] PyObject *Color_CreatePyObject_wrap(float col[3], PyTypeObject *base_type)
ATTR_NONNULL(1);
[[nodiscard]] PyObject *Color_CreatePyObject_cb(PyObject *cb_user,
unsigned char cb_type,
unsigned char cb_subtype);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.hh"
namespace blender {
extern PyTypeObject euler_Type;
#define EulerObject_Check(v) PyObject_TypeCheck((v), &euler_Type)
#define EulerObject_CheckExact(v) (Py_TYPE(v) == &euler_Type)
struct EulerObject {
BASE_MATH_MEMBERS(eul);
unsigned char order; /* rotation order */
};
/* struct data contains a pointer to the actual data that the
* object uses. It can use either PyMem allocated data (which will
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both */
/* prototypes */
[[nodiscard]] PyObject *Euler_CreatePyObject(const float eul[3],
short order,
PyTypeObject *base_type);
[[nodiscard]] PyObject *Euler_CreatePyObject_wrap(float eul[3],
short order,
PyTypeObject *base_type) ATTR_NONNULL(1);
[[nodiscard]] PyObject *Euler_CreatePyObject_cb(PyObject *cb_user,
short order,
unsigned char cb_type,
unsigned char cb_subtype);
[[nodiscard]] short euler_order_from_string(const char *str, const char *error_prefix);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,97 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pymathutils
*/
#pragma once
#include <Python.h>
#include "mathutils.hh"
namespace blender {
extern PyTypeObject matrix_Type;
extern PyTypeObject matrix_access_Type;
using ushort = unsigned short;
#define MatrixObject_Check(v) PyObject_TypeCheck((v), &matrix_Type)
#define MatrixObject_CheckExact(v) (Py_TYPE(v) == &matrix_Type)
#define MATRIX_MAX_DIM 4
/* matrix[row][col] == MATRIX_ITEM_INDEX(matrix, row, col) */
#ifndef NDEBUG
# define MATRIX_ITEM_ASSERT(_mat, _row, _col) \
(BLI_assert(_row < (_mat)->row_num && _col < (_mat)->col_num))
#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)->row_num * (_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))
struct MatrixObject {
BASE_MATH_MEMBERS(matrix);
ushort col_num;
ushort row_num;
};
/* struct data contains a pointer to the actual data that the
* object uses. It can use either PyMem allocated data (which will
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both */
/* Prototypes. */
[[nodiscard]] PyObject *Matrix_CreatePyObject(const float *mat,
ushort col_num,
ushort row_num,
PyTypeObject *base_type);
[[nodiscard]] PyObject *Matrix_CreatePyObject_wrap(float *mat,
ushort col_num,
ushort row_num,
PyTypeObject *base_type) ATTR_NONNULL(1);
[[nodiscard]] PyObject *Matrix_CreatePyObject_cb(PyObject *cb_user,
unsigned short col_num,
unsigned short row_num,
unsigned char cb_type,
unsigned char cb_subtype);
/**
* \param mat: Initialized matrix value to use in-place, allocated with #PyMem_Malloc
*/
[[nodiscard]] PyObject *Matrix_CreatePyObject_alloc(float *mat,
ushort col_num,
ushort row_num,
PyTypeObject *base_type);
/* PyArg_ParseTuple's "O&" formatting helpers. */
[[nodiscard]] int Matrix_ParseAny(PyObject *o, void *p);
[[nodiscard]] int Matrix_Parse2x2(PyObject *o, void *p);
[[nodiscard]] int Matrix_Parse3x3(PyObject *o, void *p);
[[nodiscard]] int Matrix_Parse4x4(PyObject *o, void *p);
extern unsigned char mathutils_matrix_row_cb_index; /* default */
extern unsigned char mathutils_matrix_col_cb_index;
extern unsigned char mathutils_matrix_translation_cb_index;
extern struct Mathutils_Callback mathutils_matrix_row_cb; /* default */
extern struct Mathutils_Callback mathutils_matrix_col_cb;
extern struct Mathutils_Callback mathutils_matrix_translation_cb;
void matrix_as_3x3(float mat[3][3], MatrixObject *self);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.hh"
namespace blender {
extern PyTypeObject quaternion_Type;
#define QuaternionObject_Check(v) PyObject_TypeCheck((v), &quaternion_Type)
#define QuaternionObject_CheckExact(v) (Py_TYPE(v) == &quaternion_Type)
struct QuaternionObject {
BASE_MATH_MEMBERS(quat);
};
/* struct data contains a pointer to the actual data that the
* object uses. It can use either PyMem allocated data (which will
* be stored in py_data) or be a wrapper for data allocated through
* blender (stored in blend_data). This is an either/or struct not both */
/* Prototypes. */
[[nodiscard]] PyObject *Quaternion_CreatePyObject(const float quat[4], PyTypeObject *base_type);
[[nodiscard]] PyObject *Quaternion_CreatePyObject_wrap(float quat[4], PyTypeObject *base_type)
ATTR_NONNULL(1);
[[nodiscard]] PyObject *Quaternion_CreatePyObject_cb(PyObject *cb_user,
unsigned char cb_type,
unsigned char cb_subtype);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pymathutils
*/
#pragma once
#include <Python.h>
#include "mathutils.hh"
namespace blender {
extern PyTypeObject vector_Type;
#define VectorObject_Check(v) PyObject_TypeCheck((v), &vector_Type)
#define VectorObject_CheckExact(v) (Py_TYPE(v) == &vector_Type)
struct VectorObject {
BASE_MATH_MEMBERS(vec);
/** Number of items in this vector (2 or more). */
int vec_num;
};
/* Prototypes. */
[[nodiscard]] PyObject *Vector_CreatePyObject(const float *vec,
int vec_num,
PyTypeObject *base_type);
/**
* Create a vector that wraps existing memory.
*
* \param vec: Use this vector in-place.
*/
[[nodiscard]] PyObject *Vector_CreatePyObject_wrap(float *vec,
int vec_num,
PyTypeObject *base_type) ATTR_NONNULL(1);
/**
* Create a vector where the value is defined by registered callbacks,
* see: #Mathutils_RegisterCallback
*/
[[nodiscard]] PyObject *Vector_CreatePyObject_cb(PyObject *cb_user,
int vec_num,
unsigned char cb_type,
unsigned char cb_subtype);
/**
* \param vec: Initialized vector value to use in-place, allocated with #PyMem_Malloc
*/
[[nodiscard]] PyObject *Vector_CreatePyObject_alloc(float *vec,
int vec_num,
PyTypeObject *base_type) ATTR_NONNULL(1);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,22 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup mathutils
*/
#pragma once
#include <Python.h>
namespace blender {
PyMODINIT_FUNC PyInit_mathutils_bvhtree();
extern PyTypeObject PyBVHTree_Type;
#define PyBVHTree_Check(v) PyObject_TypeCheck((v), &PyBVHTree_Type)
#define PyBVHTree_CheckExact(v) (Py_TYPE(v) == &PyBVHTree_Type)
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
namespace blender {
PyMODINIT_FUNC PyInit_mathutils_geometry();
} // namespace blender

View File

@@ -0,0 +1,120 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
#include "mathutils.hh"
#include "mathutils_interpolate.hh"
#include "BLI_math_geom.h"
namespace blender {
#ifndef MATH_STANDALONE /* define when building outside blender */
# include "MEM_guardedalloc.h"
#endif
/* ---------------------------------WEIGHT CALCULATION ----------------------- */
#ifndef MATH_STANDALONE
PyDoc_STRVAR(
/* Wrap. */
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"
" :param veclist: Sequence of 3D positions.\n"
" :type veclist: Sequence[Sequence[float]]\n"
" :param pt: 2D or 3D position.\n"
" :type pt: Sequence[float]\n"
" :return: A list of weights, one per vertex in *veclist*.\n"
" :rtype: list[float]\n");
static PyObject *M_Interpolate_poly_3d_calc(PyObject * /*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, &point)) {
return nullptr;
}
if (mathutils_array_parse(
fp, 2, 3 | MU_ARRAY_ZERO, point, "pt must be a 2-3 dimensional vector") == -1)
{
return nullptr;
}
len = mathutils_array_parse_alloc_v((reinterpret_cast<float **>(&vecs)), 3, veclist, __func__);
if (len == -1) {
return nullptr;
}
if (len) {
float *weights = MEM_new_array_uninitialized<float>(size_t(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_delete(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",
static_cast<PyCFunction>(M_Interpolate_poly_3d_calc),
METH_VARARGS,
M_Interpolate_poly_3d_calc_doc},
#endif
{nullptr, nullptr, 0, nullptr},
};
PyDoc_STRVAR(
/* Wrap. */
M_Interpolate_doc,
"The Blender interpolate module.");
static PyModuleDef M_Interpolate_module_def = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "mathutils.interpolate",
/*m_doc*/ M_Interpolate_doc,
/*m_size*/ 0,
/*m_methods*/ M_Interpolate_methods,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
/*----------------------------MODULE INIT-------------------------*/
PyMODINIT_FUNC PyInit_mathutils_interpolate()
{
PyObject *submodule = PyModule_Create(&M_Interpolate_module_def);
return submodule;
}
} // namespace blender

View File

@@ -0,0 +1,17 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pymathutils
*/
#include <Python.h>
namespace blender {
PyMODINIT_FUNC PyInit_mathutils_interpolate();
} // namespace blender

View File

@@ -0,0 +1,524 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup mathutils
*
* This file defines the 'mathutils.kdtree' module, a general purpose module to access
* blenders kdtree for 3d spatial lookups.
*/
#include <Python.h>
#include "MEM_guardedalloc.h"
#include "BLI_kdtree.hh"
#include "BLI_utildefines.h"
#include "../generic/py_capi_utils.hh"
#include "../generic/python_utildefines.hh"
#include "mathutils.hh"
#include "mathutils_kdtree.hh" /* own include */
#include "BLI_strict_flags.h" /* IWYU pragma: keep. Keep last. */
namespace blender {
struct PyKDTree {
PyObject_HEAD
KDTree<float3> *obj;
uint maxsize;
uint count;
uint count_balance; /* size when we last balanced */
};
/* -------------------------------------------------------------------- */
/* Utility helper functions */
static void kdtree_nearest_to_py_tuple(const KDTreeNearest<float3> *nearest, PyObject *py_retval)
{
BLI_assert(nearest->index >= 0);
BLI_assert(PyTuple_GET_SIZE(py_retval) == 3);
PyTuple_SET_ITEMS(py_retval,
Vector_CreatePyObject(nearest->co, 3, nullptr),
PyLong_FromLong(nearest->index),
PyFloat_FromDouble(nearest->dist));
}
static PyObject *kdtree_nearest_to_py(const KDTreeNearest<float3> *nearest)
{
PyObject *py_retval;
py_retval = PyTuple_New(3);
kdtree_nearest_to_py_tuple(nearest, py_retval);
return py_retval;
}
static PyObject *kdtree_nearest_to_py_and_check(const KDTreeNearest<float3> *nearest)
{
PyObject *py_retval;
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);
}
return py_retval;
}
/* -------------------------------------------------------------------- */
/* KDTree */
/* annoying since arg parsing won't check overflow */
#define UINT_IS_NEG(n) ((n) > INT_MAX)
static int PyKDTree__tp_init(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
uint maxsize;
const char *keywords[] = {"size", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "I:KDTree", const_cast<char **>(keywords), &maxsize))
{
return -1;
}
if (UINT_IS_NEG(maxsize)) {
PyErr_SetString(PyExc_ValueError, "negative 'size' given");
return -1;
}
self->obj = kdtree_new<float3>(maxsize);
self->maxsize = maxsize;
self->count = 0;
/* Initialize `uint-max` to avoid crashes on unbalanced trees. */
self->count_balance = uint(-1);
return 0;
}
static void PyKDTree__tp_dealloc(PyKDTree *self)
{
kdtree_free<float3>(self->obj);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject *>(self));
}
PyDoc_STRVAR(
/* Wrap. */
py_kdtree_insert_doc,
".. method:: insert(co, index)\n"
"\n"
" Insert a point into the KDTree.\n"
"\n"
" :param co: Point 3d position.\n"
" :type co: Sequence[float]\n"
" :param index: The index of the point (must be non-negative).\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", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "Oi:insert", const_cast<char **>(keywords), &py_co, &index))
{
return nullptr;
}
if (mathutils_array_parse(co, 3, 3, py_co, "insert: invalid 'co' arg") == -1) {
return nullptr;
}
if (index < 0) {
PyErr_SetString(PyExc_ValueError, "negative index given");
return nullptr;
}
if (self->count >= self->maxsize) {
PyErr_SetString(PyExc_RuntimeError, "Trying to insert more items than KDTree has room for");
return nullptr;
}
kdtree_insert<float3>(self->obj, index, co);
self->count++;
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
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");
static PyObject *py_kdtree_balance(PyKDTree *self)
{
kdtree_balance<float3>(self->obj);
self->count_balance = self->count;
Py_RETURN_NONE;
}
struct PyKDTree_NearestData {
PyObject *py_filter;
bool is_error;
};
static int py_find_nearest_cb(void *user_data, int index, const float3 &co, float dist_sq)
{
UNUSED_VARS(co, dist_sq);
PyKDTree_NearestData *data = static_cast<PyKDTree_NearestData *>(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;
const int ok = PyC_ParseBool(result, &use_node);
Py_DECREF(result);
if (ok) {
return int(use_node);
}
}
data->is_error = true;
return -1;
}
PyDoc_STRVAR(
/* Wrap. */
py_kdtree_find_doc,
".. method:: find(co, *, filter=None)\n"
"\n"
" Find nearest point to ``co``.\n"
"\n"
" :param co: 3D coordinate.\n"
" :type co: Sequence[float]\n"
" :param filter: function which takes an index and returns True for indices to "
"include in the search.\n"
" :type filter: Callable[[int], bool] | None\n"
" :return: Returns (position, index, distance),\n"
" or (None, None, None) when no match is found.\n"
" :rtype: tuple[:class:`Vector`, int, float] | tuple[None, None, None]\n");
static PyObject *py_kdtree_find(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
PyObject *py_co, *py_filter = Py_None;
float co[3];
KDTreeNearest<float3> nearest;
const char *keywords[] = {"co", "filter", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "O|$O:find", const_cast<char **>(keywords), &py_co, &py_filter))
{
return nullptr;
}
if (mathutils_array_parse(co, 3, 3, py_co, "find: invalid 'co' arg") == -1) {
return nullptr;
}
if (self->count != self->count_balance) {
PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find()");
return nullptr;
}
nearest.index = -1;
if (py_filter == Py_None) {
kdtree_find_nearest<float3>(self->obj, co, &nearest);
}
else {
PyKDTree_NearestData data = {nullptr};
data.py_filter = py_filter;
data.is_error = false;
kdtree_find_nearest_cb<float3>(
self->obj, co, &nearest, [&](int index, const float3 &co_nearest, float dist_sq) {
return py_find_nearest_cb(&data, index, co_nearest, dist_sq);
});
if (data.is_error) {
return nullptr;
}
}
return kdtree_nearest_to_py_and_check(&nearest);
}
PyDoc_STRVAR(
/* Wrap. */
py_kdtree_find_n_doc,
".. method:: find_n(co, n)\n"
"\n"
" Find nearest ``n`` points to ``co``.\n"
"\n"
" :param co: 3D coordinate.\n"
" :type co: Sequence[float]\n"
" :param n: Number of points to find.\n"
" :type n: int\n"
" :return: Returns a list of tuples (position, index, distance).\n"
" :rtype: list[tuple[:class:`Vector`, int, float]]\n");
static PyObject *py_kdtree_find_n(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
PyObject *py_list;
PyObject *py_co;
float co[3];
KDTreeNearest<float3> *nearest;
uint n;
int i, found;
const char *keywords[] = {"co", "n", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "OI:find_n", const_cast<char **>(keywords), &py_co, &n))
{
return nullptr;
}
if (mathutils_array_parse(co, 3, 3, py_co, "find_n: invalid 'co' arg") == -1) {
return nullptr;
}
if (UINT_IS_NEG(n)) {
PyErr_SetString(PyExc_RuntimeError, "negative 'n' given");
return nullptr;
}
if (self->count != self->count_balance) {
PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_n()");
return nullptr;
}
nearest = MEM_new_array_uninitialized<KDTreeNearest<float3>>(n, __func__);
found = kdtree_find_nearest_n<float3>(self->obj, co, nearest, n);
py_list = PyList_New(found);
for (i = 0; i < found; i++) {
PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
}
MEM_delete(nearest);
return py_list;
}
PyDoc_STRVAR(
/* Wrap. */
py_kdtree_find_range_doc,
".. method:: find_range(co, radius)\n"
"\n"
" Find all points within ``radius`` of ``co``.\n"
"\n"
" :param co: 3D coordinate.\n"
" :type co: Sequence[float]\n"
" :param radius: Maximum distance to search for points.\n"
" :type radius: float\n"
" :return: Returns a list of tuples (position, index, distance).\n"
" :rtype: list[tuple[:class:`Vector`, int, float]]\n");
static PyObject *py_kdtree_find_range(PyKDTree *self, PyObject *args, PyObject *kwargs)
{
PyObject *py_list;
PyObject *py_co;
float co[3];
KDTreeNearest<float3> *nearest = nullptr;
float radius;
int i, found;
const char *keywords[] = {"co", "radius", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args, kwargs, "Of:find_range", const_cast<char **>(keywords), &py_co, &radius))
{
return nullptr;
}
if (mathutils_array_parse(co, 3, 3, py_co, "find_range: invalid 'co' arg") == -1) {
return nullptr;
}
if (radius < 0.0f) {
PyErr_SetString(PyExc_RuntimeError, "negative radius given");
return nullptr;
}
if (self->count != self->count_balance) {
PyErr_SetString(PyExc_RuntimeError, "KDTree must be balanced before calling find_range()");
return nullptr;
}
found = kdtree_range_search<float3>(self->obj, co, &nearest, radius);
py_list = PyList_New(found);
for (i = 0; i < found; i++) {
PyList_SET_ITEM(py_list, i, kdtree_nearest_to_py(&nearest[i]));
}
if (nearest) {
MEM_delete(nearest);
}
return py_list;
}
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-function-type"
# else
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-function-type"
# endif
#endif
static PyMethodDef PyKDTree_methods[] = {
{"insert",
reinterpret_cast<PyCFunction>(py_kdtree_insert),
METH_VARARGS | METH_KEYWORDS,
py_kdtree_insert_doc},
{"balance",
reinterpret_cast<PyCFunction>(py_kdtree_balance),
METH_NOARGS,
py_kdtree_balance_doc},
{"find",
reinterpret_cast<PyCFunction>(py_kdtree_find),
METH_VARARGS | METH_KEYWORDS,
py_kdtree_find_doc},
{"find_n",
reinterpret_cast<PyCFunction>(py_kdtree_find_n),
METH_VARARGS | METH_KEYWORDS,
py_kdtree_find_n_doc},
{"find_range",
reinterpret_cast<PyCFunction>(py_kdtree_find_range),
METH_VARARGS | METH_KEYWORDS,
py_kdtree_find_range_doc},
{nullptr, nullptr, 0, nullptr},
};
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic pop
# else
# pragma GCC diagnostic pop
# endif
#endif
PyDoc_STRVAR(
/* Wrap. */
py_KDtree_doc,
".. class:: KDTree(size)\n"
"\n"
" KDTree(size) -> new kd-tree initialized to hold up to ``size`` items.\n"
"\n"
" :param size: Maximum number of items.\n"
" :type size: int\n"
"\n"
" .. note::\n"
"\n"
" :meth:`KDTree.balance` must have been called before using any of the ``find`` "
"methods.\n");
PyTypeObject PyKDTree_Type = {
/*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
/*tp_name*/ "KDTree",
/*tp_basicsize*/ sizeof(PyKDTree),
/*tp_itemsize*/ 0,
/*tp_dealloc*/ reinterpret_cast<destructor>(PyKDTree__tp_dealloc),
/*tp_vectorcall_offset*/ 0,
/*tp_getattr*/ nullptr,
/*tp_setattr*/ nullptr,
/*tp_as_async*/ nullptr,
/*tp_repr*/ nullptr,
/*tp_as_number*/ nullptr,
/*tp_as_sequence*/ nullptr,
/*tp_as_mapping*/ nullptr,
/*tp_hash*/ nullptr,
/*tp_call*/ nullptr,
/*tp_str*/ nullptr,
/*tp_getattro*/ nullptr,
/*tp_setattro*/ nullptr,
/*tp_as_buffer*/ nullptr,
/*tp_flags*/ Py_TPFLAGS_DEFAULT,
/*tp_doc*/ py_KDtree_doc,
/*tp_traverse*/ nullptr,
/*tp_clear*/ nullptr,
/*tp_richcompare*/ nullptr,
/*tp_weaklistoffset*/ 0,
/*tp_iter*/ nullptr,
/*tp_iternext*/ nullptr,
/*tp_methods*/ static_cast<PyMethodDef *>(PyKDTree_methods),
/*tp_members*/ nullptr,
/*tp_getset*/ nullptr,
/*tp_base*/ nullptr,
/*tp_dict*/ nullptr,
/*tp_descr_get*/ nullptr,
/*tp_descr_set*/ nullptr,
/*tp_dictoffset*/ 0,
/*tp_init*/ reinterpret_cast<initproc>(PyKDTree__tp_init),
/*tp_alloc*/ static_cast<allocfunc>(PyType_GenericAlloc),
/*tp_new*/ static_cast<newfunc>(PyType_GenericNew),
/*tp_free*/ static_cast<freefunc>(nullptr),
/*tp_is_gc*/ nullptr,
/*tp_bases*/ nullptr,
/*tp_mro*/ nullptr,
/*tp_cache*/ nullptr,
/*tp_subclasses*/ nullptr,
/*tp_weaklist*/ nullptr,
/*tp_del*/ static_cast<destructor>(nullptr),
/*tp_version_tag*/ 0,
/*tp_finalize*/ nullptr,
/*tp_vectorcall*/ nullptr,
};
PyDoc_STRVAR(
/* Wrap. */
py_kdtree_doc,
"Generic 3-dimensional kd-tree to perform spatial searches.");
static PyModuleDef kdtree_moduledef = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "mathutils.kdtree",
/*m_doc*/ py_kdtree_doc,
/*m_size*/ 0,
/*m_methods*/ nullptr,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
PyMODINIT_FUNC PyInit_mathutils_kdtree()
{
PyObject *m = PyModule_Create(&kdtree_moduledef);
if (m == nullptr) {
return nullptr;
}
/* Register the 'KDTree' class */
if (PyType_Ready(&PyKDTree_Type)) {
return nullptr;
}
PyModule_AddType(m, &PyKDTree_Type);
return m;
}
} // namespace blender

View File

@@ -0,0 +1,19 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup mathutils
*/
#pragma once
#include <Python.h>
namespace blender {
PyMODINIT_FUNC PyInit_mathutils_kdtree();
extern PyTypeObject PyKDTree_Type;
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,17 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup mathutils
*/
#pragma once
#include <Python.h>
namespace blender {
PyMODINIT_FUNC PyInit_mathutils_noise();
} // namespace blender