File: vtk.lisp

package info (click to toggle)
maxima 5.47.0-9
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 193,104 kB
  • sloc: lisp: 434,678; fortran: 14,665; tcl: 10,990; sh: 4,577; makefile: 2,763; ansic: 447; java: 328; python: 262; perl: 201; xml: 60; awk: 28; sed: 15; javascript: 2
file content (3140 lines) | stat: -rw-r--r-- 141,890 bytes parent folder | download | duplicates (2)
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
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
;;;                 COPYRIGHT NOTICE
;;;  
;;;  Copyright (C) 2012-2018 Mario Rodriguez Riotorto
;;;  
;;;  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. 
;;;  
;;;  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 at
;;;  http://www.gnu.org/copyleft/gpl.html

;;; This is a maxima-vtk interface.

;;; For examples, visit
;;; http://tecnostats.net/Maxima/vtk

;;; For questions, suggestions, bugs and the like, feel free
;;; to contact me at
;;; mario @@@ edu DOT xunta DOT es


;;; AUXILIARY FUNCTIONS

;; Global variables
(defvar *vtk-appenddata-counter* 0)
(defvar *vtk-extract-counter* 0)
(defvar *vtk-outline-counter* 0)
(defvar *vtk-polydatamapper-counter* 0)
(defvar *vtk-outlineactor-counter* 0)
(defvar *vtk-textproperty-counter* 0)
(defvar *vtk-cubeaxesactor2d-counter* 0)
(defvar *vtk-camera-counter* 0)
(defvar *vtk-renderer-counter* 0)
(defvar *vtk-source-counter* 0)
(defvar *vtk-mapper-counter* 0)
(defvar *vtk-actor-counter* 0)
(defvar *vtk-labelactor-counter* 0)
(defvar *vtk-trans-counter* 0)
(defvar *vtk-filter-counter* 0)
(defvar *vtk-floatarray-counter* 0)
(defvar *vtk-data-file-counter* 0)
(defvar *vtk-points-counter* 0)
(defvar *vtk-glyphpoints-counter* 0)
(defvar *vtk-polydata-counter* 0)
(defvar *vtk-cellarray-counter* 0)
(defvar *vtk-solidsource-counter* 0)
(defvar *vtk-triangle-counter* 0)
(defvar *vtk-label-counter* 0)
(defvar *vtk-chart-counter* 0)
(defvar *vtk-table-counter* 0)
(defvar *vtk-arrayX-counter* 0)
(defvar *vtk-arrayY-counter* 0)
(defvar *vtk-2dkey-counter* 0)
(defvar *vtk-isolines-counter* 0)
(defvar *lookup-tables* nil)
(defvar *unitscale-already-defined* nil)
(defparameter *enhanced3d-or-isolines-code* (make-hash-table))

(defun get-appenddata-name ()
  (format nil "appenddata~a" (incf *vtk-appenddata-counter*)))

(defun get-extract-name ()
  (format nil "extract~a" (incf *vtk-extract-counter*)))

(defun get-outline-name ()
  (format nil "outline~a" (incf *vtk-outline-counter*)))

(defun get-outlineactor-name ()
  (format nil "outlineactor~a" (incf *vtk-outlineactor-counter*)))

(defun get-textproperty-name ()
  (format nil "textproperty~a" (incf *vtk-textproperty-counter*)))

(defun get-cubeaxesactor2d-name ()
  (format nil "cubeaxesactor2d~a" (incf *vtk-cubeaxesactor2d-counter*)))

(defun get-camera-name ()
  (format nil "camera~a" (incf *vtk-camera-counter*)))

(defun get-renderer-name ()
  (format nil "renderer~a" (incf *vtk-renderer-counter*)))

(defun get-source-name ()
  (format nil "source~a" (incf *vtk-source-counter*)))

(defun get-mapper-name ()
  (format nil "mapper~a" (incf *vtk-mapper-counter*)))

(defun get-actor-name ()
  (format nil "actor~a" (incf *vtk-actor-counter*)))

(defun get-labelactor-name ()
  (format nil "labelactor~a" (incf *vtk-labelactor-counter*)))

(defun get-trans-name ()
  (format nil "trans~a" (incf *vtk-trans-counter*)))

(defun get-filter-name ()
  (format nil "filter~a" (incf *vtk-filter-counter*)))

(defun get-floatarray-name ()
  (format nil "floatarray~a" (incf *vtk-floatarray-counter*)))

(defun get-data-file-name ()
  (format nil "data~a.vtk" (incf *vtk-data-file-counter*)))

(defun get-points-name ()
  (format nil "points~a" (incf *vtk-points-counter*)))

(defun get-glyphpoints-name ()
  (format nil "glyphpoints~a" (incf *vtk-glyphpoints-counter*)))

(defun get-polydata-name ()
  (format nil "polydata~a" (incf *vtk-polydata-counter*)))

(defun get-cellarray-name ()
  (format nil "cellarray~a" (incf *vtk-cellarray-counter*)))

(defun get-polydatamapper-name ()
  (format nil "polydatamapper~a" (incf *vtk-polydatamapper-counter*)))

(defun get-solidsource-name ()
  (format nil "solidsource~a" (incf *vtk-solidsource-counter*)))

(defun get-triangle-name ()
  (format nil "triangle~a" (incf *vtk-triangle-counter*)))

(defun get-label-name ()
  (format nil "label~a" (incf *vtk-label-counter*)))

(defun get-chart-name ()
  (format nil "chart~a" (incf *vtk-chart-counter*)))

(defun get-table-name ()
  (format nil "table~a" (incf *vtk-table-counter*)))

(defun get-arrayX-name ()
  (format nil "arrayX~a" (incf *vtk-arrayX-counter*)))

(defun get-arrayY-name ()
  (format nil "arrayY~a" (incf *vtk-arrayY-counter*)))

(defun get-isolines-name ()
  (format nil "isolines~a" (incf *vtk-isolines-counter*)))

