-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathmath.c
4445 lines (3999 loc) · 132 KB
/
math.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
pygame-ce - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* Adjust gcc 4.4 optimization for floating point on x86-32 PCs running Linux.
* This addresses bug 67:
* https://github.com/pygame-community/pygame-ce/issues/67
* With this option, floats have consistent precision regardless of optimize
* level.
*/
#if defined(__GNUC__) && defined(__linux__) && defined(__i386__) && \
__SIZEOF_POINTER__ == 4 && \
((__GNUC__ == 4 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
#pragma GCC optimize("float-store")
#endif
#define PYGAMEAPI_MATH_INTERNAL
#define NO_PYGAME_C_API
#include "doc/math_doc.h"
#include "pygame.h"
#include "structmember.h"
#include "pgcompat.h"
#include <float.h>
#include <math.h>
#include <stddef.h>
#include <string.h>
/* on some windows platforms math.h doesn't define M_PI */
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define TWO_PI (2. * M_PI)
#ifndef M_PI_2
#define M_PI_2 (M_PI / 2.0)
#endif /* M_PI_2 */
#define VECTOR_EPSILON (1e-6)
#define VECTOR_MAX_SIZE (3)
#define STRING_BUF_SIZE_REPR (110)
#define STRING_BUF_SIZE_STR (103)
#define SWIZZLE_ERR_NO_ERR 0
#define SWIZZLE_ERR_DOUBLE_IDX 1
#define SWIZZLE_ERR_EXTRACTION_ERR 2
#define OP_ADD 1
/* #define OP_IADD 2 */
#define OP_SUB 3
/* #define OP_ISUB 4 */
#define OP_MUL 5
/* #define OP_IMUL 6 */
#define OP_DIV 7
/* #define OP_IDIV 8 */
#define OP_FLOOR_DIV 9
/* #define OP_IFLOOR_DIV 10 */
#define OP_MOD 11
#define OP_INPLACE 16
#define OP_ARG_REVERSE 32
#define OP_ARG_UNKNOWN 64
#define OP_ARG_VECTOR 128
#define OP_ARG_NUMBER 256
static PyTypeObject pgVector2_Type;
static PyTypeObject pgVector3_Type;
static PyTypeObject pgVectorElementwiseProxy_Type;
static PyTypeObject pgVectorIter_Type;
#define pgVector2_Check(x) (PyType_IsSubtype(Py_TYPE(x), &pgVector2_Type))
#define pgVector3_Check(x) (PyType_IsSubtype(Py_TYPE(x), &pgVector3_Type))
#define pgVector_Check(x) (pgVector2_Check(x) || pgVector3_Check(x))
#define vector_elementwiseproxy_Check(x) \
(Py_TYPE(x) == &pgVectorElementwiseProxy_Type)
#define _vector_subtype_new(x) \
((pgVector *)(Py_TYPE(x)->tp_new(Py_TYPE(x), NULL, NULL)))
#define DEG2RAD(angle) ((angle) * M_PI / 180.)
#define RAD2DEG(angle) ((angle) * 180. / M_PI)
typedef struct {
PyObject_HEAD double coords[VECTOR_MAX_SIZE]; /* Coordinates */
Py_ssize_t dim; /* Dimension of the vector */
double epsilon; /* Small value for comparisons */
} pgVector;
typedef struct {
PyObject_HEAD long it_index;
pgVector *vec;
} vectoriter;
typedef struct {
PyObject_HEAD pgVector *vec;
} vector_elementwiseproxy;
/* further forward declarations */
/* math functions */
static PyObject *
math_clamp(PyObject *self, PyObject *const *args, Py_ssize_t nargs);
/* generic helper functions */
static int
RealNumber_Check(PyObject *obj);
static double
PySequence_GetItem_AsDouble(PyObject *seq, Py_ssize_t index);
static int
PySequence_AsVectorCoords(PyObject *seq, double *const coords,
const Py_ssize_t size);
static int
pgVectorCompatible_Check(PyObject *obj, Py_ssize_t dim);
static int
pg_VectorCoordsFromObj(PyObject *obj, Py_ssize_t dim, double *const coords);
static double
_scalar_product(const double *coords1, const double *coords2, Py_ssize_t size);
static int
get_double_from_unicode_slice(PyObject *unicode_obj, Py_ssize_t idx1,
Py_ssize_t idx2, double *val);
static Py_ssize_t
_vector_find_string_helper(PyObject *str_obj, const char *substr,
Py_ssize_t start, Py_ssize_t end);
static Py_ssize_t
_vector_coords_from_string(PyObject *str, char **delimiter, double *coords,
Py_ssize_t dim);
static void
_vector_move_towards_helper(Py_ssize_t dim, double *origin_coords,
double *target_coords, double max_distance);
/* generic vector functions */
static PyObject *
pgVector_NEW(Py_ssize_t dim);
static void
vector_dealloc(pgVector *self);
static PyObject *
vector_generic_math(PyObject *o1, PyObject *o2, int op);
static PyObject *
vector_add(PyObject *o1, PyObject *o2);
static PyObject *
vector_sub(PyObject *o1, PyObject *o2);
static PyObject *
vector_mul(PyObject *o1, PyObject *o2);
static PyObject *
vector_div(pgVector *self, PyObject *other);
static PyObject *
vector_floor_div(pgVector *self, PyObject *other);
static PyObject *
vector_inplace_add(pgVector *self, PyObject *other);
static PyObject *
vector_inplace_sub(pgVector *self, PyObject *other);
static PyObject *
vector_inplace_mul(pgVector *self, PyObject *other);
static PyObject *
vector_inplace_div(pgVector *self, PyObject *other);
static PyObject *
vector_inplace_floor_div(pgVector *self, PyObject *other);
static PyObject *
vector_neg(pgVector *self);
static PyObject *
vector_pos(pgVector *self);
static int
vector_nonzero(pgVector *self);
static Py_ssize_t
vector_len(pgVector *self);
static PyObject *
vector_GetItem(pgVector *self, Py_ssize_t index);
static int
vector_SetItem(pgVector *self, Py_ssize_t index, PyObject *value);
static int
vector_contains(pgVector *self, PyObject *arg);
static PyObject *
vector_GetSlice(pgVector *self, Py_ssize_t ilow, Py_ssize_t ihigh);
static int
vector_SetSlice(pgVector *self, Py_ssize_t ilow, Py_ssize_t ihigh,
PyObject *v);
static PyObject *
vector_getx(pgVector *self, void *closure);
static PyObject *
vector_gety(pgVector *self, void *closure);
static PyObject *
vector_getz(pgVector *self, void *closure);
#ifdef PYGAME_MATH_VECTOR_HAVE_W
static PyObject *
vector_getw(pgVector *self, void *closure);
#endif
static int
vector_setx(pgVector *self, PyObject *value, void *closure);
static int
vector_sety(pgVector *self, PyObject *value, void *closure);
static int
vector_setz(pgVector *self, PyObject *value, void *closure);
#ifdef PYGAME_MATH_VECTOR_HAVE_W
static int
vector_setw(pgVector *self, PyObject *value, void *closure);
#endif
static PyObject *
vector_richcompare(PyObject *o1, PyObject *o2, int op);
static PyObject *
vector_length(pgVector *self, PyObject *args);
static PyObject *
vector_length_squared(pgVector *self, PyObject *args);
static PyObject *
vector_normalize(pgVector *self, PyObject *args);
static PyObject *
vector_normalize_ip(pgVector *self, PyObject *args);
static PyObject *
vector_dot(pgVector *self, PyObject *other);
static PyObject *
vector_scale_to_length(pgVector *self, PyObject *length);
static PyObject *
vector_move_towards(pgVector *self, PyObject *args);
static PyObject *
vector_move_towards_ip(pgVector *self, PyObject *args);
static PyObject *
vector_slerp(pgVector *self, PyObject *args);
static PyObject *
vector_lerp(pgVector *self, PyObject *args);
static PyObject *
vector_smoothstep(pgVector *self, PyObject *args);
static int
_vector_reflect_helper(double *dst_coords, const double *src_coords,
PyObject *normal, Py_ssize_t dim, double epsilon);
static PyObject *
vector_reflect(pgVector *self, PyObject *normal);
static PyObject *
vector_reflect_ip(pgVector *self, PyObject *normal);
static double
_vector_distance_helper(pgVector *self, PyObject *other);
static PyObject *
vector_distance_to(pgVector *self, PyObject *other);
static PyObject *
vector_distance_squared_to(pgVector *self, PyObject *other);
static PyObject *
vector_getAttr_swizzle(pgVector *self, PyObject *attr_name);
static int
vector_setAttr_swizzle(pgVector *self, PyObject *attr_name, PyObject *val);
static PyObject *
vector_elementwise(pgVector *self, PyObject *args);
static int
_vector_check_snprintf_success(int return_code, int max_size);
static PyObject *
vector_repr(pgVector *self);
static PyObject *
vector_str(pgVector *self);
static PyObject *
vector_project_onto(pgVector *self, PyObject *other);
static PyObject *
vector_copy(pgVector *self, PyObject *_null);
static PyObject *
vector_clamp_magnitude(pgVector *self, PyObject *const *args,
Py_ssize_t nargs);
static PyObject *
vector_clamp_magnitude_ip(pgVector *self, PyObject *const *args,
Py_ssize_t nargs);
static PyObject *
vector___round__(pgVector *self, PyObject *args);
/*
static Py_ssize_t vector_readbuffer(pgVector *self, Py_ssize_t segment, void
**ptrptr); static Py_ssize_t vector_writebuffer(pgVector *self, Py_ssize_t
segment, void **ptrptr); static Py_ssize_t vector_segcount(pgVector *self,
Py_ssize_t *lenp);
*/
/* vector2 specific functions */
static PyObject *
vector2_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
vector2_init(pgVector *self, PyObject *args, PyObject *kwds);
static int
_vector2_rotate_helper(double *dst_coords, const double *src_coords,
double angle, double epsilon);
static PyObject *
vector2_rotate(pgVector *self, PyObject *args);
static PyObject *
vector2_rotate_ip(pgVector *self, PyObject *args);
static PyObject *
vector2_cross(pgVector *self, PyObject *other);
static PyObject *
vector2_angle_to(pgVector *self, PyObject *other);
static PyObject *
vector2_as_polar(pgVector *self, PyObject *args);
static PyObject *
vector2_from_polar(pgVector *self, PyObject *args);
/* vector3 specific functions */
static PyObject *
vector3_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
vector3_init(pgVector *self, PyObject *args, PyObject *kwds);
static int
_vector3_rotate_helper(double *dst_coords, const double *src_coords,
const double *axis_coords, double angle,
double epsilon);
static PyObject *
vector3_rotate(pgVector *self, PyObject *args);
static PyObject *
vector3_rotate_ip(pgVector *self, PyObject *args);
static PyObject *
vector3_cross(pgVector *self, PyObject *other);
static PyObject *
vector3_angle_to(pgVector *self, PyObject *other);
static PyObject *
vector3_as_spherical(pgVector *self, PyObject *args);
static PyObject *
vector3_from_spherical(pgVector *self, PyObject *args);
/* vector iterator functions */
static void
vectoriter_dealloc(vectoriter *it);
static PyObject *
vectoriter_next(vectoriter *it);
static PyObject *
vectoriter_len(vectoriter *it, PyObject *_null);
static PyObject *
vector_iter(PyObject *vec);
/* elementwiseproxy */
static void
vector_elementwiseproxy_dealloc(vector_elementwiseproxy *it);
static PyObject *
vector_elementwiseproxy_richcompare(PyObject *o1, PyObject *o2, int op);
static PyObject *
vector_elementwiseproxy_generic_math(PyObject *o1, PyObject *o2, int op);
static PyObject *
vector_elementwiseproxy_add(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_sub(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_mul(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_div(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_floor_div(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_pow(PyObject *baseObj, PyObject *expoObj,
PyObject *mod);
static PyObject *
vector_elementwiseproxy_mod(PyObject *o1, PyObject *o2);
static PyObject *
vector_elementwiseproxy_abs(vector_elementwiseproxy *self);
static PyObject *
vector_elementwiseproxy_neg(vector_elementwiseproxy *self);
static PyObject *
vector_elementwiseproxy_pos(vector_elementwiseproxy *self);
static int
vector_elementwiseproxy_nonzero(vector_elementwiseproxy *self);
static PyObject *
vector_elementwise(pgVector *vec, PyObject *args);
/********************************
* Global helper functions
********************************/
static int
RealNumber_Check(PyObject *obj)
{
if (obj && PyNumber_Check(obj) && !PyComplex_Check(obj))
return 1;
return 0;
}
static double
PySequence_GetItem_AsDouble(PyObject *seq, Py_ssize_t index)
{
PyObject *item;
double value;
item = PySequence_GetItem(seq, index);
if (item == NULL) {
PyErr_SetString(PyExc_TypeError, "a sequence is expected");
return -1;
}
value = PyFloat_AsDouble(item);
Py_DECREF(item);
if (PyErr_Occurred())
return -1;
return value;
}
static int
PySequence_AsVectorCoords(PyObject *seq, double *const coords,
const Py_ssize_t size)
{
Py_ssize_t i;
if (pgVector_Check(seq)) {
memcpy(coords, ((pgVector *)seq)->coords, sizeof(double) * size);
return 1;
}
if (!PySequence_Check(seq) || PySequence_Length(seq) != size) {
PyErr_SetString(PyExc_ValueError, "Sequence has the wrong length.");
return 0;
}
for (i = 0; i < size; ++i) {
coords[i] = PySequence_GetItem_AsDouble(seq, i);
if (PyErr_Occurred()) {
return 0;
}
}
return 1;
}
static int
pgVectorCompatible_Check(PyObject *obj, Py_ssize_t dim)
{
Py_ssize_t i;
PyObject *tmp;
switch (dim) {
case 2:
if (pgVector2_Check(obj)) {
return 1;
}
break;
case 3:
if (pgVector3_Check(obj)) {
return 1;
}
break;
/*
case 4:
if (pgVector4_Check(obj)) {
return 1;
}
break;
*/
default:
PyErr_SetString(
PyExc_SystemError,
"Wrong internal call to pgVectorCompatible_Check.");
return 0;
}
if (!PySequence_Check(obj) || (PySequence_Length(obj) != dim)) {
return 0;
}
for (i = 0; i < dim; ++i) {
tmp = PySequence_GetItem(obj, i);
if (tmp == NULL || !RealNumber_Check(tmp)) {
Py_XDECREF(tmp);
return 0;
}
Py_DECREF(tmp);
}
return 1;
}
// Returns 1 if obj is vector compatible to a vector of size "dim," and
// copies vector coordinates into "coords" array of size >= dim
// managed by caller. Returns 0 if obj is not compatible or an error
// occurred. If 0 is returned, the error flag will not normally be set.
// Callers should set error themselves. This function is a combo of
// pgVectorCompatible_Check and PySequence_AsVectorCoords
static int
pg_VectorCoordsFromObj(PyObject *obj, Py_ssize_t dim, double *const coords)
{
Py_ssize_t i;
PyObject *tmp;
switch (dim) {
case 2:
if (pgVector2_Check(obj)) {
memcpy(coords, ((pgVector *)obj)->coords, 2 * sizeof(double));
return 1;
}
break;
case 3:
if (pgVector3_Check(obj)) {
memcpy(coords, ((pgVector *)obj)->coords, 3 * sizeof(double));
return 1;
}
break;
default:
PyErr_SetString(PyExc_SystemError,
"Wrong internal call to pg_VectorCoordsFromObj.");
return 0;
}
if (!PySequence_Check(obj) || (PySequence_Length(obj) != dim)) {
return 0;
}
for (i = 0; i < dim; ++i) {
tmp = PySequence_ITEM(obj, i);
if (tmp != NULL) {
coords[i] = PyFloat_AsDouble(tmp);
}
Py_XDECREF(tmp);
if (PyErr_Occurred()) {
PyErr_Clear();
return 0;
}
}
return 1;
}
static double
_scalar_product(const double *coords1, const double *coords2, Py_ssize_t size)
{
Py_ssize_t i;
double product = 0;
for (i = 0; i < size; ++i)
product += coords1[i] * coords2[i];
return product;
}
static int
get_double_from_unicode_slice(PyObject *unicode_obj, Py_ssize_t idx1,
Py_ssize_t idx2, double *val)
{
PyObject *float_obj;
PyObject *slice = PySequence_GetSlice(unicode_obj, idx1, idx2);
if (slice == NULL) {
PyErr_SetString(PyExc_SystemError,
"internal error while converting str slice to float");
return -1;
}
float_obj = PyFloat_FromString(slice);
Py_DECREF(slice);
if (float_obj == NULL)
return 0;
*val = PyFloat_AsDouble(float_obj);
Py_DECREF(float_obj);
return 1;
}
static Py_ssize_t
_vector_find_string_helper(PyObject *str_obj, const char *substr,
Py_ssize_t start, Py_ssize_t end)
{
/* This is implemented using Python's Unicode C-API rather than
* plain C to handle both char* and wchar_t* especially because
* wchar.h was only added to the standard in 95 and we want to be
* ISO C 90 compatible.
*/
PyObject *substr_obj;
Py_ssize_t pos;
substr_obj = PyUnicode_FromString(substr);
if (substr_obj == NULL) {
return -2;
}
pos = PyUnicode_Find(str_obj, substr_obj, start, end, 1);
Py_DECREF(substr_obj);
return pos;
}
/* Extracts coords from a str/unicode Object <str>.
* <delimiter> should be an array of <dim>+1 C-Strings of the strings before,
* between and after the coords.
* The extracted numbers will be stored in <coords>.
* return
* 0 on success.
* -1 if conversion was unsuccessful
* -2 if an internal error occurred and an exception was set
*/
static Py_ssize_t
_vector_coords_from_string(PyObject *str, char **delimiter, double *coords,
Py_ssize_t dim)
{
int error_code;
Py_ssize_t i, start_pos, end_pos, length, ret = 0;
PyObject *vector_string;
vector_string = PyUnicode_FromObject(str);
if (vector_string == NULL) {
ret = -2;
goto end;
}
length = PySequence_Length(vector_string);
/* find the starting point of the first coordinate in the string */
start_pos =
_vector_find_string_helper(vector_string, delimiter[0], 0, length);
if (start_pos < 0) {
ret = start_pos;
goto end;
}
start_pos += strlen(delimiter[0]);
for (i = 0; i < dim; i++) {
/* find the end point of the current coordinate in the string */
end_pos = _vector_find_string_helper(vector_string, delimiter[i + 1],
start_pos, length);
if (end_pos < 0) {
ret = end_pos;
goto end;
}
/* try to convert the current coordinate */
error_code = get_double_from_unicode_slice(vector_string, start_pos,
end_pos, &coords[i]);
if (error_code < 0) {
ret = -2;
goto end;
}
else if (error_code == 0) {
ret = -1;
goto end;
}
/* move starting point to the next coordinate */
start_pos = end_pos + strlen(delimiter[i + 1]);
}
end:
Py_XDECREF(vector_string);
return ret;
}
static PyMemberDef vector_members[] = {
{"epsilon", T_DOUBLE, offsetof(pgVector, epsilon), 0,
"small value used in comparisons"},
{NULL} /* Sentinel */
};
static PyObject *
pgVector_NEW(Py_ssize_t dim)
{
switch (dim) {
case 2:
return vector2_new(&pgVector2_Type, NULL, NULL);
case 3:
return vector3_new(&pgVector3_Type, NULL, NULL);
/*
case 4:
return vector4_new(&pgVector4_Type, NULL, NULL);
*/
default:
return RAISE(PyExc_SystemError,
"Wrong internal call to pgVector_NEW.\n");
}
}
static void
vector_dealloc(pgVector *self)
{
Py_TYPE(self)->tp_free((PyObject *)self);
}
/**********************************************
* Generic vector PyNumber emulation routines
**********************************************/
static PyObject *
vector_generic_math(PyObject *o1, PyObject *o2, int op)
{
Py_ssize_t i, dim;
double *vec_coords;
double other_coords[VECTOR_MAX_SIZE] = {0};
double tmp;
PyObject *other;
pgVector *vec, *ret = NULL;
if (pgVector_Check(o1)) {
vec = (pgVector *)o1;
other = o2;
}
else {
vec = (pgVector *)o2;
other = o1;
op |= OP_ARG_REVERSE;
}
dim = vec->dim;
vec_coords = vec->coords;
if (other == NULL) {
PyErr_BadInternalCall();
return NULL;
}
if (pg_VectorCoordsFromObj(other, dim, other_coords)) {
op |= OP_ARG_VECTOR;
}
else if (RealNumber_Check(other)) {
op |= OP_ARG_NUMBER;
}
else {
op |= OP_ARG_UNKNOWN;
}
if (op & OP_INPLACE) {
ret = vec;
Py_INCREF(ret);
}
else if (op != (OP_MUL | OP_ARG_VECTOR) &&
op != (OP_MUL | OP_ARG_VECTOR | OP_ARG_REVERSE)) {
ret = _vector_subtype_new(vec);
if (ret == NULL)
return NULL;
}
switch (op) {
case OP_ADD | OP_ARG_VECTOR:
case OP_ADD | OP_ARG_VECTOR | OP_ARG_REVERSE:
case OP_ADD | OP_ARG_VECTOR | OP_INPLACE:
for (i = 0; i < dim; i++)
ret->coords[i] = vec_coords[i] + other_coords[i];
break;
case OP_SUB | OP_ARG_VECTOR:
case OP_SUB | OP_ARG_VECTOR | OP_INPLACE:
for (i = 0; i < dim; i++)
ret->coords[i] = vec_coords[i] - other_coords[i];
break;
case OP_SUB | OP_ARG_VECTOR | OP_ARG_REVERSE:
for (i = 0; i < dim; i++)
ret->coords[i] = other_coords[i] - vec_coords[i];
break;
case OP_MUL | OP_ARG_VECTOR:
case OP_MUL | OP_ARG_VECTOR | OP_ARG_REVERSE:
tmp = 0.;
for (i = 0; i < dim; i++)
tmp += vec_coords[i] * other_coords[i];
ret = (pgVector *)PyFloat_FromDouble(tmp);
break;
case OP_MUL | OP_ARG_NUMBER:
case OP_MUL | OP_ARG_NUMBER | OP_ARG_REVERSE:
case OP_MUL | OP_ARG_NUMBER | OP_INPLACE:
tmp = PyFloat_AsDouble(other);
for (i = 0; i < dim; i++)
ret->coords[i] = vec_coords[i] * tmp;
break;
case OP_DIV | OP_ARG_NUMBER:
case OP_DIV | OP_ARG_NUMBER | OP_INPLACE:
tmp = PyFloat_AsDouble(other);
if (tmp == 0.) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
Py_DECREF(ret);
return NULL;
}
tmp = 1. / tmp;
for (i = 0; i < dim; i++)
ret->coords[i] = vec_coords[i] * tmp;
break;
case OP_FLOOR_DIV | OP_ARG_NUMBER:
case OP_FLOOR_DIV | OP_ARG_NUMBER | OP_INPLACE:
tmp = PyFloat_AsDouble(other);
if (tmp == 0.) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
Py_DECREF(ret);
return NULL;
}
tmp = 1. / tmp;
for (i = 0; i < dim; i++)
ret->coords[i] = floor(vec_coords[i] * tmp);
break;
default:
Py_XDECREF(ret);
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
return (PyObject *)ret;
}
static PyObject *
vector_add(PyObject *o1, PyObject *o2)
{
return vector_generic_math(o1, o2, OP_ADD);
}
static PyObject *
vector_inplace_add(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_ADD | OP_INPLACE);
}
static PyObject *
vector_sub(PyObject *o1, PyObject *o2)
{
return vector_generic_math(o1, o2, OP_SUB);
}
static PyObject *
vector_inplace_sub(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_SUB | OP_INPLACE);
}
static PyObject *
vector_mul(PyObject *o1, PyObject *o2)
{
return vector_generic_math(o1, o2, OP_MUL);
}
static PyObject *
vector_inplace_mul(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_MUL | OP_INPLACE);
}
static PyObject *
vector_div(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_DIV);
}
static PyObject *
vector_inplace_div(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_DIV | OP_INPLACE);
}
static PyObject *
vector_floor_div(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_FLOOR_DIV);
}
static PyObject *
vector_inplace_floor_div(pgVector *o1, PyObject *o2)
{
return vector_generic_math((PyObject *)o1, o2, OP_FLOOR_DIV | OP_INPLACE);
}
static PyObject *
vector_neg(pgVector *self)
{
pgVector *ret = _vector_subtype_new(self);
if (ret) {
Py_ssize_t i;
for (i = 0; i < self->dim; i++) {
ret->coords[i] = -self->coords[i];
}
}
return (PyObject *)ret;
}
static PyObject *
vector_pos(pgVector *self)
{
pgVector *ret = _vector_subtype_new(self);
if (ret) {
memcpy(ret->coords, self->coords, sizeof(ret->coords[0]) * ret->dim);
}
return (PyObject *)ret;
}
static int
vector_nonzero(pgVector *self)
{
Py_ssize_t i;
for (i = 0; i < self->dim; i++) {
if (self->coords[i] != 0) {
return 1;
}
}
return 0;
}
static PyObject *
vector_copy(pgVector *self, PyObject *_null)
{
Py_ssize_t i;
pgVector *ret = _vector_subtype_new(self);
if (!ret) {
return NULL;
}
for (i = 0; i < self->dim; i++) {
ret->coords[i] = self->coords[i];
}
return (PyObject *)ret;
}
static PyObject *
vector_clamp_magnitude(pgVector *self, PyObject *const *args, Py_ssize_t nargs)
{
Py_ssize_t i;
pgVector *ret;
ret = _vector_subtype_new(self);
if (ret == NULL)
return NULL;
for (i = 0; i < self->dim; ++i)
ret->coords[i] = self->coords[i];
PyObject *ret_val = vector_clamp_magnitude_ip(ret, args, nargs);
if (!ret_val) {
Py_DECREF(ret);
return NULL;
}
Py_DECREF(ret_val);
return (PyObject *)ret;
}
static PyObject *
vector_clamp_magnitude_ip(pgVector *self, PyObject *const *args,
Py_ssize_t nargs)
{
Py_ssize_t i;
double max_length, old_length_sq, fraction = 1, min_length = 0;
switch (nargs) {
case 2:
min_length = PyFloat_AsDouble(args[0]);
if (min_length == -1.0 && PyErr_Occurred()) {
return NULL;
}
/* Fall-through */
case 1:
max_length = PyFloat_AsDouble(args[nargs - 1]);
if (max_length == -1.0 && PyErr_Occurred()) {
return NULL;
}
break;
default:
return RAISE(PyExc_TypeError,
"Vector clamp function must take one or two floats");
}
if (min_length > max_length) {
return RAISE(PyExc_ValueError,
"Argument min_length cannot exceed max_length");
}
if (max_length < 0 || min_length < 0) {
return RAISE(PyExc_ValueError,
"Arguments to Vector clamp must be non-negative");
}
/* Get magnitude of Vector */
old_length_sq = _scalar_product(self->coords, self->coords, self->dim);
if (old_length_sq == 0 && min_length > 0) {
return RAISE(PyExc_ValueError,
"Cannot clamp a vector with zero length with a "
"min_length greater than 0");
}
/* Notes for other contributors reading this code:
* The numerator for the fraction is different.
*/
if (old_length_sq > max_length * max_length) {
/* Scale to length */
fraction = max_length / sqrt(old_length_sq);
}
if (old_length_sq < min_length * min_length) {
/* Scale to length */
fraction = min_length / sqrt(old_length_sq);
}
for (i = 0; i < self->dim; ++i)
self->coords[i] *= fraction;
Py_RETURN_NONE;
}
static PyNumberMethods vector_as_number = {
.nb_add = (binaryfunc)vector_add,
.nb_subtract = (binaryfunc)vector_sub,
.nb_multiply = (binaryfunc)vector_mul,
.nb_negative = (unaryfunc)vector_neg,
.nb_positive = (unaryfunc)vector_pos,
.nb_bool = (inquiry)vector_nonzero,
.nb_inplace_add = (binaryfunc)vector_inplace_add,
.nb_inplace_subtract = (binaryfunc)vector_inplace_sub,
.nb_inplace_multiply = (binaryfunc)vector_inplace_mul,
.nb_floor_divide = (binaryfunc)vector_floor_div,
.nb_true_divide = (binaryfunc)vector_div,
.nb_inplace_floor_divide = (binaryfunc)vector_inplace_floor_div,
.nb_inplace_true_divide = (binaryfunc)vector_inplace_div,
};
/*************************************************
* Generic vector PySequence emulation routines
*************************************************/
static Py_ssize_t
vector_len(pgVector *self)
{
return (Py_ssize_t)self->dim;
}
static PyObject *
vector_GetItem(pgVector *self, Py_ssize_t index)
{
if (index < 0 || index >= self->dim) {
return RAISE(PyExc_IndexError, "subscript out of range.");
}
return PyFloat_FromDouble(self->coords[index]);
}
static int
vector_SetItem(pgVector *self, Py_ssize_t index, PyObject *value)
{
if (index < 0 || index >= self->dim) {
PyErr_SetString(PyExc_IndexError, "subscript out of range.");
return -1;
}
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "item deletion is not supported");
return -1;