Blender V5.3
mathutils.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <Python.h>
10
11#include "mathutils.hh"
12
13#include "BLI_math_matrix_c.hh"
15#include "BLI_offset_indices.hh"
16#include "BLI_utildefines.hh"
17
19
20#ifndef MATH_STANDALONE
21# include "BLI_dynstr.hh"
22#endif
23
24namespace blender {
25
27 /* Wrap. */
28 M_Mathutils_doc,
29 "This module provides access to math operations.\n"
30 "\n"
31 ".. note::\n"
32 "\n"
33 " Classes, methods and attributes that accept vectors also accept other numeric sequences,\n"
34 " such as tuples, lists.\n"
35 "\n"
36 "The :mod:`mathutils` module provides the following classes:\n"
37 "\n"
38 "- :class:`Color`,\n"
39 "- :class:`Euler`,\n"
40 "- :class:`Matrix`,\n"
41 "- :class:`Quaternion`,\n"
42 "- :class:`Vector`,\n");
43
45 const int array_num,
46 PyObject *value_fast,
47 const char *error_prefix)
48{
49 /* Could be allowed but hints at errors, since we would typically want to avoid
50 * converting to a FAST sequence for an empty `array`. */
51 BLI_assert(array_num > 0);
52 PyObject *item;
53 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
54 for (int i = 0; i < array_num; i++) {
55 if (((array[i] = PyFloat_AsDouble(item = value_fast_items[i])) == -1.0f) && PyErr_Occurred()) {
56 PyErr_Format(PyExc_TypeError,
57 "%.200s: sequence index %d expected a number, "
58 "found '%.200s' type, ",
59 error_prefix,
60 i,
61 Py_TYPE(item)->tp_name);
62 return -1;
63 }
64 }
65
66 return array_num;
67}
68
69Py_hash_t mathutils_array_hash(const float *array, size_t array_len)
70{
71 int i;
72 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
73 Py_hash_t y;
74 Py_uhash_t mult;
75 Py_ssize_t len;
76
77 mult = _PyHASH_MULTIPLIER;
78 len = array_len;
79 x = 0x345678UL;
80 i = 0;
81 while (--len >= 0) {
82 y = _Py_HashDouble(nullptr, double(array[i++]));
83 if (y == -1) {
84 return -1;
85 }
86 x = (x ^ y) * mult;
87 /* the cast might truncate len; that doesn't change hash stability */
88 mult += Py_hash_t(82520UL + len + len);
89 }
90 x += 97531UL;
91 if (x == Py_uhash_t(-1)) {
92 x = -2;
93 }
94 return x;
95}
96
98 float *array, int array_num_min, int array_num_max, PyObject *value, const char *error_prefix)
99{
100 const uint flag = array_num_max;
101 int num;
102
103 array_num_max &= ~MU_ARRAY_FLAGS;
104
105#if 1 /* approx 6x speedup for mathutils types */
106
107 if ((num = VectorObject_Check(value) ? (reinterpret_cast<VectorObject *>(value))->vec_num : 0) ||
108 (num = EulerObject_Check(value) ? 3 : 0) || (num = QuaternionObject_Check(value) ? 4 : 0) ||
109 (num = ColorObject_Check(value) ? 3 : 0))
110 {
111 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
112 return -1;
113 }
114
115 if (flag & MU_ARRAY_SPILL) {
116 CLAMP_MAX(num, array_num_max);
117 }
118
119 if (num > array_num_max || num < array_num_min) {
120 if (array_num_max == array_num_min) {
121 PyErr_Format(PyExc_ValueError,
122 "%.200s: sequence length is %d, expected %d",
123 error_prefix,
124 num,
125 array_num_max);
126 }
127 else {
128 PyErr_Format(PyExc_ValueError,
129 "%.200s: sequence length is %d, expected [%d - %d]",
130 error_prefix,
131 num,
132 array_num_min,
133 array_num_max);
134 }
135 return -1;
136 }
137
138 memcpy(array, (reinterpret_cast<const BaseMathObject *>(value))->data, num * sizeof(float));
139 }
140 else
141#endif
142 {
143 PyObject *value_fast = nullptr;
144
145 /* non list/tuple cases */
146 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
147 /* PySequence_Fast sets the error */
148 return -1;
149 }
150
151 num = PySequence_Fast_GET_SIZE(value_fast);
152
153 if (flag & MU_ARRAY_SPILL) {
154 CLAMP_MAX(num, array_num_max);
155 }
156
157 if (num > array_num_max || num < array_num_min) {
158 if (array_num_max == array_num_min) {
159 PyErr_Format(PyExc_ValueError,
160 "%.200s: sequence length is %d, expected %d",
161 error_prefix,
162 num,
163 array_num_max);
164 }
165 else {
166 PyErr_Format(PyExc_ValueError,
167 "%.200s: sequence length is %d, expected [%d - %d]",
168 error_prefix,
169 num,
170 array_num_min,
171 array_num_max);
172 }
173 Py_DECREF(value_fast);
174 return -1;
175 }
176
177 if (num != 0) {
178 num = mathutils_array_parse_fast(array, num, value_fast, error_prefix);
179 }
180 Py_DECREF(value_fast);
181 }
182
183 if (num != -1) {
184 if (flag & MU_ARRAY_ZERO) {
185 const int array_num_left = array_num_max - num;
186 if (array_num_left) {
187 memset(&array[num], 0, sizeof(float) * array_num_left);
188 }
189 }
190 }
191
192 return num;
193}
194
196 int array_num_min,
197 PyObject *value,
198 const char *error_prefix)
199{
200 int num;
201
202#if 1 /* approx 6x speedup for mathutils types */
203
204 if ((num = VectorObject_Check(value) ? (reinterpret_cast<VectorObject *>(value))->vec_num : 0) ||
205 (num = EulerObject_Check(value) ? 3 : 0) || (num = QuaternionObject_Check(value) ? 4 : 0) ||
206 (num = ColorObject_Check(value) ? 3 : 0))
207 {
208 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
209 return -1;
210 }
211
212 if (num < array_num_min) {
213 PyErr_Format(PyExc_ValueError,
214 "%.200s: sequence size is %d, expected >= %d",
215 error_prefix,
216 num,
217 array_num_min);
218 return -1;
219 }
220
221 *array = static_cast<float *>(PyMem_Malloc(num * sizeof(float)));
222 memcpy(*array, (reinterpret_cast<const BaseMathObject *>(value))->data, num * sizeof(float));
223 return num;
224 }
225
226#endif
227
228 PyObject *value_fast = nullptr;
229 // *array = nullptr;
230 int ret;
231
232 /* non list/tuple cases */
233 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
234 /* PySequence_Fast sets the error */
235 return -1;
236 }
237
238 num = PySequence_Fast_GET_SIZE(value_fast);
239
240 if (num < array_num_min) {
241 Py_DECREF(value_fast);
242 PyErr_Format(PyExc_ValueError,
243 "%.200s: sequence size is %d, expected >= %d",
244 error_prefix,
245 num,
246 array_num_min);
247 return -1;
248 }
249
250 *array = static_cast<float *>(PyMem_Malloc(num * sizeof(float)));
251
252 ret = (num != 0) ? mathutils_array_parse_fast(*array, num, value_fast, error_prefix) : 0;
253 Py_DECREF(value_fast);
254
255 if (ret == -1) {
256 PyMem_Free(*array);
257 }
258
259 return ret;
260}
261
263 int array_dim,
264 PyObject *value,
265 const char *error_prefix)
266{
267 PyObject *value_fast;
268 const int array_dim_flag = array_dim;
269 int i, num;
270
271 *array = nullptr;
272
273 /* non list/tuple cases */
274 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
275 /* PySequence_Fast sets the error */
276 return -1;
277 }
278
279 num = PySequence_Fast_GET_SIZE(value_fast);
280
281 if (num != 0) {
282 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
283 float *fp;
284
285 array_dim &= ~MU_ARRAY_FLAGS;
286
287 fp = *array = static_cast<float *>(PyMem_Malloc(num * array_dim * sizeof(float)));
288
289 for (i = 0; i < num; i++, fp += array_dim) {
290 PyObject *item = value_fast_items[i];
291
292 if (mathutils_array_parse(fp, array_dim, array_dim_flag, item, error_prefix) == -1) {
293 PyMem_Free(*array);
294 *array = nullptr;
295 num = -1;
296 break;
297 }
298 }
299 }
300
301 Py_DECREF(value_fast);
302 return num;
303}
304
305int mathutils_int_array_parse(int *array, int array_dim, PyObject *value, const char *error_prefix)
306{
307 int size, i;
308 PyObject *value_fast, **value_fast_items, *item;
309
310 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
311 /* PySequence_Fast sets the error */
312 return -1;
313 }
314
315 if ((size = PySequence_Fast_GET_SIZE(value_fast)) != array_dim) {
316 PyErr_Format(PyExc_ValueError,
317 "%.200s: sequence size is %d, expected %d",
318 error_prefix,
319 size,
320 array_dim);
321 Py_DECREF(value_fast);
322 return -1;
323 }
324
325 value_fast_items = PySequence_Fast_ITEMS(value_fast);
326 i = size;
327 while (i > 0) {
328 i--;
329 if (((array[i] = PyC_Long_AsI32(item = value_fast_items[i])) == -1) && PyErr_Occurred()) {
330 PyErr_Format(PyExc_TypeError, "%.200s: sequence index %d expected an int", error_prefix, i);
331 size = -1;
332 break;
333 }
334 }
335 Py_DECREF(value_fast);
336
337 return size;
338}
339
341 int array_dim,
342 PyObject *value,
343 const char *error_prefix)
344{
345 PyObject *value_fast;
346 int i, size;
347
348 *array = nullptr;
349
350 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
351 /* PySequence_Fast sets the error */
352 return -1;
353 }
354
355 size = PySequence_Fast_GET_SIZE(value_fast);
356
357 if (size != 0) {
358 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
359 int *ip;
360
361 ip = *array = static_cast<int *>(PyMem_Malloc(size * array_dim * sizeof(int)));
362
363 for (i = 0; i < size; i++, ip += array_dim) {
364 PyObject *item = value_fast_items[i];
365
366 if (mathutils_int_array_parse(ip, array_dim, item, error_prefix) == -1) {
367 PyMem_Free(*array);
368 *array = nullptr;
369 size = -1;
370 break;
371 }
372 }
373 }
374
375 Py_DECREF(value_fast);
376 return size;
377}
378
380 const char *error_prefix,
381 Array<int> &r_offsets,
382 Array<int> &r_data)
383{
384 PyObject *value_fast;
385 if (!(value_fast = PySequence_Fast(value, error_prefix))) {
386 /* PySequence_Fast sets the error */
387 return false;
388 }
389
390 const int size = PySequence_Fast_GET_SIZE(value_fast);
391 if (size != 0) {
392 PyObject **value_fast_items = PySequence_Fast_ITEMS(value_fast);
393 r_offsets.reinitialize(size + 1);
394
395 int count = 0;
396 for (int i = 0; i < size; i++) {
397 r_offsets[i] = count;
398 const int subseq_len = int(PySequence_Size(value_fast_items[i]));
399 if (subseq_len == -1) {
400 PyErr_Format(
401 PyExc_ValueError, "%.200s: sequence expected to have subsequences", error_prefix);
402 Py_DECREF(value_fast);
403 return false;
404 }
405 count += int(PySequence_Size(value_fast_items[i]));
406 }
407 r_offsets.last() = count;
408 const OffsetIndices<int> offsets(r_offsets);
409
410 r_data.reinitialize(offsets.total_size());
411
412 for (const int64_t i : offsets.index_range()) {
413 PyObject *subseq = value_fast_items[i];
414 MutableSpan<int> group = r_data.as_mutable_span().slice(offsets[i]);
415 if (mathutils_int_array_parse(group.data(), group.size(), subseq, error_prefix) == -1) {
416 Py_DECREF(value_fast);
417 return false;
418 }
419 }
420 }
421
422 Py_DECREF(value_fast);
423 return true;
424}
425
426int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
427{
428 if (EulerObject_Check(value)) {
429 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
430 return -1;
431 }
432
433 eulO_to_mat3(rmat,
434 (reinterpret_cast<const EulerObject *>(value))->eul,
435 (reinterpret_cast<const EulerObject *>(value))->order);
436 return 0;
437 }
438 if (QuaternionObject_Check(value)) {
439 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
440 return -1;
441 }
442
443 float tquat[4];
444 normalize_qt_qt(tquat, (reinterpret_cast<const QuaternionObject *>(value))->quat);
445 quat_to_mat3(rmat, tquat);
446 return 0;
447 }
448 if (MatrixObject_Check(value)) {
449 if (BaseMath_ReadCallback((BaseMathObject *)value) == -1) {
450 return -1;
451 }
452 if ((reinterpret_cast<MatrixObject *>(value))->row_num < 3 ||
453 (reinterpret_cast<MatrixObject *>(value))->col_num < 3)
454 {
455 PyErr_Format(
456 PyExc_ValueError, "%.200s: matrix must have minimum 3x3 dimensions", error_prefix);
457 return -1;
458 }
459
460 matrix_as_3x3(rmat, reinterpret_cast<MatrixObject *>(value));
461 normalize_m3(rmat);
462 return 0;
463 }
464
465 PyErr_Format(PyExc_TypeError,
466 "%.200s: expected a Euler, Quaternion or Matrix type, "
467 "found %.200s",
468 error_prefix,
469 Py_TYPE(value)->tp_name);
470 return -1;
471}
472
473/* ----------------------------------MATRIX FUNCTIONS-------------------- */
474
475/* Utility functions */
476
477/* LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon */
478/* XXX We may want to use 'safer' BLI's compare_ff_relative ultimately?
479 * LomontRRDCompare4() is an optimized version of Dawson's AlmostEqual2sComplement()
480 * (see [1] and [2]).
481 * Dawson himself now claims this is not a 'safe' thing to do
482 * (pushing ULP method beyond its limits),
483 * an recommends using work from [3] instead, which is done in BLI func...
484 *
485 * [1] http://www.randydillon.org/Papers/2007/everfast.htm
486 * [2] http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
487 * [3] https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
488 * instead.
489 */
490#define SIGNMASK(i) (-int((uint(i)) >> 31))
491
492int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
493{
494 /* solid, fast routine across all platforms
495 * with constant time behavior */
496 const int ai = *reinterpret_cast<const int *>(&af);
497 const int bi = *reinterpret_cast<const int *>(&bf);
498 const int test = SIGNMASK(ai ^ bi);
499 int diff, v1, v2;
500
501 BLI_assert((0 == test) || (0xFFFFFFFF == test));
502 diff = (ai ^ (test & 0x7fffffff)) - bi;
503 v1 = maxDiff + diff;
504 v2 = maxDiff - diff;
505 return (v1 | v2) >= 0;
506}
507
508/*---------------------- EXPP_VectorsAreEqual -------------------------
509 * Builds on EXPP_FloatsAreEqual to test vectors */
510
511int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int floatSteps)
512{
513 int x;
514 for (x = 0; x < size; x++) {
515 if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0) {
516 return 0;
517 }
518 }
519 return 1;
520}
521
522#ifndef MATH_STANDALONE
524{
525 const int ds_len = BLI_dynstr_get_len(ds); /* space for \0 */
526 char *ds_buf = static_cast<char *>(PyMem_Malloc(ds_len + 1));
527 PyObject *ret;
528 BLI_dynstr_get_cstring_ex(ds, ds_buf);
529 BLI_dynstr_free(ds);
530 ret = PyUnicode_FromStringAndSize(ds_buf, ds_len);
531 PyMem_Free(ds_buf);
532 return ret;
533}
534#endif
535
536/* Mathutils Callbacks */
537
538/* For mathutils internal use only,
539 * eventually should re-alloc but to start with we only have a few users. */
540#define MATHUTILS_TOT_CB 17
542
544{
545 uchar i;
546
547 /* find the first free slot */
548 for (i = 0; mathutils_callbacks[i]; i++) {
549 if (mathutils_callbacks[i] == cb) {
550 /* already registered? */
551 return i;
552 }
553 }
554
556
557 mathutils_callbacks[i] = cb;
558 return i;
559}
560
562{
563 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
564 if (cb->check(self) != -1) [[likely]] {
565 return 0;
566 }
567 return -1;
568}
569
571{
572 /* NOTE: use macros to check for nullptr. */
573
574 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
575 if (cb->get(self, self->cb_subtype) != -1) [[likely]] {
576 return 0;
577 }
578
579 if (!PyErr_Occurred()) {
580 PyErr_Format(PyExc_RuntimeError, "%s read, user has become invalid", Py_TYPE(self)->tp_name);
581 }
582 return -1;
583}
584
586{
587 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
588 if (cb->set(self, self->cb_subtype) != -1) [[likely]] {
589 return 0;
590 }
591
592 if (!PyErr_Occurred()) {
593 PyErr_Format(PyExc_RuntimeError, "%s write, user has become invalid", Py_TYPE(self)->tp_name);
594 }
595 return -1;
596}
597
599{
600 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
601 if (cb->get_index(self, self->cb_subtype, index) != -1) [[likely]] {
602 return 0;
603 }
604
605 if (!PyErr_Occurred()) {
606 PyErr_Format(
607 PyExc_RuntimeError, "%s read index, user has become invalid", Py_TYPE(self)->tp_name);
608 }
609 return -1;
610}
611
613{
614 Mathutils_Callback *cb = mathutils_callbacks[self->cb_type];
615 if (cb->set_index(self, self->cb_subtype, index) != -1) [[likely]] {
616 return 0;
617 }
618
619 if (!PyErr_Occurred()) {
620 PyErr_Format(
621 PyExc_RuntimeError, "%s write index, user has become invalid", Py_TYPE(self)->tp_name);
622 }
623 return -1;
624}
625
627{
628 PyErr_Format(PyExc_TypeError, "%s is frozen (immutable)", Py_TYPE(self)->tp_name);
629}
630
632{
633 PyErr_Format(
634 PyExc_TypeError, "%s is not frozen (mutable), call freeze first", Py_TYPE(self)->tp_name);
635}
636
637int _BaseMathObject_ResizeOkOrRaiseExc(BaseMathObject *self, const char *error_prefix)
638{
639 if (self->flag & BASE_MATH_FLAG_IS_FROZEN) [[unlikely]] {
640 PyErr_Format(PyExc_ValueError, "%s: cannot resize frozen data", error_prefix);
641 return -1;
642 }
643 if (self->flag & BASE_MATH_FLAG_IS_WRAP) [[unlikely]] {
644 PyErr_Format(PyExc_ValueError, "%s: cannot resize wrapped data", error_prefix);
645 return -1;
646 }
647 if (self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW) [[unlikely]] {
648 PyErr_Format(PyExc_BufferError,
649 "%s: cannot resize data while exported to buffer protocol",
650 error_prefix);
651 return -1;
652 }
653 if (self->cb_user) [[unlikely]] {
654 PyErr_Format(PyExc_ValueError, "%s: cannot resize owned data", error_prefix);
655 return -1;
656 }
657 return 0;
658}
659
660int _BaseMathObject_RaiseBufferViewExc(BaseMathObject *self, Py_buffer *view, int flags)
661{
662 if (view == nullptr) [[unlikely]] {
663 PyErr_SetString(PyExc_BufferError, "null view in get-buffer is obsolete");
664 return -1;
665 }
666 if (self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW) [[unlikely]] {
667 PyErr_SetString(PyExc_BufferError,
668 "Data is already exported via buffer protocol, "
669 "multiple simultaneous exports are not allowed.");
670 return -1;
671 }
672 if (flags & PyBUF_WRITABLE) {
673 if (BaseMath_WriteCallback(self) == -1) [[unlikely]] {
674 return -1;
675 }
676 if (self->flag & BASE_MATH_FLAG_IS_FROZEN) [[unlikely]] {
677 PyErr_SetString(PyExc_BufferError, "Data is frozen, cannot get a writable buffer");
678 return -1;
679 }
680 }
681 return 0;
682}
683
684/* #BaseMathObject generic functions for all mathutils types. */
685
687 "The item this is wrapping or None (read-only).\n"
688 "\n"
689 ":type: Any";
690PyObject *BaseMathObject_owner_get(BaseMathObject *self, void * /*closure*/)
691{
692 PyObject *ret = self->cb_user ? self->cb_user : Py_None;
693 return Py_NewRef(ret);
694}
695
697 "True when this object wraps external data (read-only).\n\n:type: bool";
698PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void * /*closure*/)
699{
700 return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_WRAP) != 0);
701}
702
704 "True when this object has been frozen (read-only).\n\n:type: bool";
705PyObject *BaseMathObject_is_frozen_get(BaseMathObject *self, void * /*closure*/)
706{
707 return PyBool_FromLong((self->flag & BASE_MATH_FLAG_IS_FROZEN) != 0);
708}
709
710char BaseMathObject_is_valid_doc[] = "True when the owner of this data is valid.\n\n:type: bool";
711PyObject *BaseMathObject_is_valid_get(BaseMathObject *self, void * /*closure*/)
712{
713 return PyBool_FromLong(BaseMath_CheckCallback(self) == 0);
714}
715
717 ".. method:: freeze()\n"
718 "\n"
719 " Make this object immutable.\n"
720 "\n"
721 " After this the object can be hashed, used in dictionaries & sets.\n"
722 "\n"
723 " :return: An instance of this object.\n"
724 " :rtype: Self\n";
726{
727 if ((self->flag & BASE_MATH_FLAG_IS_WRAP) || (self->cb_user != nullptr)) {
728 PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped/owned data");
729 return nullptr;
730 }
731
732 if (self->flag & BASE_MATH_FLAG_HAS_BUFFER_VIEW) {
733 PyErr_SetString(PyExc_BufferError, "Cannot freeze data while exported to buffer protocol");
734 return nullptr;
735 }
736
737 self->flag |= BASE_MATH_FLAG_IS_FROZEN;
738
739 return Py_NewRef(self);
740}
741
742int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
743{
744 Py_VISIT(self->cb_user);
745 return 0;
746}
747
749{
750 Py_CLEAR(self->cb_user);
751 return 0;
752}
753
755#ifndef NDEBUG
757{
758 PyObject *cb_user = self->cb_user;
759 self->cb_user = reinterpret_cast<PyObject *>(uintptr_t(-1));
760 bool is_tracked = PyObject_GC_IsTracked(reinterpret_cast<PyObject *>(self));
761 self->cb_user = cb_user;
762 return is_tracked;
763}
764#endif /* !NDEBUG */
765
767{
768 /* only free non wrapped */
769 if ((self->flag & BASE_MATH_FLAG_IS_WRAP) == 0) {
770 PyMem_Free(self->data);
771 }
772
773 if (self->cb_user) {
775 PyObject_GC_UnTrack(self);
777 }
778 else if (!BaseMathObject_CheckExact(self)) {
779 /* Subclassed types get an extra track (in Pythons internal `subtype_dealloc` function). */
781 PyObject_GC_UnTrack(self);
783 }
784
785 Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); /* breaks sub-types. */
786}
787
789{
790 return self->cb_user != nullptr;
791}
792
793PyObject *_BaseMathObject_new_impl(PyTypeObject *root_type, PyTypeObject *base_type)
794{
795 PyObject *obj;
796 if (ELEM(base_type, nullptr, root_type)) {
797 obj = _PyObject_GC_New(root_type);
798 if (obj) {
800 }
801 }
802 else {
803 /* Calls Generic allocation function which always tracks
804 * (because `root_type` is flagged for GC). */
805 obj = base_type->tp_alloc(base_type, 0);
806 if (obj) {
808 PyObject_GC_UnTrack(obj);
810 }
811 }
812
813 return obj;
814}
815
816/*----------------------------MODULE INIT-------------------------*/
817static PyMethodDef M_Mathutils_methods[] = {
818 {nullptr, nullptr, 0, nullptr},
819};
820
821static PyModuleDef M_Mathutils_module_def = {
822 /*m_base*/ PyModuleDef_HEAD_INIT,
823 /*m_name*/ "mathutils",
824 /*m_doc*/ M_Mathutils_doc,
825 /*m_size*/ 0,
826 /*m_methods*/ M_Mathutils_methods,
827 /*m_slots*/ nullptr,
828 /*m_traverse*/ nullptr,
829 /*m_clear*/ nullptr,
830 /*m_free*/ nullptr,
831};
832
833} // namespace blender
834
835/* submodules only */
836#include "mathutils_geometry.hh"
838#ifndef MATH_STANDALONE
839# include "mathutils_bvhtree.hh"
840# include "mathutils_kdtree.hh"
841# include "mathutils_noise.hh"
842#endif
843
844namespace blender {
845
846PyMODINIT_FUNC PyInit_mathutils()
847{
848 PyObject *mod;
849 PyObject *submodule;
850 PyObject *sys_modules = PyImport_GetModuleDict();
851
852 if (PyType_Ready(&vector_Type) < 0) {
853 return nullptr;
854 }
855 if (PyType_Ready(&matrix_Type) < 0) {
856 return nullptr;
857 }
858 if (PyType_Ready(&matrix_access_Type) < 0) {
859 return nullptr;
860 }
861 if (PyType_Ready(&euler_Type) < 0) {
862 return nullptr;
863 }
864 if (PyType_Ready(&quaternion_Type) < 0) {
865 return nullptr;
866 }
867 if (PyType_Ready(&color_Type) < 0) {
868 return nullptr;
869 }
870
871 mod = PyModule_Create(&M_Mathutils_module_def);
872
873 /* each type has its own new() function */
874 PyModule_AddType(mod, &vector_Type);
875 PyModule_AddType(mod, &matrix_Type);
876 PyModule_AddType(mod, &matrix_access_Type);
877 PyModule_AddType(mod, &euler_Type);
878 PyModule_AddType(mod, &quaternion_Type);
879 PyModule_AddType(mod, &color_Type);
880
881 /* submodule */
882 PyModule_AddObject(mod, "geometry", (submodule = PyInit_mathutils_geometry()));
883 /* XXX, python doesn't do imports with this usefully yet
884 * 'from mathutils.geometry import PolyFill'
885 * ...fails without this. */
886 PyC_Module_AddToSysModules(sys_modules, submodule);
887
888 PyModule_AddObject(mod, "interpolate", (submodule = PyInit_mathutils_interpolate()));
889 /* XXX, python doesn't do imports with this usefully yet
890 * 'from mathutils.geometry import PolyFill'
891 * ...fails without this. */
892 PyC_Module_AddToSysModules(sys_modules, submodule);
893
894#ifndef MATH_STANDALONE
895 /* Noise submodule */
896 PyModule_AddObject(mod, "noise", (submodule = PyInit_mathutils_noise()));
897 PyC_Module_AddToSysModules(sys_modules, submodule);
898
899 /* BVHTree submodule */
900 PyModule_AddObject(mod, "bvhtree", (submodule = PyInit_mathutils_bvhtree()));
901 PyC_Module_AddToSysModules(sys_modules, submodule);
902
903 /* KDTree<float3> submodule */
904 PyModule_AddObject(mod, "kdtree", (submodule = PyInit_mathutils_kdtree()));
905 PyC_Module_AddToSysModules(sys_modules, submodule);
906#endif
907
912
913 return mod;
914}
915
916} // namespace blender
A dynamically sized string ADT.
#define CLAMP_MAX(a, c)
#define ELEM(...)
SIMD_FORCE_INLINE void mult(const btTransform &t1, const btTransform &t2)
Set the current transform as the value of the product of two transforms.
Definition btTransform.h:76
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
const T & last(const int64_t n=0) const
Definition BLI_array.hh:307
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr T * data() const
Definition BLI_span.hh:545
IMETHOD Vector diff(const Vector &a, const Vector &b, double dt)
Definition frames.inl:1166
VecBase< float, D > constexpr mod(VecOp< float, D >, VecOp< float, D >) RET
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
#define SIGNMASK(i)
Definition mathutils.cc:490
#define MATHUTILS_TOT_CB
Definition mathutils.cc:540
#define BaseMath_CheckCallback(_self)
Definition mathutils.hh:145
#define MU_ARRAY_ZERO
Definition mathutils.hh:261
#define BaseMath_WriteCallback(_self)
Definition mathutils.hh:149
#define MU_ARRAY_FLAGS
Definition mathutils.hh:268
#define MU_ARRAY_SPILL
Definition mathutils.hh:266
#define BaseMath_ReadCallback(_self)
Definition mathutils.hh:147
#define BaseMathObject_CheckExact(v)
Definition mathutils.hh:85
#define ColorObject_Check(v)
#define EulerObject_Check(v)
#define MatrixObject_Check(v)
#define QuaternionObject_Check(v)
#define VectorObject_Check(v)
BMesh Iterators.
int _BaseMathObject_ResizeOkOrRaiseExc(BaseMathObject *self, const char *error_prefix)
Definition mathutils.cc:637
char BaseMathObject_owner_doc[]
Definition mathutils.cc:686
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
char BaseMathObject_freeze_doc[]
Definition mathutils.cc:716
int EXPP_VectorsAreEqual(const float *vecA, const float *vecB, int size, int floatSteps)
Definition mathutils.cc:511
__int64 int64_t
Definition BKE_text.h:90
static bool BaseMathObject_is_tracked(BaseMathObject *self)
Definition mathutils.cc:756
void BaseMathObject_dealloc(BaseMathObject *self)
Definition mathutils.cc:766
unsigned int uint
Definition BKE_text.h:55
PyMODINIT_FUNC PyInit_mathutils_noise()
bool mathutils_array_parse_alloc_viseq(PyObject *value, const char *error_prefix, Array< int > &r_offsets, Array< int > &r_data)
Definition mathutils.cc:379
Py_hash_t mathutils_array_hash(const float *array, size_t array_len)
Definition mathutils.cc:69
PyObject * mathutils_dynstr_to_py(DynStr *ds)
Definition mathutils.cc:523
uchar mathutils_matrix_col_cb_index
uchar mathutils_matrix_row_cb_index
void normalize_m3(float R[3][3]) ATTR_NONNULL()
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param 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")
PyObject * BaseMathObject_owner_get(BaseMathObject *self, void *)
Definition mathutils.cc:690
PyTypeObject quaternion_Type
PyTypeObject euler_Type
PyTypeObject matrix_access_Type
static Mathutils_Callback * mathutils_callbacks[MATHUTILS_TOT_CB]
Definition mathutils.cc:541
int BaseMathObject_clear(BaseMathObject *self)
Definition mathutils.cc:748
PyObject * BaseMathObject_freeze(BaseMathObject *self)
Definition mathutils.cc:725
void BLI_dynstr_free(DynStr *ds) ATTR_NONNULL()
int mathutils_array_parse_alloc_vi(int **array, int array_dim, PyObject *value, const char *error_prefix)
Definition mathutils.cc:340
Mathutils_Callback mathutils_matrix_col_cb
int BaseMathObject_is_gc(BaseMathObject *self)
Definition mathutils.cc:788
int mathutils_array_parse_alloc(float **array, int array_num_min, PyObject *value, const char *error_prefix)
Definition mathutils.cc:195
void eulO_to_mat3(float M[3][3], const float e[3], short order)
void quat_to_mat3(float m[3][3], const float q[4])
PyObject * BaseMathObject_is_frozen_get(BaseMathObject *self, void *)
Definition mathutils.cc:705
static int mathutils_array_parse_fast(float *array, const int array_num, PyObject *value_fast, const char *error_prefix)
Definition mathutils.cc:44
static PyModuleDef M_Mathutils_module_def
Definition mathutils.cc:821
void _BaseMathObject_RaiseNotFrozenExc(const BaseMathObject *self)
Definition mathutils.cc:631
PyObject * BaseMathObject_is_valid_get(BaseMathObject *self, void *)
Definition mathutils.cc:711
void matrix_as_3x3(float mat[3][3], MatrixObject *self)
PyMODINIT_FUNC PyInit_mathutils()
Definition mathutils.cc:846
unsigned char uchar
Definition BKE_text.h:58
PyMODINIT_FUNC PyInit_mathutils_interpolate()
Mathutils_Callback mathutils_matrix_row_cb
BMesh const char void * data
PyObject * _BaseMathObject_new_impl(PyTypeObject *root_type, PyTypeObject *base_type)
Definition mathutils.cc:793
int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
Definition mathutils.cc:492
@ BASE_MATH_FLAG_IS_WRAP
Definition mathutils.hh:39
@ BASE_MATH_FLAG_IS_FROZEN
Definition mathutils.hh:44
@ BASE_MATH_FLAG_HAS_BUFFER_VIEW
Definition mathutils.hh:52
int mathutils_array_parse(float *array, int array_num_min, int array_num_max, PyObject *value, const char *error_prefix)
Definition mathutils.cc:97
PyMODINIT_FUNC PyInit_mathutils_bvhtree()
uchar Mathutils_RegisterCallback(Mathutils_Callback *cb)
Definition mathutils.cc:543
ATTR_WARN_UNUSED_RESULT const size_t num
PyTypeObject color_Type
int _BaseMathObject_WriteCallback(BaseMathObject *self)
Definition mathutils.cc:585
int _BaseMathObject_ReadCallback(BaseMathObject *self)
Definition mathutils.cc:570
_W64 unsigned int uintptr_t
Definition BKE_text.h:120
PyTypeObject matrix_Type
PyObject * BaseMathObject_is_wrapped_get(BaseMathObject *self, void *)
Definition mathutils.cc:698
char BaseMathObject_is_valid_doc[]
Definition mathutils.cc:710
Mathutils_Callback mathutils_matrix_translation_cb
ATTR_WARN_UNUSED_RESULT const BMVert * v2
int BaseMathObject_traverse(BaseMathObject *self, visitproc visit, void *arg)
Definition mathutils.cc:742
int mathutils_any_to_rotmat(float rmat[3][3], PyObject *value, const char *error_prefix)
Definition mathutils.cc:426
int PyC_Module_AddToSysModules(PyObject *sys_modules, PyObject *module)
PyMODINIT_FUNC PyInit_mathutils_kdtree()
uchar mathutils_matrix_translation_cb_index
char BaseMathObject_is_frozen_doc[]
Definition mathutils.cc:703
PyMODINIT_FUNC PyInit_mathutils_geometry()
static PyMethodDef M_Mathutils_methods[]
Definition mathutils.cc:817
void BLI_dynstr_get_cstring_ex(const DynStr *__restrict ds, char *__restrict rets) ATTR_NONNULL()
int mathutils_int_array_parse(int *array, int array_dim, PyObject *value, const char *error_prefix)
Definition mathutils.cc:305
void _BaseMathObject_RaiseFrozenExc(const BaseMathObject *self)
Definition mathutils.cc:626
int BLI_dynstr_get_len(const DynStr *ds) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
Definition mathutils.cc:612
int _BaseMathObject_RaiseBufferViewExc(BaseMathObject *self, Py_buffer *view, int flags)
Definition mathutils.cc:660
int mathutils_array_parse_alloc_v(float **array, int array_dim, PyObject *value, const char *error_prefix)
Definition mathutils.cc:262
PyTypeObject vector_Type
int _BaseMathObject_CheckCallback(BaseMathObject *self)
Definition mathutils.cc:561
char BaseMathObject_is_wrapped_doc[]
Definition mathutils.cc:696
int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
Definition mathutils.cc:598
float normalize_qt_qt(float r[4], const float q[4])
BaseMathCheckFunc check
Definition mathutils.hh:120
BaseMathGetIndexFunc get_index
Definition mathutils.hh:123
BaseMathSetIndexFunc set_index
Definition mathutils.hh:124