(defun scenebounds ()
  (let ((xrange (get-option '$xrange))
        (yrange (get-option '$yrange))
        (zrange (get-option '$zrange))
        code)
    (setf code
      (concatenate 'string
        (if xrange
          (format nil "mib[0]=~a~%mxb[1]=~a~%" (car xrange) (cadr xrange))
          "")
        (if yrange
          (format nil "mib[2]=~a~%mxb[3]=~a~%" (car yrange) (cadr yrange))
          "")
        (if zrange
          (format nil "mib[4]=~a~%mxb[5]=~a~%" (car zrange) (cadr zrange))
          "")))
    (format nil "~a~%~a~%~a~%~a~%~a~%~a~%~a~%~a~a~%~%"
      "if sys.version_info[0] < 3:"
      "    trb = zip(*bounds)"
      "else:"
      "    trb = list(zip(*bounds))"
      "mib = [min(i) for i in trb]"
      "mxb = [max(i) for i in trb]"
      "ranges = vtk.vtkBox()"
      code
      "ranges.SetBounds(mib[0],mxb[1],mib[2],mxb[3],mib[4],mxb[5])") ))

(defun vtkappendpolydata-code (an fe fl)
  (let ((str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)))
    (when (> (hash-table-count *enhanced3d-or-isolines-code*) 0)
      (format str (format nil "~V@{~a~:*~}~%" 18 "~a~%")
              "def rescalearray( pts, arr ):"
              "   mini = 1.0"
              "   maxi = 0.0"
              "   n = arr.GetNumberOfTuples()"
              "   for i in range(0, n):"
              "       v = pts.GetPoint(i)"
              "       f = arr.GetValue(i)"
              "       if (v[0] >= mib[0] and v[0] <= mxb[1] and"
              "           v[1] >= mib[2] and v[1] <= mxb[3] and"
              "           v[2] >= mib[4] and v[2] <= mxb[5]):"
              "           if f < mini:"
              "              mini = f"
              "           if f > maxi:"
              "              maxi = f"
              "   if maxi > mini:"
              "      for i in range(0, n):"
              "          arr.SetValue(i, (arr.GetValue(i)-mini)/(maxi-mini))"
              "   return;" ))
    (format str "~a=vtk.vtkAppendPolyData()~%" an)
    (loop for n from fe to *vtk-extract-counter* do
      (format str "~%extract~a.SetImplicitFunction(ranges)~%" n)
      (format str "extract~a.SetInputConnection(filter~a.GetOutputPort())~%" n n)
      (format str "mapper~a.SetInputConnection(extract~a.GetOutputPort())~%" n n)
      (when (gethash n *enhanced3d-or-isolines-code*)
        (format str "~a" (gethash n *enhanced3d-or-isolines-code*))
        (remhash n *enhanced3d-or-isolines-code*))
      (format str "actor~a.SetMapper(mapper~a)~%" n n)
      (format str "~a.AddInputConnection(extract~a.GetOutputPort())~%" an n))
    (loop for n from fl to *vtk-label-counter* do
      (format str "~a.AddInputConnection(label~a.GetOutputPort())~%" an n))
    (format str "~%~a.Update()~%~%" an)
    str))

(defun vtkoutlinefilter-code (on an)
  (concatenate 'string
    (format nil "~a=vtk.vtkOutlineFilter()~%" on)
    (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" on an)))

(defun vtkpolydatamapper-code (mn fn con)
  (concatenate 'string
    (format nil "~a=vtk.vtkPolyDataMapper()~%" mn)
    (if con
      (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" mn fn)
      "") ))

;; Isolines mapper
(defun vtkpolydatamapper-isoline-code (mn sn fn)
  (concatenate 'string
    (format nil "~a=vtk.vtkPolyDataMapper()~%" mn)
    (format nil "~a.GetPointData().SetActiveScalars(\"name~a\")~%" sn fn)
    (format nil "~a.ScalarVisibilityOn()~%" mn)  ))

(defun vtkextractpolydatageometry-code (en cell poin)
  (concatenate 'string
    (format nil "~a=vtk.vtkExtractPolyDataGeometry()~%" en)
    (if cell
      (format nil "~a.ExtractBoundaryCellsOn()~%" en)
      (format nil "~a.ExtractBoundaryCellsOff()~%" en))
    (if poin
      (format nil "~a.PassPointsOn()~%" en)
      (format nil "~a.PassPointsOff()~%" en))  ))

(defun vtktextproperty-code (tn)
  (concatenate 'string
    (format nil "~a=vtk.vtkTextProperty()~%" tn)
    (format nil "~a.SetColor(0,0,0)~%" tn)))

(defun vtkcubeaxesActor2d-code (can adn tn)
  (concatenate 'string
    (format nil "~a=vtk.vtkCubeAxesActor2D()~%" can)
    (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" can adn)
    (format nil "~a.SetLabelFormat(\"%6.4g\")~%" can)
    (format nil "~a.SetFlyModeToOuterEdges()~%" can)
    (format nil "~a.SetFontFactor(0.8)~%" can)
    (format nil "~a.SetAxisTitleTextProperty(~a)~%" can tn)
    (format nil "~a.SetAxisLabelTextProperty(~a)~%" can tn)
    (format nil "~a.SetXLabel(\"~a\")~%"   can (get-option '$xlabel))
    (format nil "~a.SetYLabel(\"~a\")~%"   can (get-option '$ylabel))
    (format nil "~a.SetZLabel(\"~a\")~%~%" can (get-option '$zlabel)) ))

(defun vtkrenderer3d-code (rn an on bgcol cn rv rh fa fl)
  (let* ((k 0.0174532925199433) ; %pi/180
         (rvk (* k rv))
         (rhk (* k rh))
         (x (* ($sin rvk) ($sin rhk)))
         (y (- (* ($sin rvk) ($cos rhk))))
         (z ($cos rvk))
         (colist (hex-to-numeric-list bgcol))
         (str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)) )
    (format str "~a=vtk.vtkCamera()~%" cn)
    (format str "~a.SetPosition(~a,~a,~a)~%" cn x y z)
    (format str "~a=vtk.vtkRenderer()~%" rn)
    (format str "~a.SetBackground(~a,~a,~a)~%" rn (first colist) (second colist) (third colist))
    (loop for n from fa to *vtk-actor-counter* do
      (format str "~a.AddActor(actor~a)~%" rn n))
    (loop for n from fl to *vtk-labelactor-counter* do
      (format str "~a.AddActor(labelactor~a)~%" rn n))
    (format str "~a.SetCamera(~a.GetActiveCamera())~%" an rn)
    (when (get-option '$axis_3d)
      (format str "~a.AddActor(~a)~%" rn on)     ; add box
      (format str "~a.AddViewProp(~a)~%" rn an)) ; add axes tics
    (format str "~a.SetActiveCamera(~a)~%" rn cn)
    (format str "~a.ResetCamera()~%~%" rn)
    str))

(defun vtkrenderer2d-code (cn rn)
  (let ((colist (hex-to-numeric-list (get-option '$background_color)))
        (xrange (get-option '$xrange))
        (yrange (get-option '$yrange))
        (str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)) )
    (when yrange
      (format str "~a.GetAxis(0).SetBehavior(1)~%" cn)
      (format str "~a.GetAxis(0).SetRange(~a,~a)~%~%" cn (first yrange) (second yrange)) )
    (when xrange
      (format str "~a.GetAxis(1).SetBehavior(1)~%" cn)
      (format str "~a.GetAxis(1).SetRange(~a,~a)~%~%" cn (first xrange) (second xrange)) )
    (format str "scene~a=vtk.vtkContextScene()~%scene~a.AddItem(~a)~%" cn cn cn)
    (format str "actor~a=vtk.vtkContextActor()~%actor~a.SetScene(scene~a)~%" cn cn cn)
    (format str "~a.SetShowLegend(~a)~%"
      cn
      (if (> *vtk-2dkey-counter* 0) 1 0))
    (format str "~a.GetAxis(0).SetTitle(\"~a\")~%" cn (get-option '$ylabel))
    (format str "~a.GetAxis(1).SetTitle(\"~a\")~%" cn (get-option '$xlabel))
    (when (get-option '$logx)
      (format str "~a.GetAxis(1).SetLogScale(1)~%" cn))
    (when (get-option '$logy)
      (format str "~a.GetAxis(0).SetLogScale(1)~%" cn))
    (let ((pos (get-option '$key_pos))
          vp hp)
      (when pos
        (setf pos (rest (mfunction-call $split pos)))
        (setf vp (first  pos)
              hp (second pos))
        (format str "~a.GetLegend().SetVerticalAlignment(~a)~%"
          cn
          (cond
            ((string= vp "top")    3)
            ((string= vp "center") 1)
            ((string= vp "bottom") 4)))
        (format str "~a.GetLegend().SetHorizontalAlignment(~a)~%"
          cn
          (cond
            ((string= hp "left")   0)
            ((string= hp "center") 1)
            ((string= hp "right")  2)))  ))
    (format str "~a=vtk.vtkRenderer()~%" rn)
    (format str "~a.SetBackground(~a,~a,~a)~%" rn (first colist) (second colist) (third colist))
    (format str "~a.AddActor(actor~a)~%" rn cn)
    (format str "scene~a.SetRenderer(~a)~%" cn rn)
    str))

(defun vtkchartxy-code (cn)
  (let ((str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)) )
    (format str "~a = vtk.vtkChartXY()~%" cn)
    (format str "~a.GetAxis(0).SetGridVisible(~a)~%"
       cn
       (case (first (get-option '$grid))
         (0 0)
         (otherwise 1))  )
    (format str "~a.GetAxis(1).SetGridVisible(~a)~%~%"
       cn
       (case (second (get-option '$grid))
         (0 0)
         (otherwise 1))  )
    str))

(defun vtkcellarray-code (cn pn celldim ind)
  (let ((str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)))
    (format str "~a=vtk.vtkCellArray()~%" cn)
    (loop for c in ind do
      (format str "~a.InsertNextCell(~a)~%" cn (length c))
      (loop for i in c do
        (format str "~a.InsertCellPoint(~a)~%" cn i)) )
    (format str "~a.~a(~a)~%"
       pn
       (case celldim
        (0         "SetVerts")
        (1         "SetLines")
        (otherwise "SetPolys"))
       cn)
    str ))

(defun vtkfloatarray-code (fan sn values &optional (addarr t))
  (let ((n (length values))
        (str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)))
    (format str "~a=vtk.vtkFloatArray()~%" fan)
    (loop for k from 0 below n do
      (format str "~a.InsertNextValue(~a)~%" fan (aref values k)))
    (format str "~a.SetName(\"name~a\")~%" fan fan)
    (format str "~a.GetPointData().~a(~a)~%"
       sn
       (if addarr
          "AddArray"
          "SetScalars")
       fan)
    str))

(defun vtkglyph3d-code (fn sn pdn)
  (concatenate 'string
    (format nil "~a=vtk.vtkGlyph3D()~%" fn)
    (format nil "~a.SetInputData(~a)~%" fn sn)
    (format nil "~a.~a~%" fn pdn)
    (format nil "~a.ScalingOff()~%" fn)))

(defun vtkpoints-code (pn sn x y z)
  (let ((n (length x))
        (str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0)))
    (format str "~a=vtk.vtkPoints()~%" pn)
    (format str "~a.SetNumberOfPoints(~a)~%" pn n)
    (loop for k from 0 below n do
      (format str "~a.InsertPoint(~a,~a,~a,~a)~%" pn k (aref x k) (aref y k) (aref z k)) )
    (when (not (null sn))
      (format str "~a.SetPoints(~a)~%" sn pn))
    str))

(defun vtktransform-code (tn)
  (format nil "~a=vtk.vtkTransform()~%" tn))

(defun vtktransformfilter-code (fn sn tn)
  (concatenate 'string
    (format nil "~a=vtk.vtkTransformFilter()~%" fn)
    (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" fn sn)
    (format nil "~a.SetTransform(~a)~%" fn tn) ))

(defun vtktransformpolydatafilter-code (fn sn tn ds)
  (concatenate 'string
    (format nil "~a=vtk.vtkTransformPolyDataFilter()~%" fn)
    (if ds
      (format nil "~a.SetInputData(~a)~%" fn sn)
      (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" fn sn))
    (format nil "~a.SetTransform(~a)~%" fn tn) ))

(defun vtkactor-code (an mn col op lw ws)
  (let ((colist (hex-to-numeric-list col)))
    (concatenate 'string
      (format nil "~a=vtk.vtkActor()~%" an)
      (if mn
        (format nil "~a.SetMapper(~a)~%" an mn)
        "")
      (format nil "~a.GetProperty().SetColor(~a,~a,~a)~%"
              an
              (first  colist)
              (second colist)
              (third  colist))
      (format nil "~a.GetProperty().SetOpacity(~a)~%" an op)
      (format nil "~a.GetProperty().SetLineWidth(~a)~%" an lw)
      (if (not (null ws))
        (format nil "~a.GetProperty().EdgeVisibilityOn()~%~a.GetProperty().SetEdgeColor(0,0,0)~%" an an)
        (format nil "~%")) )))

;; Isolines actor
(defun vtkactor-isoline-code (an lw)
  (concatenate 'string
    (format nil "~a=vtk.vtkActor()~%" an)
    (format nil "# ~a.GetProperty().SetColor(1.0,0.0,0.0)~%" an)
    (format nil "~a.GetProperty().SetLineWidth(~a)~%" an lw) ))

;; Glyph actor
(defun vtkactor-glyph-code (an col op)
  (let ((colist (hex-to-numeric-list col)))
    (concatenate 'string
      (format nil "~a=vtk.vtkActor()~%" an)
      (format nil "~a.GetProperty().SetColor(~a,~a,~a)~%"
              an
              (first  colist)
              (second colist)
              (third  colist))
      (format nil "~a.GetProperty().SetOpacity(~a)~%" an op) )))

(defun vtktubefilter-code (tn fn lt)
  (concatenate 'string
    (format nil "~a=vtk.vtkTubeFilter()~%" tn)
    (format nil "~a.SetInputConnection(~a.GetOutputPort())~%" tn fn)
    (format nil "~a.SetNumberOfSides(~a)~%" tn (- lt))
    (format nil "~a.SetRadius(~a)~%" tn (get-option '$line_width)) ))


(defun vtkContourFilter-code (in fn)
  (let ((str (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        (contours (get-option '$isolines_levels)))
    (format str "~a=vtk.vtkContourFilter()~%" in)
    (format str "~a.SetInputConnection(~a.GetOutputPort())~%" in fn)
    (cond
      ((numberp contours) ; number of isolines
         (format str "~a.GenerateValues(~a,~a.GetOutput().GetScalarRange())~%" in contours fn))
      ((and (stringp contours)
            (search "incremental" contours)); list with min, step, max
         (format str "u = [~a]~%" (subseq contours 12))
         (format str "~a.GenerateValues(int(round((u[2]-u[0]) / u[1])),u[0],u[2])~%" in) )
      (t ; set of user specified contour values 
         (format str "u = [~a]~%" (subseq contours 9))
         (format str "for i in range(0, len(u)):~%")
         (format str "   ~a.SetValue(i,u[i])~%" in)  ))
    str) )


(defun vtkrendererwindow-code (ns)
  (let* ((dim  (get-option '$dimensions))
         (ncol (get-option '$columns))
         (str (make-array 0 
                :element-type 'character 
                :adjustable t 
                :fill-pointer 0))
         x1 y1 x2 y2
         (alloc (reverse *allocations*))
         (nilcounter 0)
         nrow dx dy thisalloc)
    (setf nrow (ceiling (/ (count nil alloc) ncol)))
    (when (> nrow 0)
      (setf dx (/ 1.0 ncol)
            dy (/ 1.0 nrow)))
    ; place scenes on the graphic window
    (loop for counter from 1 to ns do
      (setf thisalloc (car alloc))
      (setf alloc (cdr alloc))
      (cond
        (thisalloc ; user defined scene allocation
            (setf x1 (first thisalloc)
                  y1 (second thisalloc))
            (setf x2 (+ x1 (third thisalloc))
                  y2 (+ y1 (fourth thisalloc))))
        (t ; automatic scene allocation
            (incf nilcounter)
            (setf x1 (* (mod (- nilcounter 1) ncol) dx)
                  x2 (+ x1 dx)
                  y1 (* (- nrow (ceiling nilcounter ncol)) dy)
                  y2 (+ y1 dy))))
      (format str "renderer~a.SetViewport(~a,~a,~a,~a)~%" counter x1 y1 x2 y2))
    (format str "renWin=vtk.vtkRenderWindow()~%renWin.SetMultiSamples(0)~%")
    (format str "renWin.SetSize(~a,~a)~%" (car dim) (cadr dim))
    (loop for k from 1 to ns do
      (format str "renWin.AddRenderer(renderer~a)~%" k))
    str))


; code for file output
(defun vtk-terminal ()
  (let ((terminal  (get-option '$terminal))
        (filename  (get-option '$file_name))
        (offscreenterms '($png $pngcairo $jpg $eps $eps_color $tiff $pnm))
        (extension "")
        (classformat ""))
      (cond
        ((member terminal offscreenterms)
          (case terminal
            (($png $pngcairo)
               (setf extension   "png"
                     classformat "vtkPNGWriter"))
            ($jpg
              (setf extension   "jpg"
                    classformat "vtkJPEGWriter"))
            ($tiff
              (setf extension   "tif"
                    classformat "vtkTIFFWriter"))
            ($pnm
              (setf extension   "pnm"
                    classformat "vtkPNMWriter"))
            (($eps $eps_color)
               (setf extension   "eps"
                     classformat "vtkPostScriptWriter")))
          (format nil "~a~%~a~%~a~%~a~%~a~a()~%~a~%~a(\"~a.~a\")~%~a~%~a~%"
            "renWin.OffScreenRenderingOn()"
            "renWin.Render()"
            "w2if=vtk.vtkWindowToImageFilter()"
            "w2if.SetInput(renWin)"
            "writer=vtk." classformat
            "writer.SetInputConnection(w2if.GetOutputPort())"
            "writer.SetFileName" filename extension
            "writer.Write()"
            "exit()"))
       ((eq terminal '$vrml)
          (format nil "~a~%~a~%~a(\"~a.~a\")~%~a~%~a~%~a~%"
            "vrml=vtk.vtkVRMLExporter()"
            "vrml.SetInput(renWin)"
            "vrml.SetFileName" filename "wrl"
            "vrml.SetSpeed(5.5)"
            "vrml.Write()"
            "exit()"))
       ((eq terminal '$obj)
          (format nil "~a~%~a~%~a(\"~a\")~%~a~%~a~%"
            "obj=vtk.vtkOBJExporter()"
            "obj.SetInput(renWin)"
            "obj.SetFilePrefix" filename
            "obj.Write()"
            "exit()"))
       ((eq terminal '$screen)
          (format nil "~a~%~a~%~a~%~a~%~a~%~a~%~a~%"
            "iren=vtk.vtkRenderWindowInteractor()"
            "iren.SetRenderWindow(renWin)"
            "iren.Initialize()"
            "renderer1.ResetCamera()"
            "renderer1.GetActiveCamera().Zoom(1.01)"
            "renWin.Render()"
            "iren.Start()"))
       ((eq terminal '$stl)
          (format nil "~a~%~a~%~a~%~a~%~a~a~a~%~a~%~a~%"
            "triangulator=vtk.vtkTriangleFilter()"
            "triangulator.SetInputConnection(appenddata1.GetOutputPort())"
            "stl=vtk.vtkSTLWriter()"
            "stl.SetInputConnection(triangulator.GetOutputPort())"
            "stl.SetFileName(\"" filename ".stl\")" 
            "stl.Write()"
            "exit()" ))
       ((eq terminal '$ply)
          (format nil "~a~%~a~%~a~%~a~%~a~a~a~%~a~%~a~%"
            "triangulator=vtk.vtkTriangleFilter()"
            "triangulator.SetInputConnection(appenddata1.GetOutputPort())"
            "stl=vtk.vtkPLYWriter()"
            "stl.SetInputConnection(triangulator.GetOutputPort())"
            "stl.SetFileName(\"" filename "\")" 
            "stl.Write()"
            "exit()" ))
       (t
          (merror "draw: unknown terminal for vtk")))))


; Checks if lookup table is already created.
; Returns its position number in *lookup-tables*
(defun lookup-table-exists (pal)
  (let (pos)
    (setf pos (position pal *lookup-tables* :test #'equal))
    (when (null pos)
      (setf pos -1))
    (1+ pos)))


; Writes tcl code for color transform functions
(defun color-transform-function (c n f)
  (let (pf expr)
    (if (< f 0)
      (setf pf (- f))
      (setf pf f))
    (case pf
      (0  (setf expr "x = 0"))
      (1  (setf expr "x = 0.5"))
      (2  (setf expr "x = 1"))
      (3  (setf expr "x = x"))
      (4  (setf expr "x = x*x"))
      (5  (setf expr "x = x*x*x"))
      (6  (setf expr "x = x*x*x*x"))
      (7  (setf expr "x = math.sqrt(x)"))
      (8  (setf expr "x = math.sqrt(math.sqrt(x))"))
      (9  (setf expr "x = math.sin(1.570796326794897*x)")) ; %pi/2
      (10 (setf expr "x = math.cos(1.570796326794897*x)"))
      (11 (setf expr "x = math.fabs(x-0.5)"))
      (12 (setf expr "x = (2.0*x-1.0)*(2.0*x-1.0)"))
      (13 (setf expr "x = math.sin(3.141592653589793*x)")) ; %pi
      (14 (setf expr "x = math.fabs(math.cos(3.141592653589793*x))"))
      (15 (setf expr "x = math.sin(6.283185307179586*x)")) ; 2*%pi
      (16 (setf expr "x = math.cos(6.283185307179586*x)"))
      (17 (setf expr "x = math.fabs(math.sin(6.283185307179586*x))"))
      (18 (setf expr "x = math.fabs(math.cos(6.283185307179586*x))"))
      (19 (setf expr "x = math.fabs(math.sin(12.56637061435917*x))")) ; 4*%pi
      (20 (setf expr "x = math.fabs(math.cos(12.56637061435917*x))"))
      (21 (setf expr "x = 3.0*x"))
      (22 (setf expr "x = 3.0*x-1.0"))
      (23 (setf expr "x = 3.0*x-2.0"))
      (24 (setf expr "x = math.fabs(3.0*x-1.0)"))
      (25 (setf expr "x = math.fabs(3.0*x-2.0)"))
      (26 (setf expr "x = 1.5*x-0.5"))
      (27 (setf expr "x = 1.5*x-1.0"))
      (28 (setf expr "x = math.fabs(1.5*x-0.5)"))
      (29 (setf expr "x = math.fabs(1.5*x-1.0)"))
      (30 (setf expr "x = interval(x,0.25,0.57)/0.32-0.78125"))
      (31 (setf expr "x = 2*interval(x,0.42,0.92)-0.84"))
      (32 (setf expr (concatenate 'string
                       (format nil "if x <= 0.42:~%")
                       (format nil "    x = 4.0*x~%")
                       (format nil "  elif x <= 0.92:~%")
                       (format nil "    x = -2.0*x+1.84~%")
                       (format nil "  else:~%")
                       (format nil "    x = x/0.08-11.5"))))
      (33 (setf expr "x = math.fabs(2.0*x-0.5)"))
      (34 (setf expr "x = 2*x"))
      (35 (setf expr "x = 2.0*x-0.5"))
      (36 (setf expr "x = 2.0*x-1.0")))
    (concatenate 'string
      (format nil "def f~a~a (k):~%" c n)
      (format nil "  x = unitscale(k)~%" )
      (format nil "  ~a~%" expr)
      (format nil "  return interval(x,0,1)~%~%"))   ))


; Creates lookup table. See info for option 'palette'.
; Returns list with lookup table name and the string.
(defun check-lookup-table ()
  (let ((palette (get-option '$palette))
        (lut "")
        palette-name lutn)
    (cond ((equal palette '$gray)
             (setf palette '(3 3 3)))
          ((equal palette '$color)
             (setf palette '(7 5 15))) )
    (setf lutn (1+ (length *lookup-tables*)))
    (setf *lookup-tables* (append *lookup-tables* (list palette)))
    (setf palette-name (format nil "lut~a" lutn))
    (cond ((and (listp palette)  ; build lookup table with transform functionsunitscale
                (= (length palette) 3)
                (every #'(lambda (x) (and (integerp x) (<= (abs x) 36))) palette) )
             ; if *unitscale-already-defined* is null, write
             ; tcl functions 'unitscale' and 'unitinterval'
             (when (null *unitscale-already-defined*)
               (setf lut
                 (concatenate 'string
                   (format nil "import math~%~%")
                   (format nil "def unitscale (k):~%")
                   (format nil "  return k/255.0~%~%")
                   (format nil "def interval (x,x0,x1):~%")
                   (format nil "  if x <= x0:~%")
                   (format nil "    return 0~%")
                   (format nil "  if x >= x1:~%")
                   (format nil "    return 1~%")
                   (format nil "  return x~%~%")))
                 (setf *unitscale-already-defined* t))
             ; write tcl r-g-b transform functions
             (setf lut
               (concatenate 'string
                 lut
                 (color-transform-function "R" lutn (car palette))
                 (color-transform-function "G" lutn (cadr palette))
                 (color-transform-function "B" lutn (caddr palette))))
             ; create lookup table
             (setf lut
                   (concatenate 'string
                     lut
                     (format nil "~a=vtk.vtkLookupTable()~%" palette-name)
                     (format nil "~a.SetNumberOfColors(256)~%" palette-name)
                     (format nil "~a.Build()~%" palette-name)
                     (format nil "for i in range (0,256):~%")
                     (format nil "  ~a.SetTableValue(i,fR~a(i),fG~a(i),fB~a(i),1)~%~%"
                             palette-name lutn lutn lutn)))
             (list palette-name lut))

          ((and (listp palette)  ; build user defined lookup table without transparency
             (every #'(lambda (x) (and (listp x) (= (length x) 3))) palette) )
            (list
              palette-name
              (let (triplete
                    (n (length palette)))
                (with-output-to-string (stream)
                  (format stream "~a=vtk.vtkLookupTable()~%" palette-name)
                  (format stream "~a.SetNumberOfColors(~a)~%" palette-name n)
                  (dotimes (k n)
                    (setf triplete (nth k palette))
                    (format stream "~a.SetTableValue(~a,~a,~a,~a,1)~%"
                            palette-name k (car triplete) (cadr triplete) (caddr triplete)))))))

          ((and (listp palette)  ; build user defined lookup table with transparency
             (every #'(lambda (x) (and (listp x) (= (length x) 4))) palette) )
            (list
              palette-name
              (let (triplete
                    (n (length palette)))
                (with-output-to-string (stream)
                  (format stream "~a=vtk.vtkLookupTable()~%" palette-name)
                  (format stream "~a.SetNumberOfColors(~a)~%" palette-name n)
                  (dotimes (k n)
                    (setf triplete (nth k palette))
                    (format stream "~a.SetTableValue(~a,~a,~a,~a,~a)~%"
                            palette-name k (car triplete) (cadr triplete) (caddr triplete) (cadddr triplete))))))))))


(defun build-surface-grid (nx ny)
  (let ((poly nil)
        cont)
    (dotimes (f (1- ny))
      (setf cont (* f nx))
      (dotimes (c (1- nx))
         (setf poly (cons  (list (+ cont c) (+ cont c 1) (+ cont nx c 1) (+ cont nx c)) poly))))
    (reverse poly)))




;;; OBJECT BUILDERS

;; 3d: cone(center, radius, height, direction)
;; -------------------------------------------
(defun vtk3d-cone (cen rad hei dir)
  (let ((color        (get-option '$color))
        (opacity      (get-option '$opacity))
        (linewidth    (get-option '$line_width))
        (wiredsurface (get-option '$wired_surface))
        (capping      (rest (get-option '$capping)))
        (source-name  (get-source-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (fcen         ($float cen))
        (fhei         ($float hei))
        (frad         ($float rad))
        (fdir         ($float dir))
        capn )
    (when (or (not ($listp fcen))
              (not (= ($length fcen) 3))
              (not (every #'floatp (rest fcen))) )
          (merror "draw3d: cone center must be a list of three numbers"))
    (when (or (not (floatp frad))
              (<= frad 0.0))
          (merror "draw3d: cone radius must be a number greater than zero"))
    (when (or (not (floatp fhei))
              (<= fhei 0.0))
          (merror "draw3d: cone height must be a number greater than zero"))
    (when (or (not ($listp fdir))
              (not (= ($length fdir) 3))
              (not (every #'floatp (rest fdir))) )
          (merror "draw3d: cone direction must be a list of three numbers"))
    (if (first capping)
      (setf capn 1)
      (setf capn 0))
    (concatenate 'string
      (format nil "~a=vtk.vtkConeSource()~%" source-name)
      (format nil "~a.SetHeight(~a)~%" source-name fhei)
      (format nil "~a.SetRadius(~a)~%" source-name frad)
      (format nil "~a.SetCenter(~a,~a,~a)~%"
              source-name
              (cadr fcen)
              (caddr fcen)
              (cadddr fcen))
      (format nil "~a.SetDirection(~a,~a,~a)~%"
              source-name
              (cadr fdir)
              (caddr fdir)
              (cadddr fdir))
      (format nil "~a.SetResolution(~a)~%" source-name 30)
      (format nil "~a.SetCapping(~a)~%" source-name capn)
      (vtktransform-code trans-name)
      (vtktransformpolydatafilter-code filter-name source-name trans-name nil)
      (vtkpolydatamapper-code mapper-name filter-name t)
      (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
      (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface)
      (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))  )))



;; 3d: prism(center, n, edgepoint, height, direction)
;; --------------------------------------------------

; rotates point (x,y,z) rad radians around the line with unitary direction
; vector (u,v,w) containing point (a,b,c)
(defun rotate (x y z a b c u v w rad)
    (list
      (+ (* (cos rad) x)
         (* ($sin rad) (+ (* -1 c v) (* b w) (* -1 w y) (* v z)))
         (* (+ 1 (* -1 ($cos rad)))
            (+ (* a (+ (expt v 2) (expt w 2)))
               (* -1 u (+ (* b v) (* c w) (* -1 u x) (* -1 v y) (* -1 w z)))))) 
      (+ (* ($cos rad) y)
         (* ($sin rad) (+ (* c u) (* -1 a w) (* w x) (* -1 u z)))
         (* (+ 1 (* -1 ($cos rad)))
            (+ (* b (+ (expt u 2) (expt w 2)))
               (* -1 v (+ (* a u) (* c w) (* -1 u x) (* -1 v y) (* -1 w z)))))) 
      (+ (* ($sin rad) (+ (* -1 b u) (* a v) (* -1 v x) (* u y)))
         (* ($cos rad) z)
         (* (+ 1 (* -1 ($cos rad)))
            (+ (* c (+ (expt u 2) (expt v 2)))
               (* -1 w (+ (* a u) (* b v) (* -1 u x) (* -1 v y) (* -1 w z))))))   ))

(defun vtk3d-prism (cen n edgp hei dir)
  (let ((color          (get-option '$color))
        (opacity        (get-option '$opacity))
        (linewidth      (get-option '$line_width))
        (wiredsurface   (get-option '$wired_surface))
        (capping        (rest (get-option '$capping)))
        (source-name    (get-source-name))
        (points-name    (get-points-name))
        (cellarray-name (get-cellarray-name))
        (mapper-name    (get-mapper-name))
        (actor-name     (get-actor-name))
        (trans-name     (get-trans-name))
        (filter-name    (get-filter-name))
        (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        (fcen           ($float cen))
        (fedgp          ($float edgp))
        (fhei           ($float hei))
        (fdir           ($float dir))
        (ang            (/ 6.283185307179586 n)) ; = 2*%pi/n
        (xcount -1)
        (ycount -1)
        (zcount -1)
        dirmod c1 c2 c3 d1 d2 d3 p1 p2 p3 du1 du2 du3 v v1 v2 v3 x y z)
    (when (or (not ($listp fcen))
              (not (= ($length fcen) 3))
              (not (every #'floatp (rest fcen))) )
          (merror "draw3d: prism center must be a list of three numbers"))
    (when (or (not ($listp fedgp))
              (not (= ($length fedgp) 3))
              (not (every #'floatp (rest fedgp))) )
          (merror "draw3d: point on prism edge must be a list of three numbers"))
    (when (or (not (floatp fhei))
              (<= fhei 0.0))
          (merror "draw3d: prism height must be a number greater than zero"))
    (when (or (not ($listp fdir))
              (not (= ($length fdir) 3))
              (not (every #'floatp (rest fdir))) )
          (merror "draw3d: cylinder direction must be a list of three numbers"))
    ; direction vector with module = height/2
    (setf c1 (cadr fcen)  c2 (caddr fcen)  c3 (cadddr fcen)
          p1 (cadr fedgp) p2 (caddr fedgp) p3 (cadddr fedgp)
          d1 (cadr fdir)  d2 (caddr fdir)  d3 (cadddr fdir))
    (setf dirmod (sqrt (+ (* d1 d1) (* d2 d2) (* d3 d3))))
    (when (= dirmod 0.0)
      (setf d1 0 d2 0 d3 1 dirmod 1))
    (setf du1 (/ (* d1 fhei) (* 2 dirmod))
          du2 (/ (* d2 fhei) (* 2 dirmod))
          du3 (/ (* d3 fhei) (* 2 dirmod)))
    ; intersection between edge and perpendicular plane passing through center:
    ; linsolve([d1*v1+d2*v2+d3*v3=d1*c1+d2*c2+d3*c3,
    ;           d2*v1-d1*v2      =d2*p1-d1*p2,
    ;                 d3*v2-d2*v3=d3*p2-d2*p3], [v1,v2,v3]);
    (let ((den (* dirmod dirmod)))
      (setf v1 (/ (+ (* c1 d1 d1) (* c2 d1 d2) (* c3 d1 d3) (* d2 d2 p1) (* d3 d3 p1) (* -1 d1 d2 p2) (* -1 d1 d3 p3))
                  den)
            v2 (/ (+ (* c1 d1 d2) (* c2 d2 d2) (* c3 d2 d3) (* -1 d1 d2 p1) (* d1 d1 p2) (* d3 d3 p2) (* -1 d2 d3 p3))
                  den)
            v3 (/ (+ (* c1 d1 d3) (* c2 d2 d3) (* c3 d3 d3) (* -1 d1 d3 p1) (* -1 d2 d3 p2) (* d1 d1 p3) (* d2 d2 p3)) 
                  den)))
    ; rotate n times 2 pi/n and save the vertices of the lateral rectangles
    (setf x (make-array (* (+ 2 (count t capping)) (+ n 1) ) :element-type 'flonum))
    (setf y (make-array (* (+ 2 (count t capping)) (+ n 1) ) :element-type 'flonum))
    (setf z (make-array (* (+ 2 (count t capping)) (+ n 1) ) :element-type 'flonum))
    (loop for s from 0 to n do
      ; bottom capping?
      (when (equal (second capping) t)
        (setf (aref x (incf xcount)) (- c1 du1))
        (setf (aref y (incf ycount)) (- c2 du2))
        (setf (aref z (incf zcount)) (- c3 du3)))
      (setf v (rotate v1 v2 v3 c1 c2 c3 (/ d1 dirmod) (/ d2 dirmod) (/ d3 dirmod) (* s ang)) )
      (setf (aref x (incf xcount)) (- (first v) du1))
      (setf (aref y (incf ycount)) (- (second v) du2))
      (setf (aref z (incf zcount)) (- (third v) du3))
      (setf (aref x (incf xcount)) (+ (first v) du1))
      (setf (aref y (incf ycount)) (+ (second v) du2))
      (setf (aref z (incf zcount)) (+ (third v) du3))
      ; top capping?
      (when (equal (first capping) t)
        (setf (aref x (incf xcount)) (+ c1 du1))
        (setf (aref y (incf ycount)) (+ c2 du2))
        (setf (aref z (incf zcount)) (+ c3 du3))) ) ; end loop

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2
                                         (build-surface-grid (+ 2 (count t capping)) (+ n 1))))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name t))
    (format str "bounds.append(~a.GetBounds())~%" mapper-name)
    (format str "~a~%" (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
  str))



;; 3d: cylinder(center, radius, height, direction)
;; -----------------------------------------------
(defun vtk3d-cylinder (cen rad hei dir)
  (let ((color        (get-option '$color))
        (opacity      (get-option '$opacity))
        (linewidth    (get-option '$line_width))
        (wiredsurface (get-option '$wired_surface))
        (capping      (rest (get-option '$capping)))
        (source-name  (get-source-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (fcen         ($float cen))
        (frad         ($float rad))
        (fhei         ($float hei))
        (fdir         ($float dir))
        capn dirmod xrot yrot zrot)
    (when (or (not ($listp fcen))
              (not (= ($length fcen) 3))
              (not (every #'floatp (rest fcen))) )
          (merror "draw3d: cylinder center must be a list of three numbers"))
    (when (or (not (floatp fhei))
              (<= fhei 0.0))
          (merror "draw3d: cylinder height must be a number greater than zero"))
    (when (or (not (floatp frad))
              (<= frad 0.0))
          (merror "draw3d: cylinder radius must be a number greater than zero"))
    (when (or (not ($listp fdir))
              (not (= ($length fdir) 3))
              (not (every #'floatp (rest fdir))) )
          (merror "draw3d: cylinder direction must be a list of three numbers"))
    (if (first capping)
      (setf capn 1)
      (setf capn 0))
    (setf dirmod (sqrt (+ (* (cadr fdir)   (cadr fdir))
                          (* (caddr fdir)  (caddr fdir))
                          (* (cadddr fdir) (cadddr fdir)))))
    (cond
      ((= dirmod 0.0)
         ; we use the same default direction used by cones,
         ; which is the positive X-direction
         (setf xrot 0.0
               yrot 0.0
               zrot -90.0))
      ((= (caddr fdir) 0.0)
         (setf xrot 90.0
               yrot (* 57.29577951308232
                       ($acos (/ (cadddr fdir)
                                 (sqrt (+ (* (cadr fdir)   (cadr fdir))
                                          (* (cadddr fdir) (cadddr fdir)) )))))
               zrot 0.0))
      ((< (caddr fdir) 0.0)
         (setf xrot (* 57.29577951308232 ($asin (/ (cadddr fdir) dirmod)))
               yrot 0.0
               zrot (* 57.29577951308232 (+ -3.141592653589793 (- ($atan (/ (cadr fdir) (caddr fdir))))))))
      (t
         (setf xrot (* 57.29577951308232 ($asin (/ (cadddr fdir) dirmod)))
               yrot 0.0
               zrot (* 57.29577951308232 (- ($atan (/ (cadr fdir) (caddr fdir)))))))  )
    ; python code
    (concatenate 'string
      (format nil "~a=vtk.vtkCylinderSource()~%" source-name)
      (format nil "~a.SetHeight(~a)~%" source-name fhei)
      (format nil "~a.SetRadius(~a)~%" source-name frad)
      (format nil "~a.SetResolution(~a)~%" source-name 30)
      (format nil "~a.SetCapping(~a)~%" source-name capn)
      (vtktransform-code trans-name)
      (format nil "~a.Translate(~a,~a,~a)~%"
              trans-name
              (cadr fcen)
              (caddr fcen)
              (cadddr fcen))
      ; rotations are made in reverse order as indicated here
      (format nil "~a.RotateZ(~a)~%" trans-name zrot) ; azimuth
      (format nil "~a.RotateY(~a)~%" trans-name yrot)
      (format nil "~a.RotateX(~a)~%" trans-name xrot) ; elevation
      (vtktransformpolydatafilter-code filter-name source-name trans-name nil)
      (vtkpolydatamapper-code mapper-name filter-name t)
      (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
      (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface)
      (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))  )))



;; 3d: cube(xlength, ylength, zlength, center)
;; -------------------------------------------
(defun vtk3d-cube (xlen ylen zlen cen)
  (let ((color        (get-option '$color))
        (opacity      (get-option '$opacity))
        (linewidth    (get-option '$line_width))
        (wiredsurface (get-option '$wired_surface))
        (source-name  (get-source-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (fxlen        ($float xlen))
        (fylen        ($float ylen))
        (fzlen        ($float zlen))
        (fcen         ($float cen)) )
    (when (or (not (floatp fxlen))
              (<= fxlen 0.0))
          (merror "draw3d: cube x-length must be a number greater than zero"))
    (when (or (not (floatp fylen))
              (<= fylen 0.0))
          (merror "draw3d: cube y-length must be a number greater than zero"))
    (when (or (not (floatp fzlen))
              (<= fzlen 0.0))
          (merror "draw3d: cube z-length must be a number greater than zero"))
    (when (or (not ($listp fcen))
              (not (= ($length fcen) 3))
              (not (every #'floatp (rest fcen))) )
          (merror "draw3d: cube center must be a list of three floats"))
    ; python code
    (concatenate 'string
      (format nil "~a=vtk.vtkCubeSource()~%" source-name)
      (format nil "~a.SetXLength(~a)~%" source-name fxlen)
      (format nil "~a.SetYLength(~a)~%" source-name fylen)
      (format nil "~a.SetZLength(~a)~%" source-name fzlen)
      (format nil "~a.SetCenter(~a,~a,~a)~%"
              source-name
              (cadr fcen)
              (caddr fcen)
              (cadddr fcen))
      (vtktransform-code trans-name)
      (vtktransformpolydatafilter-code filter-name source-name trans-name nil)
      (vtkpolydatamapper-code mapper-name filter-name t)
      (format nil "bounds.append(~a.GetBounds())~%" mapper-name) 
      (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface)
      (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil)) )))



;; 3d: sphere(center, radius)
;; --------------------------
(defun vtk3d-sphere (cen rad)
  (let ((color        (get-option '$color))
        (opacity      (get-option '$opacity))
        (linewidth    (get-option '$line_width))
        (wiredsurface (get-option '$wired_surface))
        (source-name  (get-source-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (frad         ($float rad))
        (fcen         ($float cen))  )
    (when (or (not ($listp fcen))
              (not (= ($length fcen) 3))
              (not (every #'floatp (rest fcen))) )
          (merror "draw3d: sphere center must be a list of three numbers"))
    (when (or (not (floatp frad))
              (<= frad 0.0))
          (merror "draw3d: sphere radius must be a number greater than zero"))

    ; python code
    (concatenate 'string
      (format nil "~a=vtk.vtkSphereSource()~%" source-name)
      (format nil "~a.SetRadius(~a)~%" source-name frad)
      (format nil "~a.SetCenter(~a,~a,~a)~%"
              source-name
              (cadr fcen)
              (caddr fcen)
              (cadddr fcen))
      (format nil "~a.SetThetaResolution(~a)~%" source-name 30)
      (format nil "~a.SetPhiResolution(~a)~%" source-name 30)
      (vtktransform-code trans-name)
      (vtktransformpolydatafilter-code filter-name source-name trans-name nil)
      (vtkpolydatamapper-code mapper-name filter-name t)
      (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
      (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface)
      (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil)) )))



;; 3d: parallelogram(origin, point1, point2)
;; -----------------------------------------
;; The parallelogram is defined by one vertex and the two other adjacent vertices
(defun vtk3d-parallelogram (ori p1 p2)
  (let ((color        (get-option '$color))
        (opacity      (get-option '$opacity))
        (linewidth    (get-option '$line_width))
        (wiredsurface (get-option '$wired_surface))
        (source-name  (get-source-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (str          (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        (fori         (map 'list #'$float (rest ori)))
        (fp1          (map 'list #'$float (rest p1)))
        (fp2          (map 'list #'$float (rest p2)))
        xx yy zz a1 b1 c1 a2 b2 c2)
    (when (notevery #'(lambda (z) (floatp z))
                    (append fori fp1 fp2))
      (merror "vtk3d: arguments to parallelogram must be lists of floats"))

    ; python code
    (format str "~a=vtk.vtkPlaneSource()~%" source-name)
    (setf xx (car   fori)
          yy (cadr  fori)
          zz (caddr fori))
    (transform-point 3)
    (setf a1 xx
          b1 yy
          c1 zz)
    (format str "~a.SetOrigin(~a,~a,~a)~%" source-name xx yy zz)
    (setf xx (car   fp1)
          yy (cadr  fp1)
          zz (caddr fp1))
    (transform-point 3)
    (if (and (= a1 xx) (= b1 yy) (= c1 zz))
      (merror "vtk3d (parallelogram): three distinct vertices are needed.")
      (setf a2 xx
            b2 yy
            c2 zz) )
    (format str "~a.SetPoint1(~a,~a,~a)~%" source-name xx yy zz)
    (setf xx (car   fp2)
          yy (cadr  fp2)
          zz (caddr fp2))
    (transform-point 3)
    (when (or (and (= a1 xx) (= b1 yy) (= c1 zz))
              (and (= a2 xx) (= b2 yy) (= c2 zz)) )
      (merror "vtk3d: we need three distinct vertices to draw a parallelogram.") )
    (format str "~a.SetPoint2(~a,~a,~a)~%" source-name xx yy zz)
    (format nil "~a.SetXResolution(~a)~%" source-name 10)
    (format str "~a.SetYResolution(~a)~%" source-name 10)
    (format str "~a" (vtktransform-code trans-name))
    (format str "~a" (vtktransformpolydatafilter-code filter-name source-name trans-name nil))
    (format str "~a" (vtkpolydatamapper-code mapper-name filter-name t))
    (format str "bounds.append(~a.GetBounds())~%" mapper-name)
    (format str "~a" (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
  str))



;; 3d: triangle(vertex1, vertex2, vertex3)
;; ---------------------------------------
;; The triangle is defined by three vertices
(defun vtk3d-triangle (v1 v2 v3)
  (let ((color         (get-option '$color))
        (opacity       (get-option '$opacity))
        (linewidth     (get-option '$line_width))
        (wiredsurface  (get-option '$wired_surface))
        (points-name   (get-points-name))
        (triangle-name (get-triangle-name))
        (polydata-name (get-polydata-name))
        (trans-name    (get-trans-name))
        (filter-name   (get-filter-name))
        (mapper-name   (get-mapper-name))
        (actor-name    (get-actor-name))
        (str           (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        (fv1           (map 'list #'$float (rest v1)))
        (fv2           (map 'list #'$float (rest v2)))
        (fv3           (map 'list #'$float (rest v3)))
        xx yy zz)
    (when (notevery #'(lambda (z) (floatp z))
                    (append fv1 fv2 fv3))
      (merror "vtk3d (triangle): arguments must be lists of three numbers"))
    ; python code
    (format str "~a=vtk.vtkPoints()~%" points-name)
    (format str "~a.SetNumberOfPoints(3)~%" points-name)
    (setf xx (car   fv1)
          yy (cadr  fv1)
          zz (caddr fv1))
    (transform-point 3)
    (format str "~a.InsertPoint(0,~a,~a,~a)~%" points-name xx yy zz)
    (setf xx (car   fv2)
          yy (cadr  fv2)
          zz (caddr fv2))
    (transform-point 3)
    (format str "~a.InsertPoint(1,~a,~a,~a)~%" points-name xx yy zz)
    (setf xx (car   fv3)
          yy (cadr  fv3)
          zz (caddr fv3))
    (transform-point 3)
    (format str "~a.InsertPoint(2,~a,~a,~a)~%" points-name xx yy zz)
    (format str "~a=vtk.vtkTriangle()~%" triangle-name)
    (format str "~a.GetPointIds().SetId(0,0)~%" triangle-name)
    (format str "~a.GetPointIds().SetId(1,1)~%" triangle-name)
    (format str "~a.GetPointIds().SetId(2,2)~%" triangle-name)
    (format str "~a=vtk.vtkPolyData()~%" polydata-name)
    (format str "~a.Allocate(1,1)~%" polydata-name)
    (format str "~a.InsertNextCell(~a.GetCellType(),~a.GetPointIds())~%"
            polydata-name
            triangle-name
            triangle-name)
    (format str "~a.SetPoints(~a)~%" polydata-name points-name)
    (format str "~a" (vtktransform-code trans-name))
    (format str "~a" (vtktransformpolydatafilter-code filter-name polydata-name trans-name t))
    (format str "~a=vtk.vtkPolyDataMapper()~%" mapper-name)
    (format str "~a.SetInputData(~a)~%" mapper-name polydata-name)
    (format str "bounds.append(~a.GetBounds())~%" mapper-name)
    (format str "~a" (vtkactor-code actor-name mapper-name color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
  str))



;; 3d: vector([x,y,z], [dx,dy,dz])
;; ---------------------------
(defun vtk3d-vector (arg1 arg2)
  (when (or (not ($listp arg1))
            (not (= ($length arg1) 3))
            (not ($listp arg2))
            (not (= ($length arg2) 3)))
      (merror "vtk3d (vector): coordinates are not correct"))
  (let ((color        (get-option '$color))
        (head-length  (get-option '$head_length))
        (head-angle   (get-option '$head_angle))
        (line-width   (get-option '$line_width))
        (unit-vectors (get-option '$unit_vectors))
        (opacity      (get-option '$opacity))
        (wiredsurface (get-option '$wired_surface))
        (source-name  (get-source-name))
        (trans-name   (get-trans-name))
        (filter-name  (get-filter-name))
        (mapper-name  (get-mapper-name))
        (actor-name   (get-actor-name))
        (x  ($float   (cadr arg1)))
        (y  ($float   (caddr arg1)))
        (z  ($float   (cadddr arg1)))
        (dx ($float   (cadr arg2)))
        (dy ($float   (caddr arg2)))
        (dz ($float   (cadddr arg2)))
        ndx ndy ndz radians tiplength module radius rotangle)
    ; unitary vector
    (setf module (sqrt (+ (* dx dx) (* dy dy) (* dz dz))))
    (setf ndx (/ dx module)
          ndy (/ dy module)
          ndz (/ dz module))
    ; transform into unitary vector when unit_vectors=true
    (when unit-vectors
      (setf module 1))
    ; head parameters
    (setf radians (* head-angle 0.0174532925199433)) ; 0.017..=%pi/180
    (setf tiplength (* head-length ($float ($cos radians))))
    (setf radius (* head-length ($float ($sin radians))))
    ; rotation angle
    (setf rotangle
          (* 57.29577951308232  ; 57.29..=180/%pi
            ($float ($asin (sqrt (+ (* ndz ndz) (* ndy ndy)))))))
    ; check if rotation angle is obtuse
    (when (< ndx 0)
      (setf rotangle (- 180.0 rotangle)))
    (when (and (= ndz 0.0) (= ndy 0.0))
      (setf ndy 0.0
            ndz -1.0))

    ; python code
    (concatenate 'string
      (format nil "~a=vtk.vtkArrowSource()~%" source-name)
      (format nil "~a.SetTipResolution(~a)~%" source-name 20)
      (format nil "~a.SetTipRadius(~a)~%" source-name (/ radius module))
      (format nil "~a.SetTipLength(~a)~%" source-name (/ tiplength module))
      (format nil "~a.SetShaftResolution(~a)~%" source-name 10)
      (format nil "~a.SetShaftRadius(~a)~%" source-name (/ line-width module))
      (vtktransform-code trans-name)
      (format nil "~a.Translate(~a,~a,~a)~%" trans-name x y z)
      (format nil "~a.RotateWXYZ(~a,~a,~a,~a)~%" trans-name rotangle 0 (- ndz) ndy)
      (format nil "~a.Scale(~a,~a,~a)~%" trans-name module module module)
      (vtktransformfilter-code filter-name source-name trans-name)
      (vtkpolydatamapper-code mapper-name filter-name t)
      (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
      (vtkactor-code actor-name mapper-name color opacity line-width wiredsurface)
      (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil)) )))



;; 3D: points([[x1,y1,z1], [x2,y2,z2], [x3,y3,z3],...])
;; ----------------------------------------------------
(defun vtk3d-points (arg)
  (let ((points-joined   (get-option '$points_joined))
        (point-type      (get-option '$point_type))
        (point-size      ($float (get-option '$point_size)))
        (line-type       (get-option '$line_type))
        (color           (get-option '$color))
        (opacity         (get-option '$opacity))
        (linewidth       (get-option '$line_width))
        (wiredsurface    (get-option '$wired_surface))
        (source-name     (get-source-name))
        (points-name     (get-points-name))
        (floatarray-name (get-floatarray-name))
        (tmp             (mapcar #'rest (rest arg)))
        (output-string   "")
        (minscalar       most-positive-double-float)
        (maxscalar       most-negative-double-float)
        source-name2 points-name2 filter-name trans-name mapper-name actor-name polydata-name 
        cellarray-name cellarray-name2 solidsource-name lookup-table-name glyphpoints-name
        newscalar slope scalars x y z ax ay az n)

    (setf n ($length arg))
    ; create array of points
    (setf x (map 'list #'$float (map 'list #'first tmp))
          y (map 'list #'$float (map 'list #'second tmp))
          z (map 'list #'$float (map 'list #'third tmp)) )
    (transform-lists 3)
    (setf ax (make-array n :element-type 'flonum :initial-contents x)
          ay (make-array n :element-type 'flonum :initial-contents y)
          az (make-array n :element-type 'flonum :initial-contents z))

    ; check enhanced3d model
    (check-enhanced3d-model "points" '(0 1 3))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array n :element-type 'flonum))
      (cond
        ((= *draw-enhanced3d-type* 1)
           (dotimes (k n)
             (setf newscalar (funcall *draw-enhanced3d-fun* k))
             (when (< newscalar minscalar) (setf minscalar newscalar))
             (when (> newscalar maxscalar) (setf maxscalar newscalar))
             (setf (aref scalars k) newscalar )) )
        ((= *draw-enhanced3d-type* 3)
           (dotimes (k n)
             (setf newscalar (funcall *draw-enhanced3d-fun* (aref ax k) (aref ay k) (aref az k)))
             (when (< newscalar minscalar) (setf minscalar newscalar))
             (when (> newscalar maxscalar) (setf maxscalar newscalar))
             (setf (aref scalars k) newscalar))))
      (if (< minscalar maxscalar)
        (setf slope (/ 1.0 (- maxscalar minscalar)))
        (setf slope 0.0)) 
      ; rescale array of scalars to interval [0,1]
      (loop for s from 0 below (length scalars) do
        (setf (aref scalars s) (* slope (- (aref scalars s) minscalar))))
      (let ((lut (check-lookup-table)))
        (setf lookup-table-name (car lut))
        (setf output-string (cadr lut))) )

    ; python code
    (setf output-string
      (concatenate 'string
        output-string
        (format nil "~a=vtk.vtkPolyData()~%" source-name)
        (vtkpoints-code points-name source-name ax ay az)
        (when (> *draw-enhanced3d-type* 0)
          (vtkfloatarray-code floatarray-name source-name scalars nil) )))
    (when points-joined ; true or impulses
      (setf trans-name       (get-trans-name)
            filter-name      (get-filter-name)
            mapper-name      (get-mapper-name)
            polydata-name    (get-polydata-name)
            cellarray-name   (get-cellarray-name)
            actor-name       (get-actor-name))
      (setf output-string
        (concatenate 'string
          output-string
          (cond
            ((eql points-joined '$impulses)
               (setf source-name2    (get-source-name)
                     points-name2    (get-points-name)
                     cellarray-name2 (get-cellarray-name))
               (concatenate 'string
                 (format nil "~a=vtk.vtkPolyData()~%" source-name2)
                 (let ((xx (make-array (* 2 n) :element-type 'flonum))
                       (yy (make-array (* 2 n) :element-type 'flonum))
                       (zz (make-array (* 2 n) :element-type 'flonum))
                       (ind 0))
                   (loop for k from 0 below n do
                     (setf (aref xx ind) (aref ax k)
                           (aref yy ind) (aref ay k)
                           (aref zz ind) 0.0)
                     (setf ind (1+ ind))
                     (setf (aref xx ind) (aref ax k)
                           (aref yy ind) (aref ay k)
                           (aref zz ind) (aref az k))
                     (setf ind (1+ ind)) )
                   (vtkpoints-code points-name2 source-name2 xx yy zz))
                 (vtkcellarray-code cellarray-name2 source-name2 1 
                                 (loop for k from 0 below n collect (list (* 2 k) (+ (* 2 k) 1))))
                 (vtktransform-code trans-name)

                 (cond
                   ((< line-type 0) ; line type is a tube
                      (concatenate 'string
                        (vtktransformpolydatafilter-code "auxfiltertube" source-name2 trans-name t)
                        (vtktubefilter-code filter-name "auxfiltertube" line-type)
                        (vtkpolydatamapper-code mapper-name filter-name t)))
                   (t
                      (concatenate 'string
                        (vtktransformpolydatafilter-code filter-name source-name2 trans-name t)
                        (vtkpolydatamapper-code mapper-name filter-name t))))))
            (t
               (concatenate 'string
                 (vtkcellarray-code cellarray-name source-name 1 (list (loop for k from 0 below n collect k)))
                 (vtktransform-code trans-name)
                 (cond
                   ((< line-type 0) ; line type is a tube
                      (concatenate 'string
                        (vtktransformpolydatafilter-code "auxfiltertube" source-name trans-name t)
                        (vtktubefilter-code filter-name "auxfiltertube" line-type)
                        (vtkpolydatamapper-code mapper-name filter-name t)))
                   (t
                      (concatenate 'string
                        (vtktransformpolydatafilter-code filter-name source-name trans-name t)
                        (vtkpolydatamapper-code mapper-name filter-name t))) ) ) ))

          (if (> *draw-enhanced3d-type* 0)
            (format nil "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
            "")

          (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
          (format nil "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
          (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))

          (if (>= line-type 0) ; when line type is not a tube, set line pattern
            (format nil "~a.GetProperty().SetLineStipplePattern(~a)~%~%"
                    actor-name
                    (case line-type
                       (0 "0x0001")
                       (1 "0xFFFF")
                       (2 "0xFF00")
                       (6 "0xFE10")))
            ""))))

    ; draw glyphs according to point-type
    (cond
      ((and (>= point-type 0)
            (<= point-type 5))
         (setf glyphpoints-name (get-glyphpoints-name)
               polydata-name    (get-polydata-name)
               cellarray-name   (get-cellarray-name)
               filter-name      (get-filter-name)
               mapper-name      (get-mapper-name)
               actor-name       (get-actor-name)
               color            (get-option '$color)
               opacity          (get-option '$opacity)
               linewidth        (get-option '$line_width) )

         (setf output-string
           (concatenate 'string
             output-string
             (case point-type
               (0 (vtkpoints-code glyphpoints-name nil
                     (make-array 1 :element-type 'flonum :initial-element 0.0)
                     (make-array 1 :element-type 'flonum :initial-element 0.0)
                     (make-array 1 :element-type 'flonum :initial-element 0.0)))
               (1 (vtkpoints-code glyphpoints-name nil 
                     (make-array 4 :element-type 'flonum
                                   :initial-contents (list (- point-size) point-size 0.0 0.0))
                     (make-array 4 :element-type 'flonum
                                   :initial-contents (list 0.0 0.0 0.0 0.0))
                     (make-array 4 :element-type 'flonum
                                   :initial-contents (list 0.0 0.0 (- point-size) point-size))))
               (2 (vtkpoints-code glyphpoints-name nil
                     (make-array 4 :element-type 'flonum
                                   :initial-contents (list point-size (- point-size) (- point-size) point-size))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list 0.0 0.0 0.0 0.0))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list point-size (- point-size) point-size (- point-size)))))
               (3 (vtkpoints-code glyphpoints-name nil
                     (make-array 8 :element-type 'flonum 
                                   :initial-contents (list point-size (- point-size) (- point-size) point-size 
                                                           (- point-size) point-size 0.0 0.0))
                     (make-array 8 :element-type 'flonum 
                                   :initial-contents (list 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0))
                     (make-array 8 :element-type 'flonum 
                                   :initial-contents (list point-size (- point-size) point-size (- point-size)
                                                           0.0 0.0 (- point-size) point-size))))
               (4 (vtkpoints-code glyphpoints-name nil
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list point-size (- point-size) (- point-size) point-size))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list 0.0 0.0 0.0 0.0))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list point-size point-size (- point-size) (- point-size)))))
               (5 (vtkpoints-code glyphpoints-name nil
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list (- point-size) point-size point-size (- point-size)))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list 0.0 0.0 0.0 0.0))
                     (make-array 4 :element-type 'flonum 
                                   :initial-contents (list point-size point-size (- point-size) (- point-size))))))
             (format nil "~a=vtk.vtkPolyData()~%" polydata-name)
             (format nil "~a.SetPoints(~a)~%" polydata-name glyphpoints-name)
             (case point-type
               (0     (vtkcellarray-code cellarray-name polydata-name 0 '((0))))
               ((1 2) (vtkcellarray-code cellarray-name polydata-name 1 '((0 1) (2 3))))
               (3     (vtkcellarray-code cellarray-name polydata-name 1 '((0 1) (2 3) (4 5) (6 7))))
               (4     (vtkcellarray-code cellarray-name polydata-name 1 '((0 1) (1 2) (2 3) (3 0))))
               (5     (vtkcellarray-code cellarray-name polydata-name 2 '((0 1 2 3))))
               (otherwise ""))
             (vtkglyph3d-code filter-name source-name (format nil "SetSourceData(~a)" polydata-name))
             (format nil "~a~%" (vtkpolydatamapper-code mapper-name filter-name t))
             (if (> *draw-enhanced3d-type* 0)
               (format nil "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
               "")
             (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
             (format nil "~a~%" (vtkactor-code actor-name nil color opacity linewidth nil))
             (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) t t))   )))

      ((and (>= point-type 14)
            (<= point-type 17))
         (setf solidsource-name (get-solidsource-name)
               filter-name      (get-filter-name)
               mapper-name      (get-mapper-name)
               actor-name       (get-actor-name)
               color            (get-option '$color)
               opacity          (get-option '$opacity) )
         (setf output-string
           (concatenate 'string
             output-string
             (case point-type
               (14 ; sphere glyph
                 (format nil "~a=vtk.vtkSphereSource()~%~a.SetRadius(~a)~%"
                         solidsource-name
                         solidsource-name
                         (/ point-size 2.0)))
               (15 ; cube glyph
                 (format nil "~a=vtk.vtkCubeSource()~%~a.SetXLength(~a)~%~a.SetYLength(~a)~%~a.SetZLength(~a)~%"
                         solidsource-name
                         solidsource-name
                         point-size
                         solidsource-name
                         point-size
                         solidsource-name
                         point-size))
               (16 ; cylinder glyph
                 (format nil "~a=vtk.vtkCylinderSource()~%~a.SetRadius(~a)~%~a.SetHeight(~a)~%"
                         solidsource-name
                         solidsource-name
                         (/ point-size 2.0)
                         solidsource-name
                         point-size))
               (17 ; cone glyph
                 (format nil "~a=vtk.vtkConeSource()~%~a.SetRadius(~a)~%~a.SetHeight(~a)~%"
                         solidsource-name
                         solidsource-name
                         (/ point-size 2.0)
                         solidsource-name
                         point-size)))
             (vtkglyph3d-code filter-name
                              source-name 
                             (format nil "SetSourceConnection(~a.GetOutputPort())" solidsource-name))
             (format nil "~a~%" (vtkpolydatamapper-code mapper-name filter-name t))
             (if (> *draw-enhanced3d-type* 0)
               (format nil "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
               "")
             (format nil "bounds.append(~a.GetBounds())~%" mapper-name)
             (format nil "~a~%" (vtkactor-glyph-code actor-name color opacity))
             (format nil "~a~%" (vtkextractpolydatageometry-code (get-extract-name) t t)) )))
      (t
         (merror "vtk3d: not recognized point_type")))))



;; 2D: points([[x1,y1], [x2,y2], [x3,y3],...])
;; -------------------------------------------
;; Options:
;;     point_size
;;     point_type
;;     points_joined
;;     line_width
;;     key
;;     line_type
;;     color
;;     transform
(defun vtk2d-points (arg1 &optional (arg2 nil))
  (let ((pointsjoined  (get-option '$points_joined))
        (pointtype     (get-option '$point_type))
        (pointsize     ($float  (get-option '$point_size)))
        (linetype      (get-option '$line_type))
        (color         (hex-to-numeric-list (get-option '$color)))
        (linewidth     (get-option '$line_width))
        (key           (get-option '$key))
        (arrayX-name   (get-arrayX-name))
        (arrayY-name   (get-arrayY-name))
        (table-name    (get-table-name))
        (str           (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        tmp x y ax ay n)

    (when (not (string= (string-trim " " key) ""))
       (incf *vtk-2dkey-counter*) )
    ; check type of input
    (cond 
       ((and ($listp arg1)
             (null arg2)
             (every #'$listp (rest arg1)))     ; xy format
          (setf tmp (mapcar #'rest (rest arg1)))
          (setf x (map 'list #'$float (map 'list #'first tmp))
                y (map 'list #'$float (map 'list #'second tmp))) )
       ((and ($matrixp arg1)
             (= (length (cadr arg1)) 3)
             (null arg2))                 ; two-column matrix
          (setf tmp (mapcar #'rest (rest arg1)))
          (setf x (map 'list #'$float (map 'list #'first tmp))
                y (map 'list #'$float (map 'list #'second tmp))) )
       ((and ($listp arg1)
             (null arg2)
             (notany #'$listp (rest arg1)))   ; y format
          (setf x (loop for xx from 1 to (length (rest arg1)) collect ($float xx))
                y (map 'list #'$float (rest arg1))))
       ((and ($matrixp arg1)
             (= (length (cadr arg1)) 2)
             (null arg2))                 ; one-column matrix
          (setf x (loop for xx from 1 to (length (rest arg1)) collect ($float xx))
                y (map 'list #'$float (map 'list #'second (rest arg1)))))
       ((and ($matrixp arg1)
             (= ($length arg1) 1)
             (null arg2))                 ; one-row matrix
          (setf x (loop for xx from 1 to (length (cdadr arg1)) collect ($float xx))
                y (map 'list #'$float (cdadr arg1))))
       ((and ($listp arg1)
             ($listp arg2)
             (= (length arg1) (length arg2)))  ; xx yy format
          (setf x (map 'list #'$float (rest arg1))
                y (map 'list #'$float (rest arg2))))
       ((and ($matrixp arg1)
             (= ($length arg1) 2)
             (null arg2))            ; two-row matrix
          (setf x (map 'list #'$float (cdadr arg1))
                y (map 'list #'$float (cdaddr arg1))))
       (t (merror "draw (points2d): incorrect input format")))
    (setf n (length x))
    (transform-lists 2)
    (setf ax (make-array n :element-type 'flonum :initial-contents x)
          ay (make-array n :element-type 'flonum :initial-contents y))

    ; python code
    (format str "~a=vtk.vtkFloatArray()~%" arrayX-name)
    (format str "~a.SetName(\"~a\")~%" arrayX-name arrayX-name)
    (format str "~a=vtk.vtkFloatArray()~%" arrayY-name)
    (format str "~a.SetName(\"~a\")~%" arrayY-name key)
    (loop for i from 0 below n do
      (format str "~a.InsertNextValue(~a)~%" arrayX-name (aref ax i))
      (format str "~a.InsertNextValue(~a)~%" arrayY-name (aref ay i))  )
    (format str "~a=vtk.vtkTable()~%" table-name)
    (format str "~a.AddColumn(~a)~%" table-name arrayX-name)
    (format str "~a.AddColumn(~a)~%~%" table-name arrayY-name)
    (cond
      ((equal pointsjoined t)
        (format str "line = chart~a.AddPlot(~a)~%" *vtk-chart-counter* 0)
        (format str "line.SetInputData(~a,0,1)~%" table-name)
        (format str "line.SetColor(~a,~a,~a,255)~%"
          (round (* 255 (first color)))
          (round (* 255 (second color)))
          (round (* 255 (third color))) )
        (format str "line.SetWidth(~a)~%" linewidth)
        (format str "#line.SetLegendVisibility(0)~%")
        (format str "line.SetMarkerStyle(0)~%")
        (format str "line.GetPen().SetLineType(~a)~%"
          (case linetype ; translate some gnuplot codes into vtk codes
            (0 3)
            (6 4)
            (otherwise linetype) ) ))
      ((equal pointsjoined '$impulses)
        (let (tbl impx impy)
          (loop for i from 0 below n do
            (setf tbl (get-table-name)
                  impx (get-arrayX-name)
                  impy (get-arrayY-name))
            (format str "~a=vtk.vtkTable()~%" tbl)
            (format str "~a=vtk.vtkFloatArray()~%" impx)
            (format str "~a.SetNumberOfTuples(2)~%" impx)
            (format str "~a.SetName(\"~a\")~%" impx impx)
            (format str "~a=vtk.vtkFloatArray()~%" impy)
            (format str "~a.SetNumberOfTuples(2)~%" impy)
            (format str "~a.SetName(\"~a\")~%" impy impy)
            (format str "~a.InsertValue(0,~a.GetColumn(0).GetValue(~a))~%" impx table-name i)
            (format str "~a.InsertValue(1,~a.GetColumn(0).GetValue(~a))~%" impx table-name i)
            (format str "~a.InsertValue(0,~a.GetColumn(1).GetValue(~a))~%" impy table-name i)
            (format str "~a.InsertValue(1,0.0)~%" impy)
            (format str "~a.AddColumn(~a)~%" tbl impx)
            (format str "~a.AddColumn(~a)~%" tbl impy)
            (format str "line = chart~a.AddPlot(0)~%" *vtk-chart-counter*)
            (format str "line.SetInputData(~a,0,1)~%" tbl)
            (format str "line.SetColor(~a,~a,~a,255)~%"
              (round (* 255 (first color)))
              (round (* 255 (second color)))
              (round (* 255 (third color))) )
            (format str "line.SetWidth(~a)~%" linewidth)
            (format str "#line.SetLegendVisibility(0)~%~%") )) ) )
    (format str "line = chart~a.AddPlot(~a)~%" *vtk-chart-counter* 1)
    (format str "line.SetInputData(~a,0,1)~%" table-name)
    (format str "line.SetColor(~a,~a,~a,255)~%"
      (round (* 255 (first color)))
      (round (* 255 (second color)))
      (round (* 255 (third color))) )
    (format str "line.SetWidth(~a)~%" pointsize)
    (format str "#line.SetLegendVisibility(~a)~%" 
      (if (string= (string-trim " " key) "")
       0
       1 ))
    (format str "line.SetMarkerStyle(~a)~%~%"
      (case pointtype
        ((-1 0) 0)
        (1 2)
        ((2 3) 1)
        ((4 5 15) 3)
        ((6 7 14) 4)
        ((12 13) 5)
        (otherwise 3) ))
    str  ))



;; 3D: parametric(xfun,yfun,zfun,par1,parmin,parmax)
;; -------------------------------------------------
(defun vtk3d-parametric (xfun yfun zfun par1 parmin parmax)
  (let* ((nticks          (get-option '$nticks))
         (color           (get-option '$color))
         (line-type       (get-option '$line_type))
         (opacity         (get-option '$opacity))
         (linewidth       (get-option '$line_width))
         (wiredsurface    (get-option '$wired_surface))
         (source-name     (get-source-name))
         (points-name     (get-points-name))
         (cellarray-name  (get-cellarray-name))
         (floatarray-name (get-floatarray-name))
         (trans-name      (get-trans-name))
         (filter-name     (get-filter-name))
         (mapper-name     (get-mapper-name))
         (actor-name      (get-actor-name))
         ($numer          t)
         (tmin            ($float parmin))
         (tmax            ($float parmax))
         (tt              tmin)
         (eps             (/ (- tmax tmin) (- nticks 1)))
         (str             (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         (count           -1)
         lookup-table-name scalars f1 f2 f3 x y z xx yy zz)
    (check-enhanced3d-model "parametric" '(0 1 3 99))
    (when (= *draw-enhanced3d-type* 99)
       (update-enhanced3d-expression (list '(mlist) par1)))
    (if (< tmax tmin)
       (merror "vtk3d (parametric): illegal range"))
    (setq f1 (coerce-float-fun xfun `((mlist) ,par1)))
    (setq f2 (coerce-float-fun yfun `((mlist) ,par1)))
    (setq f3 (coerce-float-fun zfun `((mlist) ,par1)))
    (setf x (make-array nticks :element-type 'flonum)
          y (make-array nticks :element-type 'flonum)
          z (make-array nticks :element-type 'flonum))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array nticks :element-type 'flonum)))
    (dotimes (k nticks)
      (setf xx (funcall f1 tt))
      (setf yy (funcall f2 tt))
      (setf zz (funcall f3 tt))
      (case *draw-enhanced3d-type*
        ((1 99) (setf (aref scalars k) (funcall *draw-enhanced3d-fun* tt)))
        (3      (setf (aref scalars k) (funcall *draw-enhanced3d-fun* xx yy zz))))
      (transform-point 3)
      (setf (aref x (incf count)) xx)
      (setf (aref y count) yy)
      (setf (aref z count) zz)
      (setf tt (+ tt eps)) )
    (when (> *draw-enhanced3d-type* 0)
      (let ((lut (check-lookup-table)))
        (setf lookup-table-name (car lut))
        (format str "~a~%" (cadr lut))))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 1 
                                          (list (loop for k from 0 below nticks collect k))))
    (format str "~a~%" (vtktransform-code trans-name))
    (if (< line-type 0) ; line type is a tube
      (format str "~a~%" (vtktransformpolydatafilter-code "auxfiltertube" source-name trans-name t))
      (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t) ) )
    (cond
      ((< line-type 0) ; line type is a tube
         (format str "~a~%" (vtktubefilter-code filter-name "auxfiltertube" line-type))
         (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name t)))
      (t
        (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name t))))
    (format str "bounds.append(~a.GetBounds())~%" mapper-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
    (when (> *draw-enhanced3d-type* 0)
        (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars nil))
        (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
        (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
              (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )
    (when (>= line-type 0) ; when line type is not a tube, set line pattern
        (format str "~a.GetProperty().SetLineStipplePattern(~a)~%~%"
                actor-name
                (case line-type
                   (0 "0x0001")
                   (1 "0xFFFF")
                   (2 "0xFF00")
                   (6 "0xFE10"))) )
    str) )




;; 2D: parametric(xfun,yfun,par,parmin,parmax)
;; -----------------------------------
;; Options:
;;     nticks
;;     line_width
;;     line_type
;;     color
;;     key
(defun vtk2d-parametric (xfun yfun par parmin parmax)
  (let* ((nticks      (get-option '$nticks))
         (linewidth   (get-option '$line_width))
         (linetype    (get-option '$line_type))
         (color       (hex-to-numeric-list (get-option '$color)))
         (key         (get-option '$key))
         (arrayX-name (get-arrayX-name))
         (arrayY-name (get-arrayY-name))
         (table-name  (get-table-name))
         (tmin        ($float parmin))
         (tmax        ($float parmax))
         (str         (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         ($numer      t)
         (eps         (/ (- tmax tmin) (- ($float nticks) 1)))
         (tt          ($float parmin))
         (*plot-realpart* *plot-realpart*)
         result f1 f2 xx yy result-array)

    (when (< tmax tmin)
       (merror "draw2d (parametric): illegal range"))
    (when (not (string= (string-trim " " key) ""))
       (incf *vtk-2dkey-counter*) )
    (when (not (subsetp (append (rest ($listofvars xfun)) (rest ($listofvars yfun))) (list par) :test #'like))
       (merror "draw2d (parametric): non defined variable"))
    (setq *plot-realpart* (get-option '$draw_realpart))
    (setq f1 (coerce-float-fun xfun `((mlist) ,par)))
    (setq f2 (coerce-float-fun yfun `((mlist) ,par)))
    (setf result
       (loop
          do (setf xx ($float (funcall f1 tt)))
             (setf yy ($float (funcall f2 tt)))
             (transform-point 2)
          collect xx
          collect yy
          when (>= tt tmax) do (loop-finish)
          do (setq tt (+ tt eps))
             (if (>= tt tmax) (setq tt tmax)) ))
    (setf result-array (make-array (length result) :initial-contents result))

    ; python code
    (format str "~a=vtk.vtkFloatArray()~%" arrayX-name)
    (format str "~a.SetName(\"~a\")~%" arrayX-name arrayX-name)
    (format str "~a=vtk.vtkFloatArray()~%" arrayY-name)
    (format str "~a.SetName(\"~a\")~%" arrayY-name key)
    (loop for i from 0 below (length result) by 2 do
      (format str "~a.InsertNextValue(~a)~%" arrayX-name (aref result-array i))
      (format str "~a.InsertNextValue(~a)~%" arrayY-name (aref result-array (+ i 1)))  )
    (format str "~a=vtk.vtkTable()~%" table-name)
    (format str "~a.AddColumn(~a)~%" table-name arrayX-name)
    (format str "~a.AddColumn(~a)~%" table-name arrayY-name)
    (format str "line=chart~a.AddPlot(0)~%" *vtk-chart-counter*)
    (format str "line.SetInputData(~a,0,1)~%" table-name)
    (format str "line.SetColor(~a,~a,~a,255)~%"
      (round (* 255 (first color)))
      (round (* 255 (second color)))
      (round (* 255 (third color))) )
    (format str "line.SetWidth(~a)~%" linewidth)
    (format str "#line.SetLegendVisibility(~a)~%" 
      (if (string= (string-trim " " key) "")
       0
       1 ))
    (format str "line.GetPen().SetLineType(~a)~%~%"
      (case linetype ; translate some gnuplot codes into vtk codes
        (0 3)
        (6 4)
        (otherwise linetype) ) )
    str ))



;; 2D: polar(radius,ang,minang,maxang)
;; -----------------------------------
;; Options:
;;     nticks
;;     line_width
;;     line_type
;;     color
;;     key
(defun vtk2d-polar (radius ang minang maxang)
  (vtk2d-parametric `((mtimes simp) ,radius ((%cos simp) ,ang))
                    `((mtimes simp) ,radius ((%sin simp) ,ang))
                    ang minang maxang) )



;; 3D: parametric_surface(xfun,yfun,zfun,par1,par1min,par1max,par2,par2min,par2max)
;; --------------------------------------------------------------------------------
(defun vtk3d-parametric_surface (xfun yfun zfun par1 par1min par1max par2 par2min par2max)
  (let* ((xu_grid        (get-option '$xu_grid))
         (yv_grid        (get-option '$yv_grid))
         (color          (get-option '$color))
         (opacity        (get-option '$opacity))
         (linewidth      (get-option '$line_width))
         (wiredsurface   (get-option '$wired_surface))
         (umin           ($float par1min))
         (umax           ($float par1max))
         (vmin           ($float par2min))
         (vmax           ($float par2max))
         (epsu           (/ (- umax umin) xu_grid))
         (epsv           (/ (- vmax vmin) yv_grid))
         (source-name    (get-source-name))
         (points-name    (get-points-name))
         (cellarray-name (get-cellarray-name))
         (mapper-name    (get-mapper-name))
         (actor-name     (get-actor-name))
         (trans-name     (get-trans-name))
         (filter-name    (get-filter-name))
         (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         (scalars2-count -1)
         (scalars-count  -1)
         (nx             (+ xu_grid 1))
         (ny             (+ yv_grid 1))
         ($numer         t)
         (count          -1)
         (scalars        nil) ; used for coloring
         (scalars2       nil) ; used for isolines
         (xx 0.0) (uu 0.0)
         (yy 0.0) (vv 0.0)
         (zz 0.0)
         floatarray-name mapper2-name filter2-name floatarray2-name lookup-table-name
         f1 f2 f3 x y z)
    (check-enhanced3d-model "parametric_surface" '(0 2 3 99))
    (check-isolines-model "parametric_surface" '(0 2 3 99))
    (when (= *draw-enhanced3d-type* 99)
       (update-enhanced3d-expression (list '(mlist) par1 par2)))
    (when (= *draw-isolines-type* 99)
       (update-isolines-expression (list '(mlist) par1 par2)))
    (when (or (< umax umin)
              (< vmax vmin))
       (merror "vtk3d (parametric_surface): illegal range"))
    (setq f1 (coerce-float-fun xfun `((mlist) ,par1 ,par2)))
    (setq f2 (coerce-float-fun yfun `((mlist) ,par1 ,par2)))
    (setq f3 (coerce-float-fun zfun `((mlist) ,par1 ,par2)))
    (setf x (make-array (* nx ny) :element-type 'flonum)
          y (make-array (* nx ny) :element-type 'flonum)
          z (make-array (* nx ny) :element-type 'flonum))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array (* nx ny) :element-type 'flonum)))
    (when (> *draw-isolines-type* 0)
      (setf scalars2 (make-array (* nx ny) :element-type 'flonum)))
    (loop for j below ny
           initially (setf vv vmin)
           do (setf uu umin)
           (loop for i below nx
                  do
                  (setf xx (funcall f1 uu vv))
                  (setf yy (funcall f2 uu vv))
                  (setf zz (funcall f3 uu vv))
                  ; geometric transformation
                  (transform-point 3)
                  (setf (aref x (incf count)) xx)
                  (setf (aref y count) yy)
                  (setf (aref z count) zz)
                  ; check texture model
                  (case *draw-enhanced3d-type*
                    ((2 99) (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* uu vv)))
                    (3      (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy zz))) )
                  ; check isolines model
                  (case *draw-isolines-type*
                    ((2 99) (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* uu vv)))
                    (3      (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy zz))) )
                  (setq uu (+ uu epsu)))
           (setq vv (+ vv epsv)))
    (when (> *draw-enhanced3d-type* 0)
      (let ((lut (check-lookup-table)))
        (setf lookup-table-name (car lut))
        (format str "~a~%" (cadr lut))))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2 (build-surface-grid nx ny)))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name nil))

    (format str "bounds.append(~a.GetBounds())~%" points-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil t))

    (when (> *draw-enhanced3d-type* 0)
      (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
      (format str "~a.SetScalarModeToUsePointFieldData()~%" mapper-name)
      (format str "~a.ScalarVisibilityOn()~%~%" mapper-name)
      (setf floatarray-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars))
      ; remove next string if we want isolines and solid color when enhanced3d is not active
      (format str "~a.SelectColorArray(\"name~a\")~%" mapper-name floatarray-name)
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )

    (when (> *draw-isolines-type* 0)
      (setf floatarray2-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray2-name source-name scalars2))
      (setf filter2-name (get-filter-name))
      (format str "~a~%" (vtkContourFilter-code filter2-name filter-name))
      (setf mapper2-name (get-mapper-name))
      (format str "~a" (vtkpolydatamapper-isoline-code mapper2-name source-name floatarray2-name))
      (format str "~a~%" (vtkactor-isoline-code (get-actor-name) linewidth))
      (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray2-name)) )

    str ))



;; spherical(radius,az,minazi,maxazi,zen,minzen,maxzen)
;; ----------------------------------------------------
(defun vtk3d-spherical (radius azi minazi maxazi zen minzen maxzen)
  (vtk3d-parametric_surface
    `((mtimes simp) ,radius ((%sin simp) ,zen) ((%cos simp) ,azi))
    `((mtimes simp) ,radius ((%sin simp) ,zen) ((%sin simp) ,azi))
    `((mtimes simp) ,radius ((%cos simp) ,zen))
    azi minazi maxazi
    zen minzen maxzen))



;; cylindrical(r,z,minz,maxz,azi,minazi,maxazi)
;; --------------------------------------------
(defun vtk3d-cylindrical (r z minz maxz azi minazi maxazi)
  (vtk3d-parametric_surface
    `((mtimes simp) ,r ((%cos simp) ,azi))
    `((mtimes simp) ,r ((%sin simp) ,azi))
    z 
    z minz maxz
    azi minazi maxazi))



;; 3D: explicit(fcn,par1,minval1,maxval1,par2,minval2,maxval2)
;; -----------------------------------------------------------
(defun vtk3d-explicit (fcn par1 minval1 maxval1 par2 minval2 maxval2)
  (let* ((xu_grid        (get-option '$xu_grid))
         (yv_grid        (get-option '$yv_grid))
         (color          (get-option '$color))
         (opacity        (get-option '$opacity))
         (linewidth      (get-option '$line_width))
         (wiredsurface   (get-option '$wired_surface))
         (fminval1       ($float minval1))
         (fminval2       ($float minval2))
         (fmaxval1       ($float maxval1))
         (fmaxval2       ($float maxval2))
         (epsx           (/ (- fmaxval1 fminval1) xu_grid))
         (epsy           (/ (- fmaxval2 fminval2) yv_grid))
         (source-name    (get-source-name))
         (points-name    (get-points-name))
         (cellarray-name (get-cellarray-name))
         (mapper-name    (get-mapper-name))
         (actor-name     (get-actor-name))
         (trans-name     (get-trans-name))
         (filter-name    (get-filter-name))
         (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         ($numer         t)
         (count          -1)
         (scalars        nil) ; used for coloring
         (scalars2       nil) ; used for isolines
         (scalars-count  -1)
         (scalars2-count -1)
         (nx             (+ xu_grid 1))
         (ny             (+ yv_grid 1))
         (xx 0.0) (uu 0.0)
         (yy 0.0) (vv 0.0)
         (zz 0.0)
         floatarray-name floatarray2-name mapper2-name filter2-name lookup-table-name
         x y z)
    (check-enhanced3d-model "explicit" '(0 2 3 99))
    (check-isolines-model "explicit" '(0 2 3 99))
    (when (= *draw-enhanced3d-type* 99)
       (update-enhanced3d-expression (list '(mlist) par1 par2)))
    (when (= *draw-isolines-type* 99)
       (update-isolines-expression (list '(mlist) par1 par2)))
    (setq fcn (coerce-float-fun fcn `((mlist) ,par1 ,par2)))
    (setf x (make-array (* nx ny) :element-type 'flonum)
          y (make-array (* nx ny) :element-type 'flonum)
          z (make-array (* nx ny) :element-type 'flonum))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array (* nx ny) :element-type 'flonum)))
    (when (> *draw-isolines-type* 0)
      (setf scalars2 (make-array (* nx ny) :element-type 'flonum)))
    (loop for j below ny
           initially (setf vv fminval2)
           do (setf uu fminval1)
           (loop for i below nx
                  do
                  (setf xx uu
                        yy vv)
                  (setf zz (funcall fcn xx yy))
                  ; geometric transformation
                  (transform-point 3)
                  (setf (aref x (incf count)) xx)
                  (setf (aref y count) yy)
                  (setf (aref z count) zz)
                  ; check texture model
                  (case *draw-enhanced3d-type*
                    ((2 99) (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy)))
                    (3      (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy zz))) )
                  ; check isolines model
                  (case *draw-isolines-type*
                    ((2 99) (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy)))
                    (3      (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy zz))) )
                  (setq uu (+ uu epsx)))
           (setq vv (+ vv epsy)))
    (when (> *draw-enhanced3d-type* 0)
      (let ((lut (check-lookup-table)))
        (setf lookup-table-name (car lut))
        (format str "~a~%" (cadr lut))))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2 (build-surface-grid nx ny)))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name nil))

    (format str "bounds.append(~a.GetBounds())~%" points-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil t))

    (when (> *draw-enhanced3d-type* 0)
      (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
      (format str "~a.SetScalarModeToUsePointFieldData()~%" mapper-name)
      (format str "~a.ScalarVisibilityOn()~%~%" mapper-name)
      (setf floatarray-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars))
      ; remove next string if we want isolines and solid color when enhanced3d is not active
      (format str "~a.SelectColorArray(\"name~a\")~%" mapper-name floatarray-name)
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )

    (when (> *draw-isolines-type* 0)
      (setf floatarray2-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray2-name source-name scalars2))
      (setf filter2-name (get-filter-name))
      (format str "~a~%" (vtkContourFilter-code filter2-name filter-name))
      (setf mapper2-name (get-mapper-name))
      (format str "~a" (vtkpolydatamapper-isoline-code mapper2-name source-name floatarray2-name))
      (format str "~a~%" (vtkactor-isoline-code (get-actor-name) linewidth))
      (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray2-name))  )

    str ))



;; 2D: explicit(fcn,var,minval,maxval)
;; -----------------------------------
;; Options:
;;     nticks
;;     adapt_depth
;;     line_width
;;     line_type
;;     color
;;     key
(defun vtk2d-explicit (fcn var minval maxval)
  (let* ((nticks      (get-option '$nticks))
         (adaptdepth  (get-option '$adapt_depth))
         (linewidth   (get-option '$line_width))
         (linetype    (get-option '$line_type))
         (color       (hex-to-numeric-list (get-option '$color)))
         (fillcolor   (hex-to-numeric-list (get-option '$fill_color)))
         (key         (get-option '$key))
         (xmin        ($float minval))
         (xmax        ($float maxval))
         (x-step      (/ (- xmax xmin) ($float nticks) 2))
         (arrayX-name (get-arrayX-name))
         (arrayY-name (get-arrayY-name))
         (table-name  (get-table-name))
         (str         (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         (*plot-realpart* *plot-realpart*)
         ($numer t)
         x-samples y-samples result result-array )
    (when (< xmax xmin)
       (merror "draw2d (explicit): illegal range"))
    (when (not (string= (string-trim " " key) ""))
       (incf *vtk-2dkey-counter*) )
    (when (get-option '$logx)
      (setf xmin (log xmin))
      (setf xmax (log xmax))
      (setf x-step (/ (- xmax xmin) ($float nticks) 2)))
    (setq *plot-realpart* (get-option '$draw_realpart))
    (setq fcn (coerce-float-fun fcn `((mlist) ,var)))
    (flet ((fun (x)
               (let ((y (if (get-option '$logx)
                            (funcall fcn (exp x))
                            (funcall fcn x))))
                 (if (and (get-option '$logy)
                          (numberp y))
                     (if (> y 0)
                       (log y)
                       (merror "draw2d (explicit): logarithm of negative number"))
                     y))))
      (dotimes (k (1+ (* 2 nticks)))
        (let ((x (+ xmin (* k x-step))))
          (push x x-samples)
          (push (fun x) y-samples)))
      (setf x-samples (nreverse x-samples))
      (setf y-samples (nreverse y-samples))
      ;; For each region, adaptively plot it.
      (do ((x-start x-samples (cddr x-start))
           (x-mid (cdr x-samples) (cddr x-mid))
           (x-end (cddr x-samples) (cddr x-end))
           (y-start y-samples (cddr y-start))
           (y-mid (cdr y-samples) (cddr y-mid))
           (y-end (cddr y-samples) (cddr y-end)))
          ((null x-end))
        ;; The region is x-start to x-end, with mid-point x-mid.
        (let ((sublst (adaptive-plot #'fun (car x-start) (car x-mid) (car x-end)
                                           (car y-start) (car y-mid) (car y-end)
                                           adaptdepth 1e-5)))
          (when (notevery #'(lambda (x) (or (numberp x) (eq x t) )) sublst)
            (let ((items sublst) (item 'nil))
	      ;; Search for the item in sublist that is the undefined variable
	      (while items
		(when (not (or (numberp (car items)) (eq (car items) t) ))
		    (setq item (car items)) )
		(setq items (cdr items)) )
	      (merror "draw2d (explicit): non defined variable in term ~M" item) ) )
          (when (not (null result))
            (setf sublst (cddr sublst)))
          (do ((lst sublst (cddr lst)))
              ((null lst) 'done)
            (setf result (append result
                                 (list
                                   (if (and (get-option '$logx)
                                            (numberp (first lst)))
                                     (exp (first lst))
                                     (first lst))
                                   (if (and (get-option '$logy)
                                            (numberp (second lst)))
                                     (exp (second lst))
                                     (second lst)))))))))
    (cond
      ((> *draw-transform-dimensions* 0)
         ; With geometric transformation.
         ; When option filled_func in not nil,
         ; geometric transformation is ignored
         (setf result-array (make-array (length result)))
         (setf xmin most-positive-double-float
               xmax most-negative-double-float)
         (let (xold yold x y (count -1))
           (do ((lis result (cddr lis)))
               ((null lis))
             (setf xold (first lis)
                   yold (second lis))
             (setf x (funcall *draw-transform-f1* xold yold)
                   y (funcall *draw-transform-f2* xold yold))
             (setf (aref result-array (incf count)) x)
             (setf (aref result-array (incf count)) y)  )  ) )
      (t
         ; No geometric transformation invoked.
         (setf result-array (make-array (length result)
                                        :initial-contents result))))
    ; python code
    (format str "~a=vtk.vtkFloatArray()~%" arrayX-name)
    (format str "~a.SetName(\"~a\")~%" arrayX-name arrayX-name)
    (format str "~a=vtk.vtkFloatArray()~%" arrayY-name)
    (format str "~a.SetName(\"~a\")~%" arrayY-name key)
    (loop for i from 0 below (length result) by 2 do
      (when (not (equal (aref result-array (+ i 1)) t))
        ; in case of division by zero, do not insert next value.
        ; A vertical line will be plotted, which should be fixed.
        (format str "~a.InsertNextValue(~a)~%" arrayX-name (aref result-array i))
        (format str "~a.InsertNextValue(~a)~%" arrayY-name (aref result-array (+ i 1))) ) )
    (format str "~a=vtk.vtkTable()~%" table-name)
    (format str "~a.AddColumn(~a)~%" table-name arrayX-name)
    (format str "~a.AddColumn(~a)~%" table-name arrayY-name)
    (format str "line=chart~a.AddPlot(~a)~%"
      *vtk-chart-counter*
      (if (get-option '$filled_func) 3 0))
    (format str "line.SetInputData(~a,0,1)~%" table-name)
    (let (col)
      (if (get-option '$filled_func)
        (setf col fillcolor)
        (setf col color))
      (format str "line.SetColor(~a,~a,~a,255)~%"
        (round (* 255 (first  col)))
        (round (* 255 (second col)))
        (round (* 255 (third  col))) ))
    (format str "line.SetWidth(~a)~%" linewidth)
; not present in 6.2
;    (format str "line.SetLegendVisibility(~a)~%" 
;      (if (string= (string-trim " " key) "")
;       0
;       1 ))
    (format str "line.GetPen().SetLineType(~a)~%~%"
      (case linetype ; translate some gnuplot codes into vtk codes
        (0 3)
        (6 4)
        (otherwise linetype) ) )
    str ))



;; 3d: elevation_grid(mat x0 y0 width height)
;; ------------------------------------------
(defun vtk3d-elevation_grid (mat x0 y0 width height)
  (let* ((fx0            ($float x0))
         (fy0            ($float y0))
         (fwidth         ($float width))
         (fheight        ($float height))
         (color          (get-option '$color))
         (opacity        (get-option '$opacity))
         (linewidth      (get-option '$line_width))
         (wiredsurface   (get-option '$wired_surface))
         (source-name    (get-source-name))
         (points-name    (get-points-name))
         (cellarray-name (get-cellarray-name))
         (mapper-name    (get-mapper-name))
         (actor-name     (get-actor-name))
         (trans-name     (get-trans-name))
         (filter-name    (get-filter-name))
         (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         (xi             0.0)
         (yi             (+ fy0 fheight))
         (xx             0.0)
         (yy             0.0)
         (zz             0.0)
         (count          -1)
         (scalars        nil) ; used for coloring
         (scalars2       nil) ; used for isolines
         (scalars-count  -1)
         (scalars2-count -1)
         floatarray-name floatarray2-name mapper2-name filter2-name lookup-table-name
         ny nx dx dy x y z)
    (check-enhanced3d-model "elevation_grid" '(0 2 3))
    (check-isolines-model   "elevation_grid" '(0 2 3))
    (when (null ($matrixp mat))
      (merror "draw3d (elevation_grid): Argument not recognized"))
    (setf nx (length (cdadr mat))
          ny (length (cdr mat)))
    (setf dx (/ fwidth (1- nx))
          dy (/ fheight (1- ny)))
    (setf x (make-array (* nx ny) :element-type 'flonum)
          y (make-array (* nx ny) :element-type 'flonum)
          z (make-array (* nx ny) :element-type 'flonum))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array (* nx ny) :element-type 'flonum)))
    (when (> *draw-isolines-type* 0)
      (setf scalars2 (make-array (* nx ny) :element-type 'flonum)))
    (loop for row on (cdr mat) by #'cdr do
       (setf xi fx0)
       (loop for col on (cdar row) by #'cdr do
          (setf xx xi
                yy yi)
          (setf zz ($float (car col)))
          ; geometric transformation
          (transform-point 3)
          (setf (aref x (incf count)) xx)
          (setf (aref y count) yy)
          (setf (aref z count) zz)
          ; check texture model
          (case *draw-enhanced3d-type*
            (2 (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy)))
            (3 (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy zz))))
          ; check isolines model
          (case *draw-isolines-type*
            (2 (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy)))
            (3 (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy zz))) )
          (setf xi (+ xi dx)))
       (setf yi (- yi dy)))
    (when (> *draw-enhanced3d-type* 0)
      (let ((lut (check-lookup-table)))
        (setf lookup-table-name (car lut))
        (format str "~a~%" (cadr lut))))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2 (build-surface-grid nx ny)))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name nil))

    (format str "bounds.append(~a.GetBounds())~%" points-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil t))

    (when (> *draw-enhanced3d-type* 0)
      (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
      (format str "~a.SetScalarModeToUsePointFieldData()~%" mapper-name)
      (format str "~a.ScalarVisibilityOn()~%~%" mapper-name)
      (setf floatarray-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars))
      ; remove next string if we want isolines and solid color when enhanced3d is not active
      (format str "~a.SelectColorArray(\"name~a\")~%" mapper-name floatarray-name)
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )

    (when (> *draw-isolines-type* 0)
      (setf floatarray2-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray2-name source-name scalars2))
      (setf filter2-name (get-filter-name))
      (format str "~a~%" (vtkContourFilter-code filter2-name filter-name))
      (setf mapper2-name (get-mapper-name))
      (format str "~a" (vtkpolydatamapper-isoline-code mapper2-name source-name floatarray2-name))
      (format str "~a~%" (vtkactor-isoline-code (get-actor-name) linewidth))
      (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray2-name)) )

    str ))



;; 3d: implicit(expr,x,xmin,xmax,y,ymin,ymax,z,zmin,zmax)
;; ------------------------------------------------------
(defun build-surface-triangular-grid (ntri)
  (let ((poly nil)
        (cont -1)
        (p (/ ntri 3)))
    (dotimes (tri p)
      (setf poly (cons (list (incf cont) (incf cont) (incf cont)) poly)))
    (reverse poly)))

(defun vtk3d-implicit (expr par1 xmin xmax par2 ymin ymax par3 zmin zmax)
  (let ((fxmin          ($float xmin))
        (fxmax          ($float xmax))
        (fymin          ($float ymin))
        (fymax          ($float ymax))
        (fzmin          ($float zmin))
        (fzmax          ($float zmax))
        (color          (get-option '$color))
        (opacity        (get-option '$opacity))
        (linewidth      (get-option '$line_width))
        (wiredsurface   (get-option '$wired_surface))
        (transform      (get-option '$transform))
        (source-name    (get-source-name))
        (points-name    (get-points-name))
        (cellarray-name (get-cellarray-name))
        (mapper-name    (get-mapper-name))
        (actor-name     (get-actor-name))
        (trans-name     (get-trans-name))
        (filter-name    (get-filter-name))
        (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
        (scalars        nil) ; used for coloring
        (scalars2       nil) ; used for isolines
        floatarray-name floatarray2-name mapper2-name filter2-name lookup-table-name
        vertices numvert xx yy zz x y z)
    (check-enhanced3d-model "implicit" '(0 3 99))
    (check-isolines-model   "implicit" '(0 3 99))
    (when (= *draw-enhanced3d-type* 99)
       (update-enhanced3d-expression (list '(mlist) par1 par2 par3)))
    (when (= *draw-isolines-type* 99)
       (update-isolines-expression (list '(mlist) par1 par2 par3)))
    (setf vertices (find-triangles expr par1 fxmin fxmax par2 fymin fymax par3 fzmin fzmax))
    (when (null vertices)
      (merror "draw3d (implicit): no surface within these ranges"))
    (setf numvert (length vertices))
    (setf x (make-array numvert :element-type 'flonum :initial-contents (map 'list #'first vertices))
          y (make-array numvert :element-type 'flonum :initial-contents (map 'list #'second vertices))
          z (make-array numvert :element-type 'flonum :initial-contents (map 'list #'third vertices)))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array numvert :element-type 'flonum)))
    (when (> *draw-isolines-type* 0)
      (setf scalars2 (make-array numvert :element-type 'flonum)))
    (do ((nf 0 (1+ nf)))
        ((= nf numvert) 'done)
      (setf xx (aref x nf)
            yy (aref y nf)
            zz (aref z nf))
      ; geometric transformation
      (when (not (eq transform '$none))
        (transform-point 3)
        (setf (aref x nf) xx)
        (setf (aref y nf) yy)
        (setf (aref z nf) zz))
      ; check texture model
      (when (> *draw-enhanced3d-type* 0)
        (setf (aref scalars nf) (funcall *draw-enhanced3d-fun* xx yy zz)))
      ; check isolines model
      (when (> *draw-isolines-type* 0)
        (setf (aref scalars2 nf) (funcall *draw-isolines-fun* xx yy zz))) )
    (let ((lut (check-lookup-table)))
      (setf lookup-table-name (car lut))
      (format str "~a~%" (cadr lut)))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2 (build-surface-triangular-grid numvert)))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name nil))

    (format str "bounds.append(~a.GetBounds())~%" points-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil t))

    (when (> *draw-enhanced3d-type* 0)
      (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
      (format str "~a.SetScalarModeToUsePointFieldData()~%" mapper-name)
      (format str "~a.ScalarVisibilityOn()~%~%" mapper-name)
      (setf floatarray-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars))
      ; remove next string if we want isolines and solid color when enhanced3d is not active
      (format str "~a.SelectColorArray(\"name~a\")~%" mapper-name floatarray-name)
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )

    (when (> *draw-isolines-type* 0)
      (setf floatarray2-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray2-name source-name scalars2))
      (setf filter2-name (get-filter-name))
      (format str "~a~%" (vtkContourFilter-code filter2-name filter-name))
      (setf mapper2-name (get-mapper-name))
      (format str "~a" (vtkpolydatamapper-isoline-code mapper2-name source-name floatarray2-name))
      (format str "~a~%" (vtkactor-isoline-code (get-actor-name) linewidth))
      (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray2-name)) )

    str ))



;; 3d: label([string1,x1,y1,z1],[string2,x2,y2,z2],...)
;; ----------------------------------------------------
(defun vtk3d-label (&rest lab)
  (let ((font-size (get-option '$font_size))
        (colist    (hex-to-numeric-list (get-option '$color)))
        (out "")
        label-name
        polydatamapper-name
        labelactor-name
        text fx fy fz)
    (cond ((null lab)
             (merror "vtk (label): no arguments in object labels"))
          ((or (notevery #'$listp lab)
               (notevery #'(lambda (z) (= 4 ($length z))) lab))
             (merror "vtk3d (label): arguments must be lists of length 4"))
          (t
             (dolist (k lab)
               (setf text (format nil "\"~a\"" ($first k))
                     fx   ($float ($second k))
                     fy   ($float ($third k))
                     fz   ($float ($fourth k)))
               (when (or (not (floatp fx)) 
                         (not (floatp fy))
                         (not (floatp fz)))
                   (merror "vtk3d (label): non real 3d coordinates"))
               (setf labelactor-name     (get-labelactor-name)
                     label-name          (get-label-name)
                     polydatamapper-name (get-polydatamapper-name))
               (setf out
                     (concatenate 'string
                       out
                       (format nil "~a=vtk.vtkVectorText()~%" label-name)
                       (format nil "~a.SetText(~a)~%" label-name text)
                       (format nil "~a=vtk.vtkPolyDataMapper()~%" polydatamapper-name)
                       (format nil "~a.SetInputConnection(~a.GetOutputPort())~%"
                               polydatamapper-name
                               label-name)
                       (format nil "~a.ScalarVisibilityOff()~%" polydatamapper-name)
                       (format nil "~a=vtk.vtkFollower()~%" labelactor-name)
                       (format nil "~a.SetMapper(~a)~%" labelactor-name polydatamapper-name)
                       (format nil "~a.SetScale(~a,~a,~a)~%" labelactor-name font-size font-size font-size)
                       (format nil "~a.AddPosition(~a,~a,~a)~%" labelactor-name fx fy fz)
                       (format nil "~a.GetProperty().SetColor(~a,~a,~a)~%~%"
                               labelactor-name
                               (first colist)
                               (second colist)
                               (third colist)))))
             out))))



;; 3d: tube(xfun,yfun,zfun,rad,par,parmin,parmax)
;; ----------------------------------------------
(defmacro vtk-check-tube-extreme (ex cx cy cz)
    `(when (equal (nth ,ex (get-option '$capping)) t)
       (let ((cxx ,cx)
             (cyy ,cy)
             (czz ,cz))
         (when (> *draw-transform-dimensions* 0)
           (setf cxx (funcall *draw-transform-f1* ,cx ,cy ,cz)
                 cyy (funcall *draw-transform-f2* ,cx ,cy ,cz)
                 czz (funcall *draw-transform-f3* ,cx ,cy ,cz)))

        ; check texture model
        (when (> *draw-enhanced3d-type* 0)
          (case *draw-enhanced3d-type*
            ((1 99) (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* tt)))
            (3      (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* cxx cyy czz)))) )
        (dotimes (k vgrid)
          (setf (aref x (incf count)) cxx)
          (setf (aref y count) cyy)
          (setf (aref z count) czz) ))))

(defun vtk3d-tube (xfun yfun zfun rad par parmin parmax)
  (let* ((ugrid          (get-option '$xu_grid))
         (vgrid          (get-option '$yv_grid))
         (color          (get-option '$color))
         (opacity        (get-option '$opacity))
         (linewidth      (get-option '$line_width))
         (wiredsurface   (get-option '$wired_surface))
         (capping        (rest (get-option '$capping)))
         (tmin           ($float parmin))
         (tmax           ($float parmax))
         (vmax           6.283185307179586) ; = float(2*%pi)
         (teps           (/ (- tmax tmin) (- ugrid 1)))
         (veps           (/ vmax (- vgrid 1)))
         (nu             (+ ugrid (count t capping)))
         (nv             vgrid)
         (source-name    (get-source-name))
         (points-name    (get-points-name))
         (cellarray-name (get-cellarray-name))
         (trans-name     (get-trans-name))
         (filter-name    (get-filter-name))
         (mapper-name    (get-mapper-name))
         (actor-name     (get-actor-name))
         (str            (make-array 0 :element-type 'character :adjustable t :fill-pointer 0))
         (count          -1)
         (scalars        nil) ; used for coloring
         (scalars2       nil) ; used for isolines
         (scalars-count  -1)
         (scalars2-count -1)
         f1 f2 f3 radius
         cx cy cz nx ny nz
         ux uy uz vx vy vz
         xx yy zz module r vv rcos rsin
         cxold cyold czold
         uxold uyold uzold ttnext
         floatarray-name floatarray2-name mapper2-name filter2-name lookup-table-name
         x y z tt)
    (when (< tmax tmin)
       (merror "draw3d (tube): illegal parametric range"))
    (when (not (subsetp (rest ($append ($listofvars xfun) ($listofvars yfun)
                                       ($listofvars zfun) ($listofvars rad)))
                        (list par) :test #'like))
       (merror "draw3d (tube): non defined variable"))
    (check-enhanced3d-model "tube" '(0 1 3 99))
    (check-isolines-model "tube" '(0 1 3 99))
    (when (= *draw-enhanced3d-type* 99)
       (update-enhanced3d-expression (list '(mlist) par)))
    (when (= *draw-isolines-type* 99)
       (update-isolines-expression (list '(mlist) par)))
    (setq f1 (coerce-float-fun xfun `((mlist) ,par)))
    (setq f2 (coerce-float-fun yfun `((mlist) ,par)))
    (setq f3 (coerce-float-fun zfun `((mlist) ,par)))
    (setf radius (coerce-float-fun rad `((mlist) ,par)))
    (setf x (make-array (* nu nv) :element-type 'flonum)
          y (make-array (* nu nv) :element-type 'flonum)
          z (make-array (* nu nv) :element-type 'flonum))
    (when (> *draw-enhanced3d-type* 0)
      (setf scalars (make-array (* nu nv) :element-type 'flonum)))
    (when (> *draw-isolines-type* 0)
      (setf scalars2 (make-array (* nu nv) :element-type 'flonum)))
    (loop for j from 0 below ugrid do
      (setf tt (+ tmin (* j teps)))
      ; calculate center and radius of circle
      (cond
        ((= j 0)  ; 1st circle
           (setf cx (funcall f1 tt)
                 cy (funcall f2 tt)
                 cz (funcall f3 tt)
                 ttnext (+ tt teps))
           (vtk-check-tube-extreme 1 cx cy cz)
           (setf nx (- (funcall f1 ttnext) cx)
                 ny (- (funcall f2 ttnext) cy)
                 nz (- (funcall f3 ttnext) cz)))
        (t  ; all next circles
           (setf cxold cx
                 cyold cy
                 czold cz)
           (setf cx (funcall f1 tt)
                 cy (funcall f2 tt)
                 cz (funcall f3 tt))
           (setf nx (- cx cxold)
                 ny (- cy cyold)
                 nz (- cz czold))))
      (setf r (funcall radius tt))
      ; calculate the unitary normal vector      
      (setf module (sqrt (+ (* nx nx) (* ny ny) (* nz nz))))
      (setf nx (/ nx module)
            ny (/ ny module)
            nz (/ nz module))
      ; calculate unitary vector perpendicular to n=(nx,ny,nz)
      ; ux.nx+uy.ny+uz.nz=0 => ux=-t(ny+nz)/nx, uy=uz=t
      ; let's take t=1
      (cond
        ((= nx 0.0)
           (setf ux 1.0 uy 0.0 uz 0.0))
        ((= ny 0.0)
           (setf ux 0.0 uy 1.0 uz 0.0))
        ((= nz 0.0)
           (setf ux 0.0 uy 0.0 uz 1.0))
        (t  ; all other cases
           (setf ux (- (/ (+ ny nz) nx))
                 uy 1.0
                 uz 1.0)))
      (setf module (sqrt (+ (* ux ux) (* uy uy) (* uz uz))))
      (setf ux (/ ux module)
            uy (/ uy module)
            uz (/ uz module))
      (when (and (> tt tmin)
                 (< (+ (* uxold ux) (* uyold uy) (* uzold uz)) 0))
        (setf ux (- ux)
              uy (- uy)
              uz (- uz)))
      (setf uxold ux
            uyold uy
            uzold uz)
      ; vector v = n times u
      (setf vx (- (* ny uz) (* nz uy))
            vy (- (* nz ux) (* nx uz))
            vz (- (* nx uy) (* ny ux)))
      ; parametric equation of the circumference of radius
      ; r and centered at c=(cx,cy,cz):
      ; x(t) = c + r(cos(t)u + sin(t)v),
      ; for t in (0, 2*%pi)
      (setf vv 0.0)
      ; calculate points of one circumference
      (loop for i below vgrid do
        (setf rcos (* r (cos vv))
              rsin (* r (sin vv)))
        (setf xx (+ cx (* rcos ux) (* rsin vx))
              yy (+ cy (* rcos uy) (* rsin vy))
              zz (+ cz (* rcos uz) (* rsin vz)))
        ; geometric translation
        (transform-point 3)
        (setf (aref x (incf count)) xx)
        (setf (aref y count) yy)
        (setf (aref z count) zz)
        ; check texture model
        (when (> *draw-enhanced3d-type* 0)
          (case *draw-enhanced3d-type*
            ((1 99) (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* tt)))
            (3      (setf (aref scalars (incf scalars-count)) (funcall *draw-enhanced3d-fun* xx yy zz)))) )
        ; check isolines model
        (when (> *draw-isolines-type* 0)
          (case *draw-isolines-type*
            ((1 99) (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* tt)) )
            (3      (setf (aref scalars2 (incf scalars2-count)) (funcall *draw-isolines-fun* xx yy zz))) ))
        (setf vv (+ vv veps))
        (when (> vv vmax) (setf vv vmax))  ) ) ; end both loops
    (vtk-check-tube-extreme 2 cx cy cz)
    (let ((lut (check-lookup-table)))
      (setf lookup-table-name (car lut))
      (format str "~a~%" (cadr lut)))

    ; python code
    (format str "~a=vtk.vtkPolyData()~%" source-name)
    (format str "~a~%" (vtkpoints-code points-name source-name x y z))
    (format str "~a~%" (vtkcellarray-code cellarray-name source-name 2 (build-surface-grid nv nu)))
    (format str "~a~%" (vtktransform-code trans-name))
    (format str "~a~%" (vtktransformpolydatafilter-code filter-name source-name trans-name t))
    (format str "~a~%" (vtkpolydatamapper-code mapper-name filter-name nil))

    (format str "bounds.append(~a.GetBounds())~%" points-name)
    (format str "~a~%" (vtkactor-code actor-name nil color opacity linewidth wiredsurface))
    (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil t))

    (when (> *draw-enhanced3d-type* 0)
      (format str "~a.SetLookupTable(~a)~%" mapper-name lookup-table-name)
      (format str "~a.SetScalarModeToUsePointFieldData()~%" mapper-name)
      (format str "~a.ScalarVisibilityOn()~%~%" mapper-name)
      (setf floatarray-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray-name source-name scalars))
      ; remove next string if we want isolines and solid color when enhanced3d is not active
      (format str "~a.SelectColorArray(\"name~a\")~%" mapper-name floatarray-name)
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray-name)) )

    (when (> *draw-isolines-type* 0)
      (setf floatarray2-name (get-floatarray-name))
      (format str "~a~%" (vtkfloatarray-code floatarray2-name source-name scalars2))
      (setf filter2-name (get-filter-name))
      (format str "~a~%" (vtkContourFilter-code filter2-name filter-name))
      (setf mapper2-name (get-mapper-name))
      (format str "~a" (vtkpolydatamapper-isoline-code mapper2-name source-name floatarray2-name))
      (format str "~a~%" (vtkactor-isoline-code (get-actor-name) linewidth))
      (format str "~a~%" (vtkextractpolydatageometry-code (get-extract-name) nil nil))
      (setf (gethash *vtk-extract-counter* *enhanced3d-or-isolines-code*)
            (format nil "rescalearray(~a,~a)~%" points-name floatarray2-name)) )

    str ))





;; 2D SCENE BUILDER

(defvar *vtk2d-graphic-objects* (make-hash-table))

; table of 2d graphic objects
(setf (gethash '$explicit           *vtk2d-graphic-objects*) 'vtk2d-explicit
      (gethash '$parametric         *vtk2d-graphic-objects*) 'vtk2d-parametric
      (gethash '$points             *vtk2d-graphic-objects*) 'vtk2d-points
      (gethash '$polar              *vtk2d-graphic-objects*) 'vtk2d-polar        )

(defun make-vtk-scene-2d (args)
  (let ((objects "")
        (chart-name     (get-chart-name))
        (renderer-name  (get-renderer-name))
        largs obj)
    (ini-gr-options)
    (ini-local-option-variables)
    (user-defaults)
    (setf largs (listify-arguments args))
    (dolist (x largs)
      (cond ((equal ($op x) "=")
              (case ($lhs x)
                ($allocation       (update-allocation                           ($rhs x)))
                ($color            (update-color             '$color            ($rhs x)))
                ($fill_color       (update-color             '$fill_color       ($rhs x)))
                ($file_name        (update-string            '$file_name        ($rhs x)))
                ($font_size        (update-positive-float    '$font_size        ($rhs x)))
                ($head_angle       (update-positive-float    '$head_angle       ($rhs x)))
                ($head_length      (update-positive-float    '$head_length      ($rhs x)))
                ($background_color (update-color             '$background_color ($rhs x)))
                ($dimensions       (update-dimensions                           ($rhs x)))
                ($nticks           (update-positive-integer  '$nticks           ($rhs x)))
                ($line_width       (update-positive-float    '$line_width       ($rhs x)))
                ($line_type        (update-linestyle         '$line_type        ($rhs x)))
                ($key              (update-string            '$key              ($rhs x)))
                ($key_pos          (update-key_pos                              ($rhs x)))
                ($logx             (update-boolean-option    '$logx             ($rhs x)))
                ($logy             (update-boolean-option    '$logy             ($rhs x)))
                ($filled_func      (update-gr-option         '$filled_func      ($rhs x)))
                ($grid             (update-gr-option         '$grid             ($rhs x)))
                ($transform        (update-transform                            ($rhs x)))
                ($points_joined    (update-pointsjoined                         ($rhs x)))
                ($point_type       (update-pointtype                            ($rhs x)))
                ($point_size       (update-nonnegative-float '$point_size       ($rhs x)))
                ($terminal         (update-terminal                             ($rhs x)))
                ($unit_vectors     (update-boolean-option    '$unit_vectors     ($rhs x)))
                ($xlabel           (update-string            '$xlabel           ($rhs x)))
                ($ylabel           (update-string            '$ylabel           ($rhs x)))

                ; options not yet implemented for 2D-vtk
                ; they are included here to avoid error messages
                ($xrange           (update-gr-option         '$xrange           ($rhs x)))
                ($yrange           (update-gr-option         '$yrange           ($rhs x)))

                (otherwise (merror "vtk2d: unknown option ~M " ($lhs x)))))

            ((setf obj (gethash (caar x) *vtk2d-graphic-objects*))
               (setf objects
                     (concatenate 'string
                       objects
                       (apply obj (rest x)))))

            (t
              (merror "vtk2d: item ~M is not recognized" x))))
    ; scene allocation
    (setf *allocations* (cons (get-option '$allocation) *allocations*))
    (concatenate 'string
      (vtkchartxy-code chart-name)
      objects
      (vtkrenderer2d-code
         chart-name
         renderer-name)  )))



;; 3D SCENE BUILDER

(defvar *vtk3d-graphic-objects* (make-hash-table))

; table of 3d graphic objects
(setf (gethash '$cone               *vtk3d-graphic-objects*) 'vtk3d-cone
      (gethash '$cylinder           *vtk3d-graphic-objects*) 'vtk3d-cylinder
      (gethash '$cube               *vtk3d-graphic-objects*) 'vtk3d-cube
      (gethash '$prism              *vtk3d-graphic-objects*) 'vtk3d-prism
      (gethash '$elevation_grid     *vtk3d-graphic-objects*) 'vtk3d-elevation_grid
      (gethash '$implicit           *vtk3d-graphic-objects*) 'vtk3d-implicit
      (gethash '$sphere             *vtk3d-graphic-objects*) 'vtk3d-sphere
      (gethash '$parallelogram      *vtk3d-graphic-objects*) 'vtk3d-parallelogram
      (gethash '$triangle           *vtk3d-graphic-objects*) 'vtk3d-triangle
      (gethash '$vector             *vtk3d-graphic-objects*) 'vtk3d-vector
      (gethash '$points             *vtk3d-graphic-objects*) 'vtk3d-points
      (gethash '$parametric         *vtk3d-graphic-objects*) 'vtk3d-parametric
      (gethash '$parametric_surface *vtk3d-graphic-objects*) 'vtk3d-parametric_surface
      (gethash '$spherical          *vtk3d-graphic-objects*) 'vtk3d-spherical
      (gethash '$cylindrical        *vtk3d-graphic-objects*) 'vtk3d-cylindrical
      (gethash '$explicit           *vtk3d-graphic-objects*) 'vtk3d-explicit
      (gethash '$label              *vtk3d-graphic-objects*) 'vtk3d-label
      (gethash '$tube               *vtk3d-graphic-objects*) 'vtk3d-tube )

(defun make-vtk-scene-3d (args)
  (let ((objects              "")
        (appenddata-name      (get-appenddata-name))
        (outline-name         (get-outline-name))
        (polydatamapper-name  (get-polydatamapper-name))
        (outlineactor-name    (get-outlineactor-name))
        (textproperty-name    (get-textproperty-name))
        (cubeaxesactor2d-name (get-cubeaxesactor2d-name))
        (renderer-name        (get-renderer-name))
        (camera-name          (get-camera-name))
        (first-actor          (+ *vtk-actor-counter* 1))
        (first-labelactor     (+ *vtk-labelactor-counter* 1))
        (first-extract        (+ *vtk-extract-counter* 1))
        (first-label          (+ *vtk-label-counter* 1))
        largs obj)
    (ini-gr-options)
    (ini-local-option-variables)
    (user-defaults)
    (setf largs (listify-arguments args))
    (dolist (x largs)
      (cond ((equal ($op x) "=")
              (case ($lhs x)
                ($allocation        (update-allocation                           ($rhs x)))
                ($axis_3d           (update-boolean-option    '$axis_3d          ($rhs x)))
                ($background_color  (update-color             '$background_color ($rhs x)))
                ($capping           (update-capping                              ($rhs x)))
                ($color             (update-color             '$color            ($rhs x)))
                ($isolines_color    (update-color             '$isolines_color   ($rhs x)))
                ($isolines_levels   (update-contour-isolines  '$isolines_levels  ($rhs x)))
                ($dimensions        (update-dimensions                           ($rhs x)))
                ($enhanced3d        (update-enhanced3d                           ($rhs x)))
                ($file_name         (update-string            '$file_name        ($rhs x)))
                ($font_size         (update-positive-float    '$font_size        ($rhs x)))
                ($head_angle        (update-positive-float    '$head_angle       ($rhs x)))
                ($head_length       (update-positive-float    '$head_length      ($rhs x)))
                ($isolines          (update-isolines                             ($rhs x)))
                ($line_type         (update-linestyle         '$line_type        ($rhs x)))
                ($line_width        (update-positive-float    '$line_width       ($rhs x)))
                ($nticks            (update-positive-integer  '$nticks           ($rhs x)))
                ($opacity           (update-opacity                              ($rhs x)))
                ($palette           (update-palette                              ($rhs x)))
                ($points_joined     (update-pointsjoined                         ($rhs x)))
                ($point_size        (update-nonnegative-float '$point_size       ($rhs x)))
                ($point_type        (update-pointtype                            ($rhs x)))
                ($terminal          (update-terminal                             ($rhs x)))
                ($transform         (update-transform                            ($rhs x)))
                ($unit_vectors      (update-boolean-option    '$unit_vectors     ($rhs x)))
                ($view              (update-view                                 ($rhs x)))
                ($wired_surface     (update-boolean-option    '$wired_surface    ($rhs x)))
                ($xu_grid           (update-positive-integer  '$xu_grid          ($rhs x)))
                ($yv_grid           (update-positive-integer  '$yv_grid          ($rhs x)))
                ($x_voxel           (update-positive-integer  '$x_voxel          ($rhs x)))
                ($y_voxel           (update-positive-integer  '$y_voxel          ($rhs x)))
                ($z_voxel           (update-positive-integer  '$z_voxel          ($rhs x)))
                ($xlabel            (update-string            '$xlabel           ($rhs x)))
                ($ylabel            (update-string            '$ylabel           ($rhs x)))
                ($zlabel            (update-string            '$zlabel           ($rhs x)))

                ; must be changed to script_file_name
                ($gnuplot_file_name (update-string            '$gnuplot_file_name           ($rhs x)))

                ; options not yet implemented for 3D-vtk
                ; they are included here to avoid error messages
                ($surface_hide      (update-boolean-option    '$surface_hide      ($rhs x)))
                ($label_alignment   (update-string            '$label_alignment   ($rhs x)))
                ($label_orientation (update-string            '$label_orientation ($rhs x)))
                ($xrange            (update-gr-option         '$xrange            ($rhs x)))
                ($yrange            (update-gr-option         '$yrange            ($rhs x)))
                ($zrange            (update-gr-option         '$zrange            ($rhs x)))

                (otherwise (merror "vtk3d: unknown option ~M " ($lhs x)))))

            ((setf obj (gethash (caar x) *vtk3d-graphic-objects*))
               (setf objects
                     (concatenate 'string
                       objects
                       (apply obj (rest x)))))

            (t
              (merror "vtk3d: item ~M is not recognized" x))))    
    ; scene allocation
    (setf *allocations* (cons (get-option '$allocation) *allocations*))
    (concatenate 'string
      objects
      (if (> *vtk-extract-counter* 0)
        (scenebounds)
        "")
      (vtkappendpolydata-code appenddata-name first-extract first-label)
      (vtkoutlinefilter-code outline-name appenddata-name)
      (vtkpolydatamapper-code polydatamapper-name outline-name t)
      (vtkactor-code outlineactor-name polydatamapper-name "#ff0000" 1 1 nil)
      (vtktextproperty-code textproperty-name)
      (vtkcubeaxesactor2d-code cubeaxesactor2d-name appenddata-name textproperty-name)
      (vtkrenderer3d-code
        renderer-name
        cubeaxesactor2d-name
        outlineactor-name
        (get-option '$background_color)
        camera-name
        (car  (get-option '$view))
        (cadr (get-option '$view))
        first-actor
        first-labelactor ) )))



(defun draw_vtk (&rest args)
  (let ((scenes nil)
        (cmdstorage "")
        gfn largs)
    (ini-gr-options)
    (ini-global-options)
    (ini-local-option-variables)
    (user-defaults)
    (setf *allocations* nil)
    (setf *vtk-appenddata-counter* 0
          *vtk-extract-counter* 0
          *vtk-outline-counter* 0
          *vtk-polydatamapper-counter* 0
          *vtk-outlineactor-counter* 0
          *vtk-textproperty-counter* 0
          *vtk-cubeaxesactor2d-counter* 0
          *vtk-camera-counter* 0
          *vtk-renderer-counter* 0
          *vtk-source-counter* 0
          *vtk-mapper-counter* 0
          *vtk-actor-counter* 0
          *vtk-labelactor-counter* 0
          *vtk-trans-counter* 0
          *vtk-filter-counter* 0
          *vtk-data-file-counter* 0
          *vtk-floatarray-counter* 0
          *vtk-points-counter* 0
          *vtk-glyphpoints-counter* 0
          *vtk-polydata-counter* 0
          *vtk-cellarray-counter* 0
          *vtk-polydatamapper-counter* 0
          *vtk-solidsource-counter* 0
          *vtk-triangle-counter* 0
          *vtk-label-counter* 0
          *vtk-chart-counter* 0
          *vtk-table-counter* 0
          *vtk-arrayX-counter* 0
          *vtk-arrayY-counter* 0
          *vtk-2dkey-counter* 0
          *vtk-isolines-counter* 0
          *lookup-tables* nil
          *unitscale-already-defined* nil)
    (setf largs (listify-arguments args))
    (dolist (x largs)
      (cond ((equal ($op x) "=")
              (case ($lhs x)
                ($terminal         (update-terminal                             ($rhs x)))
                ($columns          (update-positive-integer  '$columns          ($rhs x)))
                ($dimensions       (update-dimensions                           ($rhs x)))
                ($file_name        (update-string            '$file_name        ($rhs x)))
                ($background_color (update-color             '$background_color ($rhs x)))
                (otherwise (merror "draw: unknown global option ~M " ($lhs x)))))
            ((equal (caar x) '$gr3d)
              (setf scenes (append scenes (list (funcall #'make-vtk-scene-3d (rest x))))))
            ((equal (caar x) '$gr2d)
              (setf scenes (append scenes (list (funcall #'make-vtk-scene-2d (rest x))))))
            (t
              (merror "draw: item ~M is not recognized" x))) )

    ;; prepare script file
    (setf gfn (plot-temp-file (format nil "maxout~d.py" (getpid))))
    (setf cmdstorage
      (open gfn
            :direction :output :if-exists :supersede))
    (when (eql cmdstorage nil)
      (merror "draw: Cannot create file '~a'. Probably maxima_tempdir doesn't point to a writable directory." gfn))

    ;; pull in required packages
    (format cmdstorage "~a~%~a~%~%~a~%~a~%~%~a~%~%"
      "#!/usr/bin/env python"
      "# -*- coding: UTF-8 -*-"
      "import vtk"
      "import sys"
      "bounds=[]")

    ;: write scenes
    (dolist (scn scenes)
      (format cmdstorage "~a" scn) )

    ;; the renderer window
    (format cmdstorage "~a" (vtkrendererwindow-code (length scenes)))
    (format cmdstorage "~a" (vtk-terminal))

    ;; close script file
    (close cmdstorage)

    #+(or windows win32 win64)
    ($system "vtkpython " gfn)
    #-(or windows win32 win64)
    (if (member $draw_renderer '($vtk $vtk6))
      ($system (format nil "(python \"~a\")&" gfn))
      ($system (format nil "(python3 \"~a\")&" gfn)))

    '$done))