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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
|
/*
* $Id$
*
* ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. The Blender
* Foundation also sells licenses for use in proprietary software under
* the Blender License. See http://www.blender.org/BL/ for information
* about this.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* This is a new part of Blender.
*
* Contributor(s): Michel Selten, Willian P. Germano, Stephen Swaney,
* Chris Keith, Chris Want, Ken Hughes
*
* ***** END GPL/BL DUAL LICENSE BLOCK *****
*/
#include <Python.h>
#include "compile.h" /* for the PyCodeObject */
#include "eval.h" /* for PyEval_EvalCode */
#include "BLI_blenlib.h" /* for BLI_last_slash() */
#include "BIF_interface.h" /* for pupmenu() */
#include "BIF_space.h"
#include "BIF_screen.h"
#include "BIF_toolbox.h"
#include "BKE_action.h" /* for get_pose_channel() */
#include "BKE_library.h"
#include "BKE_object.h" /* during_scriptlink() */
#include "BKE_text.h"
#include "DNA_curve_types.h" /* for struct IpoDriver */
#include "DNA_ID.h" /* ipo driver */
#include "DNA_object_types.h" /* ipo driver */
#include "DNA_constraint_types.h" /* for pyconstraint */
#include "DNA_screen_types.h"
#include "DNA_userdef_types.h" /* for U.pythondir */
#include "MEM_guardedalloc.h"
#include "BPY_extern.h"
#include "BPY_menus.h"
#include "BPI_script.h"
#include "BKE_global.h"
#include "BKE_main.h"
#include "api2_2x/EXPP_interface.h"
#include "api2_2x/constant.h"
#include "api2_2x/gen_utils.h"
#include "api2_2x/gen_library.h" /* GetPyObjectFromID */
#include "api2_2x/BGL.h"
#include "api2_2x/Blender.h"
#include "api2_2x/Camera.h"
#include "api2_2x/Draw.h"
#include "api2_2x/Object.h"
#include "api2_2x/Registry.h"
#include "api2_2x/Pose.h"
#include "api2_2x/bpy.h" /* for the new "bpy" module */
/*these next two are for pyconstraints*/
#include "api2_2x/IDProp.h"
#include "api2_2x/matrix.h"
/* for scriptlinks */
#include "DNA_lamp_types.h"
#include "DNA_camera_types.h"
#include "DNA_world_types.h"
#include "DNA_scene_types.h"
#include "DNA_material_types.h"
/* bpy_registryDict is declared in api2_2x/Registry.h and defined
* in api2_2x/Registry.c
* This Python dictionary will be used to store data that scripts
* choose to preserve after they are executed, so user changes can be
* restored next time the script is used. Check the Blender.Registry module.
*/
/*#include "api2_2x/Registry.h" */
/* for pydrivers (ipo drivers defined by one-line Python expressions) */
PyObject *bpy_pydriver_Dict = NULL;
/*
* set up a weakref list for Armatures
* creates list in __main__ module dict
*/
int setup_armature_weakrefs()
{
PyObject *maindict;
PyObject *main_module;
char *list_name = ARM_WEAKREF_LIST_NAME;
main_module = PyImport_AddModule( "__main__");
if(main_module){
PyObject *weakreflink;
maindict= PyModule_GetDict(main_module);
/* check if there is already a dict entry for the armature weakrefs,
* and delete if so before making another one */
weakreflink= PyDict_GetItemString(maindict,list_name);
if( weakreflink != NULL ) {
PyDict_DelItemString(maindict,list_name);
Py_XDECREF( weakreflink );
}
if (PyDict_SetItemString(maindict,
list_name,
PyList_New(0)) == -1){
printf("Oops - setup_armature_weakrefs()\n");
return 0;
}
}
return 1;
}
/* Declares the modules and their initialization functions
* These are TOP-LEVEL modules e.g. import `module` - there is no
* support for packages here e.g. import `package.module` */
static struct _inittab BPy_Inittab_Modules[] = {
{"Blender", M_Blender_Init},
{"bpy", m_bpy_init},
{NULL, NULL}
};
/*************************************************************************
* Structure definitions
**************************************************************************/
#define FILENAME_LENGTH 24
typedef struct _ScriptError {
char filename[FILENAME_LENGTH];
int lineno;
} ScriptError;
/****************************************************************************
* Global variables
****************************************************************************/
ScriptError g_script_error;
/***************************************************************************
* Function prototypes
***************************************************************************/
PyObject *RunPython( Text * text, PyObject * globaldict );
char *GetName( Text * text );
PyObject *CreateGlobalDictionary( void );
void ReleaseGlobalDictionary( PyObject * dict );
void DoAllScriptsFromList( ListBase * list, short event );
PyObject *importText( char *name );
void init_ourImport( void );
void init_ourReload( void );
PyObject *blender_import( PyObject * self, PyObject * args );
PyObject *RunPython2( Text * text, PyObject * globaldict, PyObject *localdict );
void BPY_Err_Handle( char *script_name );
PyObject *traceback_getFilename( PyObject * tb );
/****************************************************************************
* Description: This function will start the interpreter and load all modules
* as well as search for a python installation.
****************************************************************************/
void BPY_start_python( int argc, char **argv )
{
static int argc_copy = 0;
static char **argv_copy = NULL;
int first_time = argc;
/* we keep a copy of the values of argc and argv so that the game engine
* can call BPY_start_python(0, NULL) whenever a game ends, without having
* to know argc and argv there (in source/blender/src/space.c) */
if( first_time ) {
argc_copy = argc;
argv_copy = argv;
}
//stuff for Registry module
bpy_registryDict = PyDict_New( );/* check comment at start of this file */
if( !bpy_registryDict )
printf( "Error: Couldn't create the Registry Python Dictionary!" );
Py_SetProgramName( "blender" );
/* Py_Initialize() will attempt to import the site module and
* print an error if not found. See init_syspath() for the
* rest of our init msgs.
*/
/* print Python version
* Py_GetVersion() returns a ptr to a static string "9.9.9 (aaaa..."
*/
{
int count = 3; /* a nice default for major.minor. example 2.5 */
const char *version = Py_GetVersion();
/* we know a blank is there somewhere! */
char *blank_ptr = strchr( version, ' ');
if(blank_ptr)
count = blank_ptr - version;
printf( "Compiled with Python version %.*s.\n", count, version );
}
//Initialize the TOP-LEVEL modules
PyImport_ExtendInittab(BPy_Inittab_Modules);
//Start the interpreter
Py_Initialize( );
PySys_SetArgv( argc_copy, argv_copy );
//Overrides __import__
init_ourImport( );
init_ourReload( );
//init a global dictionary
g_blenderdict = NULL;
//Look for a python installation
init_syspath( first_time ); /* not first_time: some msgs are suppressed */
return;
}
/*****************************************************************************/
/* Description: This function will terminate the Python interpreter */
/*****************************************************************************/
void BPY_end_python( void )
{
Script *script = NULL;
if( bpy_registryDict ) {
Py_DECREF( bpy_registryDict );
bpy_registryDict = NULL;
}
if( bpy_pydriver_Dict ) {
Py_DECREF( bpy_pydriver_Dict );
bpy_pydriver_Dict = NULL;
}
/* Freeing all scripts here prevents problems with the order in which
* Python is finalized and G.main is freed in exit_usiblender() */
for (script = G.main->script.first; script; script = script->id.next) {
BPY_clear_script(script);
free_libblock( &G.main->script, script );
}
Py_Finalize( );
BPyMenu_RemoveAllEntries( ); /* freeing bpymenu mem */
/* a script might've opened a .blend file but didn't close it, so: */
EXPP_Library_Close( );
return;
}
void syspath_append( char *dirname )
{
PyObject *mod_sys, *dict, *path, *dir;
PyErr_Clear( );
dir = Py_BuildValue( "s", dirname );
mod_sys = PyImport_ImportModule( "sys" ); /* new ref */
dict = PyModule_GetDict( mod_sys ); /* borrowed ref */
path = PyDict_GetItemString( dict, "path" ); /* borrowed ref */
if( !PyList_Check( path ) )
return;
PyList_Append( path, dir );
if( PyErr_Occurred( ) )
Py_FatalError( "could not build sys.path" );
Py_DECREF( mod_sys );
}
void init_syspath( int first_time )
{
PyObject *path;
PyObject *mod, *d;
char *progname;
char execdir[FILE_MAXDIR]; /*defines from DNA_space_types.h */
int n;
path = Py_BuildValue( "s", bprogname );
mod = PyImport_ImportModule( "Blender.sys" );
if( mod ) {
d = PyModule_GetDict( mod );
EXPP_dict_set_item_str( d, "progname", path );
Py_DECREF( mod );
} else
printf( "Warning: could not set Blender.sys.progname\n" );
progname = BLI_last_slash( bprogname ); /* looks for the last dir separator */
n = progname - bprogname;
if( n > 0 ) {
strncpy( execdir, bprogname, n );
if( execdir[n - 1] == '.' )
n--; /*fix for when run as ./blender */
execdir[n] = '\0';
syspath_append( execdir ); /* append to module search path */
} else
printf( "Warning: could not determine argv[0] path\n" );
/*
attempt to import 'site' module as a check for valid
python install found.
*/
printf("Checking for installed Python... "); /* appears after msg "Compiled with Python 2.x" */
mod = PyImport_ImportModule( "site" ); /* new ref */
if( mod ) {
printf("got it!\n");
Py_DECREF( mod );
} else { /* import 'site' failed */
PyErr_Clear( );
if( first_time ) {
printf( "No installed Python found.\n" );
printf( "Only built-in modules are available. Some scripts may not run.\n" );
printf( "Continuing happily.\n" );
}
}
/*
* initialize the sys module
* set sys.executable to the Blender exe
*/
mod = PyImport_ImportModule( "sys" ); /* new ref */
if( mod ) {
d = PyModule_GetDict( mod ); /* borrowed ref */
EXPP_dict_set_item_str( d, "executable",
Py_BuildValue( "s", bprogname ) );
Py_DECREF( mod );
} else{
printf("import of sys module failed\n");
}
}
/****************************************************************************
* Description: This function finishes Python initialization in Blender.
Because U.pythondir (user defined dir for scripts) isn't
initialized when BPY_start_Python needs to be executed, we
postpone adding U.pythondir to sys.path and also BPyMenus
(mechanism to register scripts in Blender menus) for when
that dir info is available.
****************************************************************************/
void BPY_post_start_python( void )
{
char dirpath[FILE_MAX];
char *sdir = NULL;
if(U.pythondir[0] != '\0' ) {
char modpath[FILE_MAX];
int upyslen = strlen(U.pythondir);
/* check if user pydir ends with a slash and, if so, remove the slash
* (for eventual implementations of c library's stat function that might
* not like it) */
if (upyslen > 2) { /* avoids doing anything if dir == '//' */
char ending = U.pythondir[upyslen - 1];
if (ending == '/' || ending == '\\')
U.pythondir[upyslen - 1] = '\0';
}
BLI_strncpy(dirpath, U.pythondir, FILE_MAX);
BLI_convertstringcode(dirpath, G.sce, 0);
syspath_append(dirpath); /* append to module search path */
BLI_make_file_string("/", modpath, dirpath, "bpymodules");
if (BLI_exists(modpath)) syspath_append(modpath);
}
sdir = bpy_gethome(1);
if (sdir) {
syspath_append(sdir);
BLI_make_file_string("/", dirpath, sdir, "bpymodules");
if (BLI_exists(dirpath)) syspath_append(dirpath);
}
BPyMenu_Init( 0 ); /* get dynamic menus (registered scripts) data */
return;
}
/****************************************************************************
* Description: This function will return the linenumber on which an error
* has occurred in the Python script.
****************************************************************************/
int BPY_Err_getLinenumber( void )
{
return g_script_error.lineno;
}
/*****************************************************************************/
/* Description: This function will return the filename of the python script. */
/*****************************************************************************/
const char *BPY_Err_getFilename( void )
{
return g_script_error.filename;
}
/*****************************************************************************/
/* Description: Return PyString filename from a traceback object */
/*****************************************************************************/
PyObject *traceback_getFilename( PyObject * tb )
{
PyObject *v = NULL;
/* co_filename is in f_code, which is in tb_frame, which is in tb */
v = PyObject_GetAttrString( tb, "tb_frame" );
if (v) {
Py_DECREF( v );
v = PyObject_GetAttrString( v, "f_code" );
if (v) {
Py_DECREF( v );
v = PyObject_GetAttrString( v, "co_filename" );
}
}
if (v) return v;
else return PyString_FromString("unknown");
}
/****************************************************************************
* Description: Blender Python error handler. This catches the error and
* stores filename and line number in a global
*****************************************************************************/
void BPY_Err_Handle( char *script_name )
{
PyObject *exception, *err, *tb, *v;
if( !script_name ) {
printf( "Error: script has NULL name\n" );
return;
}
PyErr_Fetch( &exception, &err, &tb );
if (!script_name) script_name = "untitled";
//if( !exception && !tb ) {
// printf( "FATAL: spurious exception\n" );
// return;
//}
strcpy( g_script_error.filename, script_name );
if( exception
&& PyErr_GivenExceptionMatches( exception, PyExc_SyntaxError ) ) {
/* no traceback available when SyntaxError */
PyErr_Restore( exception, err, tb ); /* takes away reference! */
PyErr_Print( );
v = PyObject_GetAttrString( err, "lineno" );
if( v ) {
g_script_error.lineno = PyInt_AsLong( v );
Py_DECREF( v );
} else {
g_script_error.lineno = -1;
}
/* this avoids an abort in Python 2.3's garbage collecting: */
PyErr_Clear( );
return;
} else {
PyErr_NormalizeException( &exception, &err, &tb );
PyErr_Restore( exception, err, tb ); /* takes away reference! */
PyErr_Print( );
tb = PySys_GetObject( "last_traceback" );
if( !tb ) {
printf( "\nCan't get traceback\n" );
return;
}
Py_INCREF( tb );
/* From old bpython BPY_main.c:
* 'check traceback objects and look for last traceback in the
* same text file. This is used to jump to the line of where the
* error occured. "If the error occured in another text file or module,
* the last frame in the current file is adressed."'
*/
for(;;) {
v = PyObject_GetAttrString( tb, "tb_next" );
if( !v || v == Py_None ||
strcmp(PyString_AsString(traceback_getFilename(v)), script_name)) {
break;
}
Py_DECREF( tb );
tb = v;
}
v = PyObject_GetAttrString( tb, "tb_lineno" );
if (v) {
g_script_error.lineno = PyInt_AsLong(v);
Py_DECREF(v);
}
v = traceback_getFilename( tb );
if (v) {
strncpy( g_script_error.filename, PyString_AsString( v ),
FILENAME_LENGTH );
Py_DECREF(v);
}
Py_DECREF( tb );
}
return;
}
/****************************************************************************
* Description: This function executes the script passed by st.
* Notes: It is called by blender/src/drawtext.c when a Blender user
* presses ALT+PKEY in the script's text window.
*****************************************************************************/
int BPY_txt_do_python_Text( struct Text *text )
{
PyObject *py_dict, *py_result;
BPy_constant *info;
char textname[24];
Script *script = G.main->script.first;
if( !text )
return 0;
/* check if this text is already running */
while( script ) {
if( !strcmp( script->id.name + 2, text->id.name + 2 ) ) {
/* if this text is already a running script,
* just move to it: */
SpaceScript *sc;
newspace( curarea, SPACE_SCRIPT );
sc = curarea->spacedata.first;
sc->script = script;
return 1;
}
script = script->id.next;
}
/* Create a new script structure and initialize it: */
script = alloc_libblock( &G.main->script, ID_SCRIPT, GetName( text ) );
if( !script ) {
printf( "couldn't allocate memory for Script struct!" );
return 0;
}
/* if in the script Blender.Load(blendfile) is not the last command,
* an error after it will call BPY_Err_Handle below, but the text struct
* will have been deallocated already, so we need to copy its name here.
*/
BLI_strncpy( textname, GetName( text ),
strlen( GetName( text ) ) + 1 );
script->id.us = 1;
script->flags = SCRIPT_RUNNING;
script->py_draw = NULL;
script->py_event = NULL;
script->py_button = NULL;
script->py_browsercallback = NULL;
py_dict = CreateGlobalDictionary( );
if( !setup_armature_weakrefs()){
printf("Oops - weakref dict\n");
return 0;
}
script->py_globaldict = py_dict;
info = ( BPy_constant * ) PyConstant_New( );
if( info ) {
PyConstant_Insert( info, "name",
PyString_FromString( script->id.name + 2 ) );
Py_INCREF( Py_None );
PyConstant_Insert( info, "arg", Py_None );
EXPP_dict_set_item_str( py_dict, "__script__",
( PyObject * ) info );
}
py_result = RunPython( text, py_dict ); /* Run the script */
if( !py_result ) { /* Failed execution of the script */
BPY_Err_Handle( textname );
ReleaseGlobalDictionary( py_dict );
script->py_globaldict = NULL;
if( G.main->script.first )
free_libblock( &G.main->script, script );
return 0;
} else {
Py_DECREF( py_result );
script->flags &= ~SCRIPT_RUNNING;
if( !script->flags ) {
ReleaseGlobalDictionary( py_dict );
script->py_globaldict = NULL;
free_libblock( &G.main->script, script );
}
}
return 1; /* normal return */
}
/****************************************************************************
* Description: Called from command line to run a Python script
* automatically. The script can be a file or a Blender Text in the current
* .blend.
****************************************************************************/
void BPY_run_python_script( char *fn )
{
Text *text = NULL;
int is_blender_text = 0;
if (!BLI_exists(fn)) { /* if there's no such filename ... */
text = G.main->text.first; /* try an already existing Blender Text */
while (text) {
if (!strcmp(fn, text->id.name + 2)) break;
text = text->id.next;
}
if (text == NULL) {
printf("\nError: no such file or Blender text -- %s.\n", fn);
return;
}
else is_blender_text = 1; /* fn is already a Blender Text */
}
else {
text = add_text(fn);
if (text == NULL) {
printf("\nError in BPY_run_python_script:\n"
"couldn't create Blender text from %s\n", fn);
/* Chris: On Windows if I continue I just get a segmentation
* violation. To get a baseline file I exit here. */
exit(2);
/* return; */
}
}
if (BPY_txt_do_python_Text(text) != 1) {
printf("\nError executing Python script from command-line:\n"
"%s (at line %d).\n", fn, BPY_Err_getLinenumber());
}
if (!is_blender_text) {
/* We can't simply free the text, since the script might have called
* Blender.Load() to load a new .blend, freeing previous data.
* So we check if the pointer is still valid. */
Text *txtptr = G.main->text.first;
while (txtptr) {
if (txtptr == text) {
free_libblock(&G.main->text, text);
break;
}
txtptr = txtptr->id.next;
}
}
}
/****************************************************************************
* Description: This function executes the script chosen from a menu.
* Notes: It is called by the ui code in src/header_???.c when a user
* clicks on a menu entry that refers to a script.
* Scripts are searched in the BPyMenuTable, using the given
* menutype and event values to know which one was chosen.
*****************************************************************************/
int BPY_menu_do_python( short menutype, int event )
{
PyObject *py_dict, *py_res, *pyarg = NULL;
BPy_constant *info;
BPyMenu *pym;
BPySubMenu *pysm;
FILE *fp = NULL;
char *buffer, *s;
char filestr[FILE_MAXDIR + FILE_MAXFILE];
char scriptname[21];
Script *script = NULL;
int len;
pym = BPyMenu_GetEntry( menutype, ( short ) event );
if( !pym )
return 0;
if( pym->version > G.version )
notice( "Version mismatch: script was written for Blender %d. "
"It may fail with yours: %d.", pym->version,
G.version );
/* if there are submenus, let the user choose one from a pupmenu that we
* create here.*/
pysm = pym->submenus;
if( pysm ) {
char *pupstr;
int arg;
pupstr = BPyMenu_CreatePupmenuStr( pym, menutype );
if( pupstr ) {
arg = pupmenu( pupstr );
MEM_freeN( pupstr );
if( arg >= 0 ) {
while( arg-- )
pysm = pysm->next;
pyarg = PyString_FromString( pysm->arg );
} else
return 0;
}
}
if( !pyarg ) { /* no submenus */
Py_INCREF( Py_None );
pyarg = Py_None;
}
if( pym->dir ) { /* script is in U.pythondir */
char upythondir[FILE_MAXDIR];
/* dirs in Blender can be "//", which has a special meaning */
BLI_strncpy(upythondir, U.pythondir, FILE_MAXDIR);
BLI_convertstringcode(upythondir, G.sce, 0); /* if so, this expands it */
BLI_make_file_string( "/", filestr, upythondir, pym->filename );
}
else { /* script is in default scripts dir */
char *scriptsdir = bpy_gethome(1);
if (!scriptsdir) {
printf("Error loading script: can't find default scripts dir!");
return 0;
}
BLI_make_file_string( "/", filestr, scriptsdir, pym->filename );
}
fp = fopen( filestr, "rb" );
if( !fp ) {
printf( "Error loading script: couldn't open file %s\n",
filestr );
return 0;
}
BLI_strncpy(scriptname, pym->name, 21);
len = strlen(scriptname) - 1;
/* by convention, scripts that open the file browser or have submenus
* display '...'. Here we remove them from the datablock name */
while ((len > 0) && scriptname[len] == '.') {
scriptname[len] = '\0';
len--;
}
/* Create a new script structure and initialize it: */
script = alloc_libblock( &G.main->script, ID_SCRIPT, scriptname );
if( !script ) {
printf( "couldn't allocate memory for Script struct!" );
fclose( fp );
return 0;
}
/* let's find a proper area for an eventual script gui:
* (still experimenting here, need definition on which win
* each group will be put to code this properly) */
switch ( menutype ) {
case PYMENU_IMPORT: /* first 4 were handled in header_info.c */
case PYMENU_EXPORT:
case PYMENU_HELP:
case PYMENU_RENDER:
case PYMENU_WIZARDS:
case PYMENU_SCRIPTTEMPLATE:
case PYMENU_MESHFACEKEY:
break;
default:
if( curarea->spacetype != SPACE_SCRIPT ) {
ScrArea *sa = NULL;
sa = find_biggest_area_of_type( SPACE_BUTS );
if( sa ) {
if( ( 1.5 * sa->winx ) < sa->winy )
sa = NULL; /* too narrow? */
}
if( !sa )
sa = find_biggest_area_of_type( SPACE_SCRIPT );
if( !sa )
sa = find_biggest_area_of_type( SPACE_TEXT );
if( !sa )
sa = find_biggest_area_of_type( SPACE_IMAGE ); /* group UV */
if( !sa )
sa = find_biggest_area_of_type( SPACE_VIEW3D );
if( !sa )
sa = find_biggest_area( );
areawinset( sa->win );
}
break;
}
script->id.us = 1;
script->flags = SCRIPT_RUNNING;
script->py_draw = NULL;
script->py_event = NULL;
script->py_button = NULL;
script->py_browsercallback = NULL;
py_dict = CreateGlobalDictionary( );
script->py_globaldict = py_dict;
info = ( BPy_constant * ) PyConstant_New( );
if( info ) {
PyConstant_Insert( info, "name",
PyString_FromString( script->id.name + 2 ) );
PyConstant_Insert( info, "arg", pyarg );
EXPP_dict_set_item_str( py_dict, "__script__",
( PyObject * ) info );
}
/* Previously we used PyRun_File to run directly the code on a FILE
* object, but as written in the Python/C API Ref Manual, chapter 2,
* 'FILE structs for different C libraries can be different and
* incompatible'.
* So now we load the script file data to a buffer */
fseek( fp, 0L, SEEK_END );
len = ftell( fp );
fseek( fp, 0L, SEEK_SET );
buffer = MEM_mallocN( len + 2, "pyfilebuf" ); /* len+2 to add '\n\0' */
len = fread( buffer, 1, len, fp );
buffer[len] = '\n'; /* fix syntax error in files w/o eol */
buffer[len + 1] = '\0';
/* fast clean-up of dos cr/lf line endings: change '\r' to space */
/* we also have to check for line splitters: '\\' */
/* to avoid possible syntax errors on dos files on win */
/**/
/* but first make sure we won't disturb memory below &buffer[0]: */
if( *buffer == '\r' )
*buffer = ' ';
/* now handle the whole buffer */
for( s = buffer + 1; *s != '\0'; s++ ) {
if( *s == '\r' ) {
if( *( s - 1 ) == '\\' ) { /* special case: long lines split with '\': */
*( s - 1 ) = ' '; /* we write ' \', because '\ ' is a syntax error */
*s = '\\';
} else
*s = ' '; /* not a split line, just replace '\r' with ' ' */
}
}
fclose( fp );
if( !setup_armature_weakrefs()){
printf("Oops - weakref dict\n");
MEM_freeN( buffer );
return 0;
}
/* run the string buffer */
py_res = PyRun_String( buffer, Py_file_input, py_dict, py_dict );
MEM_freeN( buffer );
if( !py_res ) { /* Failed execution of the script */
BPY_Err_Handle( script->id.name + 2 );
ReleaseGlobalDictionary( py_dict );
script->py_globaldict = NULL;
if( G.main->script.first )
free_libblock( &G.main->script, script );
error( "Python script error: check console" );
return 0;
} else {
Py_DECREF( py_res );
script->flags &= ~SCRIPT_RUNNING;
if( !script->flags ) {
ReleaseGlobalDictionary( py_dict );
script->py_globaldict = NULL;
free_libblock( &G.main->script, script );
/* special case: called from the menu in the Scripts window
* we have to change sc->script pointer, since it'll be freed here.*/
if( curarea->spacetype == SPACE_SCRIPT ) {
SpaceScript *sc = curarea->spacedata.first;
sc->script = G.main->script.first; /* can be null, which is ok ... */
/* ... meaning no other script is running right now. */
}
}
}
return 1; /* normal return */
}
/*****************************************************************************
* Description:
* Notes:
*****************************************************************************/
void BPY_free_compiled_text( struct Text *text )
{
if( !text->compiled )
return;
Py_DECREF( ( PyObject * ) text->compiled );
text->compiled = NULL;
return;
}
/*****************************************************************************
* Description: This function frees a finished (flags == 0) script.
*****************************************************************************/
void BPY_free_finished_script( Script * script )
{
if( !script )
return;
if( PyErr_Occurred( ) ) { /* if script ended after filesel */
PyErr_Print( ); /* eventual errors are handled now */
error( "Python script error: check console" );
}
free_libblock( &G.main->script, script );
return;
}
static void unlink_script( Script * script )
{ /* copied from unlink_text in drawtext.c */
bScreen *scr;
ScrArea *area;
SpaceLink *sl;
for( scr = G.main->screen.first; scr; scr = scr->id.next ) {
for( area = scr->areabase.first; area; area = area->next ) {
for( sl = area->spacedata.first; sl; sl = sl->next ) {
if( sl->spacetype == SPACE_SCRIPT ) {
SpaceScript *sc = ( SpaceScript * ) sl;
if( sc->script == script ) {
sc->script = NULL;
if( sc ==
area->spacedata.first ) {
scrarea_queue_redraw
( area );
}
}
}
}
}
}
}
void BPY_clear_script( Script * script )
{
PyObject *dict;
if( !script )
return;
if (!Py_IsInitialized()) {
printf("\nError: trying to free script data after finalizing Python!");
printf("\nScript name: %s\n", script->id.name+2);
return;
}
Py_XDECREF( ( PyObject * ) script->py_draw );
Py_XDECREF( ( PyObject * ) script->py_event );
Py_XDECREF( ( PyObject * ) script->py_button );
Py_XDECREF( ( PyObject * ) script->py_browsercallback );
script->py_draw = NULL;
script->py_event = NULL;
script->py_button = NULL;
script->py_browsercallback = NULL;
dict = script->py_globaldict;
if( dict ) {
PyDict_Clear( dict );
Py_DECREF( dict ); /* Release dictionary. */
script->py_globaldict = NULL;
}
unlink_script( script );
}
/* PyDrivers */
/* PyDrivers are Ipo Drivers governed by expressions written in Python.
* Expressions here are one-liners that evaluate to a float value. */
/* For faster execution we keep a special dictionary for pydrivers, with
* the needed modules and aliases. */
static int bpy_pydriver_create_dict(void)
{
PyObject *d, *mod;
if (bpy_pydriver_Dict) return -1;
d = PyDict_New();
if (!d) return -1;
bpy_pydriver_Dict = d;
/* import some modules: builtins, Blender, math, Blender.noise */
PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
mod = PyImport_ImportModule("Blender");
if (mod) {
PyDict_SetItemString(d, "Blender", mod);
PyDict_SetItemString(d, "b", mod);
Py_DECREF(mod);
}
mod = PyImport_ImportModule("math");
if (mod) {
PyDict_SetItemString(d, "math", mod);
PyDict_SetItemString(d, "m", mod);
Py_DECREF(mod);
}
mod = PyImport_ImportModule("Blender.Noise");
if (mod) {
PyDict_SetItemString(d, "noise", mod);
PyDict_SetItemString(d, "n", mod);
Py_DECREF(mod);
}
/* If there's a Blender text called pydrivers.py, import it.
* Users can add their own functions to this module. */
mod = importText("pydrivers"); /* can also use PyImport_Import() */
if (mod) {
PyDict_SetItemString(d, "pydrivers", mod);
PyDict_SetItemString(d, "p", mod);
Py_DECREF(mod);
}
else
PyErr_Clear();
/* short aliases for some Get() functions: */
/* ob(obname) == Blender.Object.Get(obname) */
mod = PyImport_ImportModule("Blender.Object");
if (mod) {
PyObject *fcn = PyObject_GetAttrString(mod, "Get");
Py_DECREF(mod);
if (fcn) {
PyDict_SetItemString(d, "ob", fcn);
Py_DECREF(fcn);
}
}
/* me(meshname) == Blender.Mesh.Get(meshname) */
mod = PyImport_ImportModule("Blender.Mesh");
if (mod) {
PyObject *fcn = PyObject_GetAttrString(mod, "Get");
Py_DECREF(mod);
if (fcn) {
PyDict_SetItemString(d, "me", fcn);
Py_DECREF(fcn);
}
}
/* ma(matname) == Blender.Material.Get(matname) */
mod = PyImport_ImportModule("Blender.Material");
if (mod) {
PyObject *fcn = PyObject_GetAttrString(mod, "Get");
Py_DECREF(mod);
if (fcn) {
PyDict_SetItemString(d, "ma", fcn);
Py_DECREF(fcn);
}
}
return 0;
}
/* error return function for BPY_eval_pydriver */
static float pydriver_error(IpoDriver *driver) {
if (bpy_pydriver_oblist)
bpy_pydriver_freeList();
if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
Py_DECREF(bpy_pydriver_Dict);
bpy_pydriver_Dict = NULL;
}
driver->flag |= IPO_DRIVER_FLAG_INVALID; /* py expression failed */
if (driver->ob)
fprintf(stderr, "\nError in Ipo Driver: Object %s\nThis is the failed Python expression:\n'%s'\n\n", driver->ob->id.name+2, driver->name);
else
fprintf(stderr, "\nError in Ipo Driver: No Object\nThis is the failed Python expression:\n'%s'\n\n", driver->name);
PyErr_Print();
return 0.0f;
}
/********PyConstraints*********/
int BPY_is_pyconstraint(Text *text)
{
TextLine *tline = text->lines.first;
if (tline && (tline->len > 10)) {
char *line = tline->line;
/* Expected format: #BPYCONSTRAINT
* The actual checks are forgiving, so slight variations also work. */
if (line && line[0] == '#' && strstr(line, "BPYCONSTRAINT")) return 1;
}
return 0;
}
/* This evals py constraints. It is passed all the arguments the normal constraints recieve */
void BPY_pyconstraint_eval(bPythonConstraint *con, float ownermat[][4], float targetmat[][4])
{
PyObject *srcmat, *tarmat, *idprop;
PyObject *globals;
PyObject *gval;
PyObject *pyargs, *retval;
MatrixObject *retmat;
int row, col;
if ( !con->text ) return;
if ( con->flag & PYCON_SCRIPTERROR) return;
globals = CreateGlobalDictionary();
srcmat = newMatrixObject( (float*)ownermat, 4, 4, Py_NEW );
tarmat = newMatrixObject( (float*)targetmat, 4, 4, Py_NEW );
idprop = BPy_Wrap_IDProperty( NULL, con->prop, NULL);
/* since I can't remember what the armature weakrefs do, I'll just leave this here
commented out. This function was based on pydrivers, and it might still be relevent.
if( !setup_armature_weakrefs()){
fprintf( stderr, "Oops - weakref dict setup\n");
return result;
}
*/
retval = RunPython( con->text, globals );
if ( retval == NULL ) {
BPY_Err_Handle(con->text->id.name);
ReleaseGlobalDictionary( globals );
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
return;
}
if (retval) {Py_XDECREF( retval );}
retval = NULL;
gval = PyDict_GetItemString(globals, "doConstraint");
if (!gval) {
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
printf("ERROR: no doConstraint function in constraint!\n");
return;
}
/* Now for the fun part! Try and find the functions we need. */
if (PyFunction_Check(gval) ) {
pyargs = Py_BuildValue("OOO", srcmat, tarmat, idprop);
retval = PyObject_CallObject(gval, pyargs);
Py_XDECREF( pyargs );
} else {
printf("ERROR: doConstraint is supposed to be a function!\n");
con->flag |= PYCON_SCRIPTERROR;
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
return;
}
if (!retval) {
BPY_Err_Handle(con->text->id.name);
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
return;
}
if (!PyObject_TypeCheck(retval, &matrix_Type)) {
printf("Error in PyConstraint - doConstraint: Function not returning a matrix!\n");
con->flag |= PYCON_SCRIPTERROR;
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return;
}
retmat = (MatrixObject*) retval;
if (retmat->rowSize != 4 || retmat->colSize != 4) {
printf("Error in PyConstraint - doConstraint: Matrix returned is the wrong size!\n");
con->flag |= PYCON_SCRIPTERROR;
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return;
}
/* this is the reverse of code taken from newMatrix() */
for(row = 0; row < 4; row++) {
for(col = 0; col < 4; col++) {
ownermat[row][col] = retmat->contigPtr[row*4+col];
}
}
/* clear globals */
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( idprop );
Py_XDECREF( srcmat );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
}
/* This evaluates whether constraint uses targets, and also the target matrix
* Return code of 0 = doesn't use targets, 1 = uses targets + matrix set, -1 = uses targets + matrix not set
*/
int BPY_pyconstraint_targets(bPythonConstraint *con, float targetmat[][4])
{
PyObject *tar, *subtar;
PyObject *tarmat, *idprop;
PyObject *globals;
PyObject *gval, *gval2;
PyObject *pyargs, *retval;
MatrixObject *retmat;
bPoseChannel *pchan;
int row, col;
if ( !con->text ) return 0;
if ( con->flag & PYCON_SCRIPTERROR) return 0;
globals = CreateGlobalDictionary();
tar = Object_CreatePyObject( con->tar );
if ( con->tar )
pchan = get_pose_channel( con->tar->pose, con->subtarget );
else
pchan = NULL;
subtar = PyPoseBone_FromPosechannel( pchan );
tarmat = newMatrixObject( (float*)targetmat, 4, 4, Py_NEW );
idprop = BPy_Wrap_IDProperty( NULL, con->prop, NULL);
/* since I can't remember what the armature weakrefs do, I'll just leave this here
commented out. This function was based on pydrivers, and it might still be relevent.
if( !setup_armature_weakrefs()){
fprintf( stderr, "Oops - weakref dict setup\n");
return result;
}
*/
retval = RunPython( con->text, globals );
if ( retval == NULL ) {
BPY_Err_Handle(con->text->id.name);
ReleaseGlobalDictionary( globals );
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
return 0;
}
if (retval) {Py_XDECREF( retval );}
retval = NULL;
/* try to find USE_TARGET global constant */
gval = PyDict_GetItemString(globals, "USE_TARGET");
if (!gval) {
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
return 0;
}
/* try to find doTarget function to set the target matrix */
gval2 = PyDict_GetItemString(globals, "doTarget");
if (!gval2) {
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
return -1;
}
/* Now for the fun part! Try and find the functions we need.*/
if (PyFunction_Check(gval2) ) {
pyargs = Py_BuildValue("OOOO", tar, subtar, tarmat, idprop);
retval = PyObject_CallObject(gval2, pyargs);
Py_XDECREF( pyargs );
} else {
printf("ERROR: doTarget is supposed to be a function!\n");
con->flag |= PYCON_SCRIPTERROR;
ReleaseGlobalDictionary( globals );
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
return -1;
}
if (!retval) {
BPY_Err_Handle(con->text->id.name);
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
ReleaseGlobalDictionary( globals );
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
return -1;
}
if (!PyObject_TypeCheck(retval, &matrix_Type)) {
ReleaseGlobalDictionary( globals );
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return -1;
}
retmat = (MatrixObject*) retval;
if (retmat->rowSize != 4 || retmat->colSize != 4) {
printf("Error in PyConstraint - doTarget: Matrix returned is the wrong size!\n");
con->flag |= PYCON_SCRIPTERROR;
ReleaseGlobalDictionary( globals );
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return -1;
}
/* this is the reverse of code taken from newMatrix() */
for(row = 0; row < 4; row++) {
for(col = 0; col < 4; col++) {
targetmat[row][col] = retmat->contigPtr[row*4+col];
}
}
/* clear globals */
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( tar );
Py_XDECREF( subtar );
Py_XDECREF( idprop );
Py_XDECREF( tarmat );
Py_XDECREF( retval );
return 1;
}
/* This draws+handles the user-defined interface for editing pyconstraints idprops */
void BPY_pyconstraint_settings(void *arg1, void *arg2)
{
bPythonConstraint *con= (bPythonConstraint *)arg1;
PyObject *idprop;
PyObject *globals;
PyObject *gval;
PyObject *retval;
if ( !con->text ) return;
if ( con->flag & PYCON_SCRIPTERROR) return;
globals = CreateGlobalDictionary();
idprop = BPy_Wrap_IDProperty( NULL, con->prop, NULL);
retval = RunPython( con->text, globals );
if ( retval == NULL ) {
BPY_Err_Handle(con->text->id.name);
ReleaseGlobalDictionary( globals );
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
Py_XDECREF( idprop );
return;
}
if (retval) {Py_XDECREF( retval );}
retval = NULL;
gval = PyDict_GetItemString(globals, "getSettings");
if (!gval) {
printf("ERROR: no getSettings function in constraint!\n");
/* free temp objects */
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
return;
}
/* Now for the fun part! Try and find the functions we need. */
if (PyFunction_Check(gval) ) {
retval = PyObject_CallFunction(gval, "O", idprop);
} else {
printf("ERROR: getSettings is supposed to be a function!\n");
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
return;
}
if (!retval) {
BPY_Err_Handle(con->text->id.name);
con->flag |= PYCON_SCRIPTERROR;
/* free temp objects */
ReleaseGlobalDictionary( globals );
Py_XDECREF( idprop );
return;
}
else {
/* clear globals */
ReleaseGlobalDictionary( globals );
/* free temp objects */
Py_XDECREF( idprop );
return;
}
}
/* Update function, it gets rid of pydrivers global dictionary, forcing
* BPY_pydriver_eval to recreate it. This function is used to force
* reloading the Blender text module "pydrivers.py", if available, so
* updates in it reach pydriver evaluation. */
void BPY_pydriver_update(void)
{
if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
Py_DECREF(bpy_pydriver_Dict);
bpy_pydriver_Dict = NULL;
}
return;
}
/* for depsgraph.c, runs py expr once to collect all refs. made
* to objects (self refs. to the object that owns the py driver
* are not allowed). */
struct Object **BPY_pydriver_get_objects(IpoDriver *driver)
{
/*if (!driver || !driver->ob || driver->name[0] == '\0')
return NULL;*/
/*PyErr_Clear();*/
/* clear the flag that marks invalid python expressions */
driver->flag &= ~IPO_DRIVER_FLAG_INVALID;
/* tell we're running a pydriver, so Get() functions know they need
* to add the requested obj to our list */
bpy_pydriver_running(1);
/* append driver owner object as the 1st ob in the list;
* we put it there to make sure it is not itself referenced in
* its pydriver expression */
bpy_pydriver_appendToList(driver->ob);
/* this will append any other ob referenced in expr (driver->name)
* or set the driver's error flag if driver's py expression fails */
BPY_pydriver_eval(driver);
bpy_pydriver_running(0); /* ok, we're done */
return bpy_pydriver_obArrayFromList(); /* NULL if eval failed */
}
/* This evals py driver expressions, 'expr' is a Python expression that
* should evaluate to a float number, which is returned. */
float BPY_pydriver_eval(IpoDriver *driver)
{
char *expr = NULL;
PyObject *retval, *floatval, *bpy_ob = NULL;
float result = 0.0f; /* default return */
int setitem_retval;
if (!driver) return result;
expr = driver->name; /* the py expression to be evaluated */
if (!expr || expr[0]=='\0') return result;
if (!bpy_pydriver_Dict) {
if (bpy_pydriver_create_dict() != 0) {
fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
return result;
}
}
if (driver->ob)
bpy_ob = Object_CreatePyObject(driver->ob);
if (!bpy_ob) {
Py_INCREF(Py_None);
bpy_ob = Py_None;
}
setitem_retval = EXPP_dict_set_item_str(bpy_pydriver_Dict, "self", bpy_ob);
if( !setup_armature_weakrefs()){
fprintf( stderr, "Oops - weakref dict setup\n");
return result;
}
retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict,
bpy_pydriver_Dict);
if (retval == NULL) {
return pydriver_error(driver);
}
floatval = PyNumber_Float(retval);
Py_DECREF(retval);
if (floatval == NULL)
return pydriver_error(driver);
result = (float)PyFloat_AsDouble(floatval);
Py_DECREF(floatval);
/* remove 'self', since this dict is also used by py buttons */
if (setitem_retval == 0) PyDict_DelItemString(bpy_pydriver_Dict, "self");
/* all fine, make sure the "invalid expression" flag is cleared */
driver->flag &= ~IPO_DRIVER_FLAG_INVALID;
return result;
}
/* Button Python Evaluation */
/* Python evaluation for gui buttons:
* users can write any valid Python expression (that evals to an int or float)
* inside Blender's gui number buttons and have them evaluated to their
* actual int or float value.
*
* The global dict used for pydrivers is also used here, so all imported
* modules for pydrivers (including the pydrivers.py Blender text) are
* available for button py eval, too. */
static int bpy_button_eval_error(char *expr) {
if (bpy_pydriver_oblist)
bpy_pydriver_freeList();
if (bpy_pydriver_Dict) { /* free the persistent global dict */
/* it's the same dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
Py_DECREF(bpy_pydriver_Dict);
bpy_pydriver_Dict = NULL;
}
fprintf(stderr, "\nError in button evaluation:\nThis is the failed Python expression:\n'%s'\n\n", expr);
PyErr_Print();
return -1;
}
int BPY_button_eval(char *expr, double *value)
{
PyObject *retval, *floatval;
if (!value || !expr || expr[0]=='\0') return -1;
*value = 0.0; /* default value */
if (!bpy_pydriver_Dict) {
if (bpy_pydriver_create_dict() != 0) {
fprintf(stderr,
"Button Python Eval error: couldn't create Python dictionary");
return -1;
}
}
if( !setup_armature_weakrefs()){
fprintf(stderr, "Oops - weakref dict\n");
return -1;
}
retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict,
bpy_pydriver_Dict);
if (retval == NULL) {
return bpy_button_eval_error(expr);
}
else {
floatval = PyNumber_Float(retval);
Py_DECREF(retval);
}
if (floatval == NULL)
return bpy_button_eval_error(expr);
else {
*value = (float)PyFloat_AsDouble(floatval);
Py_DECREF(floatval);
}
return 0; /* successful exit */
}
/*****************************************************************************/
/* ScriptLinks */
/*****************************************************************************/
/*****************************************************************************/
/* Description: */
/* Notes: Not implemented yet */
/*****************************************************************************/
void BPY_clear_bad_scriptlinks( struct Text *byebye )
{
/*
BPY_clear_bad_scriptlist(getObjectList(), byebye);
BPY_clear_bad_scriptlist(getLampList(), byebye);
BPY_clear_bad_scriptlist(getCameraList(), byebye);
BPY_clear_bad_scriptlist(getMaterialList(), byebye);
BPY_clear_bad_scriptlist(getWorldList(), byebye);
BPY_clear_bad_scriptlink(&scene_getCurrent()->id, byebye);
allqueue(REDRAWBUTSSCRIPT, 0);
*/
return;
}
/*****************************************************************************
* Description: Loop through all scripts of a list of object types, and
* execute these scripts.
* For the scene, only the current active scene the scripts are
* executed (if any).
*****************************************************************************/
void BPY_do_all_scripts( short event )
{
DoAllScriptsFromList( &( G.main->object ), event );
DoAllScriptsFromList( &( G.main->lamp ), event );
DoAllScriptsFromList( &( G.main->camera ), event );
DoAllScriptsFromList( &( G.main->mat ), event );
DoAllScriptsFromList( &( G.main->world ), event );
BPY_do_pyscript( &( G.scene->id ), event );
return;
}
/*****************************************************************************
* Description: Execute a Python script when an event occurs. The following
* events are possible: frame changed, load script and redraw.
* Only events happening to one of the following object types
* are handled: Object, Lamp, Camera, Material, World and
* Scene.
*****************************************************************************/
static ScriptLink *ID_getScriptlink( ID * id )
{
switch ( MAKE_ID2( id->name[0], id->name[1] ) ) {
case ID_OB:
return &( ( Object * ) id )->scriptlink;
case ID_LA:
return &( ( Lamp * ) id )->scriptlink;
case ID_CA:
return &( ( Camera * ) id )->scriptlink;
case ID_MA:
return &( ( Material * ) id )->scriptlink;
case ID_WO:
return &( ( World * ) id )->scriptlink;
case ID_SCE:
return &( ( Scene * ) id )->scriptlink;
default:
return NULL;
}
}
int BPY_has_onload_script( void )
{
ScriptLink *slink = &G.scene->scriptlink;
int i;
if( !slink || !slink->totscript )
return 0;
for( i = 0; i < slink->totscript; i++ ) {
if( ( slink->flag[i] == SCRIPT_ONLOAD )
&& ( slink->scripts[i] != NULL ) )
return 1;
}
return 0;
}
void BPY_do_pyscript( ID * id, short event )
{
ScriptLink *scriptlink;
if( !id ) return;
scriptlink = ID_getScriptlink( id );
if( scriptlink && scriptlink->totscript ) {
PyObject *dict;
PyObject *ret;
int index, during_slink = during_scriptlink( );
/* invalid scriptlinks (new .blend was just loaded), return */
if( during_slink < 0 )
return;
/* tell we're running a scriptlink. The sum also tells if this script
* is running nested inside another. Blender.Load needs this info to
* avoid trouble with invalid slink pointers. */
during_slink++;
disable_where_scriptlink( (short)during_slink );
/* set globals in Blender module to identify scriptlink */
EXPP_dict_set_item_str( g_blenderdict, "bylink", EXPP_incr_ret_True() );
EXPP_dict_set_item_str( g_blenderdict, "link",
GetPyObjectFromID( id ) );
EXPP_dict_set_item_str( g_blenderdict, "event",
PyString_FromString( event_to_name
( event ) ) );
if (event == SCRIPT_POSTRENDER) event = SCRIPT_RENDER;
for( index = 0; index < scriptlink->totscript; index++ ) {
if( ( scriptlink->flag[index] == event ) &&
( scriptlink->scripts[index] != NULL ) ) {
dict = CreateGlobalDictionary( );
ret = RunPython( ( Text * ) scriptlink->
scripts[index], dict );
ReleaseGlobalDictionary( dict );
if( !ret ) {
/* Failed execution of the script */
BPY_Err_Handle( scriptlink->
scripts[index]->name +
2 );
//BPY_end_python ();
//BPY_start_python ();
} else {
Py_DECREF( ret );
}
/* If a scriptlink has just loaded a new .blend file, the
* scriptlink pointer became invalid (see api2_2x/Blender.c),
* so we stop here. */
if( during_scriptlink( ) == -1 ) {
during_slink = 1;
break;
}
}
}
disable_where_scriptlink( (short)(during_slink - 1) );
/* cleanup bylink flag and clear link so PyObject
* can be released
*/
EXPP_dict_set_item_str( g_blenderdict, "bylink", EXPP_incr_ret_False() );
PyDict_SetItemString( g_blenderdict, "link", Py_None );
EXPP_dict_set_item_str( g_blenderdict, "event",
PyString_FromString( "" ) );
}
}
/* SPACE HANDLERS */
/* These are special script links that can be assigned to ScrArea's to
* (EVENT type) receive events sent to a given space (and use or ignore them) or
* (DRAW type) be called after the space is drawn, to draw anything on top of
* the space area. */
/* How to add space handlers to other spaces:
* - add the space event defines to DNA_scriptlink_types.h, as done for
* 3d view: SPACEHANDLER_VIEW3D_EVENT, for example;
* - add the new defines to Blender.SpaceHandler dictionary in Blender.c;
* - check space.c for how to call the event handlers;
* - check drawview.c for how to call the draw handlers;
* - check header_view3d.c for how to add the "Space Handler Scripts" menu.
* Note: DRAW handlers should be called with 'event = 0', chech drawview.c */
int BPY_has_spacehandler(Text *text, ScrArea *sa)
{
ScriptLink *slink;
int index;
if (!sa || !text) return 0;
slink = &sa->scriptlink;
for (index = 0; index < slink->totscript; index++) {
if (slink->scripts[index] && (slink->scripts[index] == (ID *)text))
return 1;
}
return 0;
}
int BPY_is_spacehandler(Text *text, char spacetype)
{
TextLine *tline = text->lines.first;
unsigned short type = 0;
if (tline && (tline->len > 10)) {
char *line = tline->line;
/* Expected format: # SPACEHANDLER.SPACE.TYPE
* Ex: # SPACEHANDLER.VIEW3D.DRAW
* The actual checks are forgiving, so slight variations also work. */
if (line && line[0] == '#' && strstr(line, "HANDLER")) {
line++; /* skip '#' */
/* only done for 3D View right now, trivial to add for others: */
switch (spacetype) {
case SPACE_VIEW3D:
if (strstr(line, "3D")) { /* VIEW3D, 3DVIEW */
if (strstr(line, "DRAW")) type = SPACEHANDLER_VIEW3D_DRAW;
else if (strstr(line, "EVENT")) type = SPACEHANDLER_VIEW3D_EVENT;
}
break;
}
}
}
return type; /* 0 if not a space handler */
}
int BPY_del_spacehandler(Text *text, ScrArea *sa)
{
ScriptLink *slink;
int i, j;
if (!sa || !text) return -1;
slink = &sa->scriptlink;
if (slink->totscript < 1) return -1;
for (i = 0; i < slink->totscript; i++) {
if (text == (Text *)slink->scripts[i]) {
for (j = i; j < slink->totscript - 1; j++) {
slink->flag[j] = slink->flag[j+1];
slink->scripts[j] = slink->scripts[j+1];
}
slink->totscript--;
/* like done in buttons_script.c we just free memory
* if all slinks have been removed -- less fragmentation,
* these should be quite small arrays */
if (slink->totscript == 0) {
if (slink->scripts) MEM_freeN(slink->scripts);
if (slink->flag) MEM_freeN(slink->flag);
break;
}
}
}
return 0;
}
int BPY_add_spacehandler(Text *text, ScrArea *sa, char spacetype)
{
unsigned short handlertype;
if (!sa || !text) return -1;
handlertype = (unsigned short)BPY_is_spacehandler(text, spacetype);
if (handlertype) {
ScriptLink *slink = &sa->scriptlink;
void *stmp, *ftmp;
unsigned short space_event = SPACEHANDLER_VIEW3D_EVENT;
/* extend slink */
stmp= slink->scripts;
slink->scripts= MEM_mallocN(sizeof(ID*)*(slink->totscript+1),
"spacehandlerscripts");
ftmp= slink->flag;
slink->flag= MEM_mallocN(sizeof(short*)*(slink->totscript+1),
"spacehandlerflags");
if (slink->totscript) {
memcpy(slink->scripts, stmp, sizeof(ID*)*(slink->totscript));
MEM_freeN(stmp);
memcpy(slink->flag, ftmp, sizeof(short)*(slink->totscript));
MEM_freeN(ftmp);
}
switch (spacetype) {
case SPACE_VIEW3D:
if (handlertype == 1) space_event = SPACEHANDLER_VIEW3D_EVENT;
else space_event = SPACEHANDLER_VIEW3D_DRAW;
break;
default:
break;
}
slink->scripts[slink->totscript] = (ID *)text;
slink->flag[slink->totscript]= space_event;
slink->totscript++;
slink->actscript = slink->totscript;
}
return 0;
}
int BPY_do_spacehandlers( ScrArea *sa, unsigned short event,
unsigned short space_event )
{
ScriptLink *scriptlink;
int retval = 0;
if (!sa || !(G.f & G_DOSCRIPTLINKS)) return 0;
scriptlink = &sa->scriptlink;
if (scriptlink->totscript > 0) {
PyObject *dict;
PyObject *ret;
int index, during_slink = during_scriptlink();
/* invalid scriptlinks (new .blend was just loaded), return */
if (during_slink < 0) return 0;
/* tell we're running a scriptlink. The sum also tells if this script
* is running nested inside another. Blender.Load needs this info to
* avoid trouble with invalid slink pointers.
* Update (test): allow EVENT space handlers to call file/image selectors,
* still disabled for DRAW space handlers: */
if (event == 0) { /* event = 0: DRAW space handler */
during_slink++;
disable_where_scriptlink( (short)during_slink );
}
/* set globals in Blender module to identify space handler scriptlink */
EXPP_dict_set_item_str(g_blenderdict, "bylink", EXPP_incr_ret_True());
/* unlike normal scriptlinks, here Blender.link is int (space event type) */
EXPP_dict_set_item_str(g_blenderdict, "link", PyInt_FromLong(space_event));
/* note: DRAW space_events set event to 0 */
EXPP_dict_set_item_str(g_blenderdict, "event", PyInt_FromLong(event));
/* now run all assigned space handlers for this space and space_event */
for( index = 0; index < scriptlink->totscript; index++ ) {
/* for DRAW handlers: */
if (event == 0) {
glPushAttrib(GL_ALL_ATTRIB_BITS);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
}
if( ( scriptlink->flag[index] == space_event ) &&
( scriptlink->scripts[index] != NULL ) ) {
dict = CreateGlobalDictionary();
ret = RunPython( ( Text * ) scriptlink->scripts[index], dict );
ReleaseGlobalDictionary( dict );
if (!ret) { /* Failed execution of the script */
BPY_Err_Handle( scriptlink->scripts[index]->name+2 );
} else {
Py_DECREF(ret);
/* an EVENT type (event != 0) script can either accept an event or
* ignore it:
* if the script sets Blender.event to None it accepted it;
* otherwise the space's event handling callback that called us
* can go on processing the event */
if (event && (PyDict_GetItemString(g_blenderdict,"event") == Py_None))
retval = 1; /* event was swallowed */
}
/* If a scriptlink has just loaded a new .blend file, the
* scriptlink pointer became invalid (see api2_2x/Blender.c),
* so we stop here. */
if( during_scriptlink( ) == -1 ) {
during_slink = 1;
if (event == 0) glPopAttrib();
break;
}
}
/* for DRAW handlers: */
if (event == 0) {
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
disable_where_scriptlink( (short)(during_slink - 1) );
}
}
EXPP_dict_set_item_str(g_blenderdict, "bylink", EXPP_incr_ret_False());
PyDict_SetItemString(g_blenderdict, "link", Py_None );
EXPP_dict_set_item_str(g_blenderdict, "event", PyString_FromString(""));
}
/* retval:
* space_event is of type EVENT:
* 0 - event was returned,
* 1 - event was processed;
* space_event is of type DRAW:
* 0 always */
return retval;
}
/*****************************************************************************
* Description:
* Notes:
*****************************************************************************/
void BPY_free_scriptlink( struct ScriptLink *slink )
{
if( slink->totscript ) {
if( slink->flag ) {
MEM_freeN( slink->flag );
slink->flag= NULL;
}
if( slink->scripts ) {
MEM_freeN( slink->scripts );
slink->scripts= NULL;
}
}
return;
}
static int CheckAllSpaceHandlers(Text *text)
{
bScreen *screen;
ScrArea *sa;
ScriptLink *slink;
int fixed = 0;
for (screen = G.main->screen.first; screen; screen = screen->id.next) {
for (sa = screen->areabase.first; sa; sa = sa->next) {
slink = &sa->scriptlink;
if (!slink->totscript) continue;
if (BPY_del_spacehandler(text, sa) == 0) fixed++;
}
}
return fixed;
}
static int CheckAllScriptsFromList( ListBase * list, Text * text )
{
ID *id;
ScriptLink *scriptlink;
int index;
int fixed = 0;
id = list->first;
while( id != NULL ) {
scriptlink = ID_getScriptlink( id );
if( scriptlink && scriptlink->totscript ) {
for( index = 0; index < scriptlink->totscript; index++) {
if ((Text *)scriptlink->scripts[index] == text) {
scriptlink->scripts[index] = NULL;
fixed++;
}
}
}
id = id->next;
}
return fixed;
}
/* When a Text is deleted, we need to unlink it from eventual scriptlinks */
int BPY_check_all_scriptlinks( Text * text )
{
int fixed = 0;
fixed += CheckAllScriptsFromList( &( G.main->object ), text );
fixed += CheckAllScriptsFromList( &( G.main->lamp ), text );
fixed += CheckAllScriptsFromList( &( G.main->camera ), text );
fixed += CheckAllScriptsFromList( &( G.main->mat ), text );
fixed += CheckAllScriptsFromList( &( G.main->world ), text );
fixed += CheckAllScriptsFromList( &( G.main->scene ), text );
fixed += CheckAllSpaceHandlers(text);
return fixed;
}
/*****************************************************************************
* Description:
* Notes:
*****************************************************************************/
void BPY_copy_scriptlink( struct ScriptLink *scriptlink )
{
void *tmp;
if( scriptlink->totscript ) {
tmp = scriptlink->scripts;
scriptlink->scripts =
MEM_mallocN( sizeof( ID * ) * scriptlink->totscript,
"scriptlistL" );
memcpy( scriptlink->scripts, tmp,
sizeof( ID * ) * scriptlink->totscript );
tmp = scriptlink->flag;
scriptlink->flag =
MEM_mallocN( sizeof( short ) * scriptlink->totscript,
"scriptlistF" );
memcpy( scriptlink->flag, tmp,
sizeof( short ) * scriptlink->totscript );
}
return;
}
/****************************************************************************
* Description:
* Notes: Not implemented yet
*****************************************************************************/
int BPY_call_importloader( char *name )
{ /* XXX Should this function go away from Blender? */
printf( "In BPY_call_importloader(name=%s)\n", name );
return ( 0 );
}
/*****************************************************************************
* Private functions
*****************************************************************************/
/*****************************************************************************
* Description: This function executes the python script passed by text.
* The Python dictionary containing global variables needs to
* be passed in globaldict.
*****************************************************************************/
PyObject *RunPython( Text * text, PyObject * globaldict )
{
char *buf = NULL;
/* The script text is compiled to Python bytecode and saved at text->compiled
* to speed-up execution if the user executes the script multiple times */
if( !text->compiled ) { /* if it wasn't already compiled, do it now */
buf = txt_to_buf( text );
text->compiled =
Py_CompileString( buf, GetName( text ),
Py_file_input );
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
BPY_free_compiled_text( text );
return NULL;
}
}
return PyEval_EvalCode( text->compiled, globaldict, globaldict );
}
/*****************************************************************************
* Description: This function returns the value of the name field of the
* given Text struct.
*****************************************************************************/
char *GetName( Text * text )
{
return ( text->id.name + 2 );
}
/*****************************************************************************
* Description: This function creates a new Python dictionary object.
*****************************************************************************/
PyObject *CreateGlobalDictionary( void )
{
PyObject *dict = PyDict_New( );
PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins( ) );
EXPP_dict_set_item_str( dict, "__name__",
PyString_FromString( "__main__" ) );
return dict;
}
/*****************************************************************************
* Description: This function deletes a given Python dictionary object.
*****************************************************************************/
void ReleaseGlobalDictionary( PyObject * dict )
{
PyDict_Clear( dict );
Py_DECREF( dict ); /* Release dictionary. */
return;
}
/***************************************************************************
* Description: This function runs all scripts (if any) present in the
* list argument. The event by which the function has been
* called, is passed in the event argument.
*****************************************************************************/
void DoAllScriptsFromList( ListBase * list, short event )
{
ID *id;
id = list->first;
while( id != NULL ) {
BPY_do_pyscript( id, event );
id = id->next;
}
return;
}
PyObject *importText( char *name )
{
Text *text;
char *txtname;
char *buf = NULL;
int namelen = strlen( name );
txtname = malloc( namelen + 3 + 1 );
if( !txtname )
return NULL;
memcpy( txtname, name, namelen );
memcpy( &txtname[namelen], ".py", 4 );
text = ( Text * ) & ( G.main->text.first );
while( text ) {
if( !strcmp( txtname, GetName( text ) ) )
break;
text = text->id.next;
}
if( !text ) {
free( txtname );
return NULL;
}
if( !text->compiled ) {
buf = txt_to_buf( text );
text->compiled =
Py_CompileString( buf, GetName( text ),
Py_file_input );
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
PyErr_Print( );
BPY_free_compiled_text( text );
free( txtname );
return NULL;
}
}
free( txtname );
return PyImport_ExecCodeModule( name, text->compiled );
}
static PyMethodDef bimport[] = {
{"blimport", blender_import, METH_VARARGS, "our own import"}
};
PyObject *blender_import( PyObject * self, PyObject * args )
{
PyObject *exception, *err, *tb;
char *name;
PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
PyObject *m;
if( !PyArg_ParseTuple( args, "s|OOO:bimport",
&name, &globals, &locals, &fromlist ) )
return NULL;
m = PyImport_ImportModuleEx( name, globals, locals, fromlist );
if( m )
return m;
else
PyErr_Fetch( &exception, &err, &tb ); /*restore for probable later use */
m = importText( name );
if( m ) { /* found module, ignore above exception */
PyErr_Clear( );
Py_XDECREF( exception );
Py_XDECREF( err );
Py_XDECREF( tb );
printf( "imported from text buffer...\n" );
} else {
PyErr_Restore( exception, err, tb );
}
return m;
}
void init_ourImport( void )
{
PyObject *m, *d;
PyObject *import = PyCFunction_New( bimport, NULL );
m = PyImport_AddModule( "__builtin__" );
d = PyModule_GetDict( m );
EXPP_dict_set_item_str( d, "__import__", import );
}
/*
* find in-memory module and recompile
*/
static PyObject *reimportText( PyObject *module )
{
Text *text;
char *txtname;
char *name;
char *buf = NULL;
/* get name, filename from the module itself */
txtname = PyModule_GetFilename( module );
name = PyModule_GetName( module );
if( !txtname || !name)
return NULL;
/* look up the text object */
text = ( Text * ) & ( G.main->text.first );
while( text ) {
if( !strcmp( txtname, GetName( text ) ) )
break;
text = text->id.next;
}
/* uh-oh.... didn't find it */
if( !text )
return NULL;
/* if previously compiled, free the object */
/* (can't see how could be NULL, but check just in case) */
if( text->compiled ){
Py_DECREF( (PyObject *)text->compiled );
}
/* compile the buffer */
buf = txt_to_buf( text );
text->compiled = Py_CompileString( buf, GetName( text ),
Py_file_input );
MEM_freeN( buf );
/* if compile failed.... return this error */
if( PyErr_Occurred( ) ) {
PyErr_Print( );
BPY_free_compiled_text( text );
return NULL;
}
/* make into a module */
return PyImport_ExecCodeModule( name, text->compiled );
}
/*
* our reload() module, to handle reloading in-memory scripts
*/
static PyObject *blender_reload( PyObject * self, PyObject * args )
{
PyObject *exception, *err, *tb;
PyObject *module = NULL;
PyObject *newmodule = NULL;
/* check for a module arg */
if( !PyArg_ParseTuple( args, "O:breload", &module ) )
return NULL;
/* try reimporting from file */
newmodule = PyImport_ReloadModule( module );
if( newmodule )
return newmodule;
/* no file, try importing from memory */
PyErr_Fetch( &exception, &err, &tb ); /*restore for probable later use */
newmodule = reimportText( module );
if( newmodule ) { /* found module, ignore above exception */
PyErr_Clear( );
Py_XDECREF( exception );
Py_XDECREF( err );
Py_XDECREF( tb );
} else
PyErr_Restore( exception, err, tb );
return newmodule;
}
static PyMethodDef breload[] = {
{"blreload", blender_reload, METH_VARARGS, "our own reload"}
};
void init_ourReload( void )
{
PyObject *m, *d;
PyObject *reload = PyCFunction_New( breload, NULL );
m = PyImport_AddModule( "__builtin__" );
d = PyModule_GetDict( m );
EXPP_dict_set_item_str( d, "reload", reload );
}
|