GameState.lua
155 KB
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
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
-- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2018 Nicolas Casalini
--
-- 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 3 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.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
require "engine.Entity"
local Particles = require "engine.Particles"
local Shader = require "engine.Shader"
local Map = require "engine.Map"
local NameGenerator = require "engine.NameGenerator"
local NameGenerator2 = require "engine.NameGenerator2"
local Donation = require "mod.dialogs.Donation"
local Dialog = require "engine.ui.Dialog"
module(..., package.seeall, class.inherit(engine.Entity))
function _M:init(t, no_default)
engine.Entity.init(self, t, no_default)
self.allow_backup_guardians = {}
self.world_artifacts_pool = {}
self.seen_special_farportals = {}
self.unique_death = {}
self.used_events = {}
self.boss_killed = 0
self.stores_restock = 1
self.east_orc_patrols = 4
self.tier1_done = 0
self.birth = {}
end
--- Restock all stores
function _M:storesRestock()
self.stores_restock_levels = self.stores_restock_levels or {}
self.stores_restock_levels[#self.stores_restock_levels+1] = game.player.level -- Store the level so shops using player_material_level know what levels to update stock
self.stores_restock = self.stores_restock + 1
game.log("#AQUAMARINE#Most stores should have new stock now.")
print("[STORES] restocking")
end
--- Number of bosses killed
function _M:bossKilled(rank)
self.boss_killed = self.boss_killed + 1
end
--- Register a tier1 boss kill
function _M:tier1Kill()
self.tier1_done = self.tier1_done + 1
end
--- Return true if enough tier1 boss killed
function _M:tier1Killed(nb)
return self.tier1_done >= nb
end
--- Sets unique as dead
function _M:registerUniqueDeath(u)
if u.randboss then return end
self.unique_death[u.name] = true
end
--- Is unique dead?
function _M:isUniqueDead(name)
return self.unique_death[name]
end
--- Seen a special farportal location
function _M:seenSpecialFarportal(name)
self.seen_special_farportals[name] = true
end
--- Is farportal already used
function _M:hasSeenSpecialFarportal(name)
return self.seen_special_farportals[name]
end
--- Allow dropping the rod of recall
function _M:allowRodRecall(v)
if v == nil then return self.allow_drop_recall end
self.allow_drop_recall = v
end
--- Discovered the far east
function _M:goneEast()
self.is_advanced = true
end
--- Is the game in an advanced state (gone east ? others ?)
function _M:isAdvanced()
return self.is_advanced
end
--- Reduce the chance of orc patrols
function _M:eastPatrolsReduce()
self.east_orc_patrols = self.east_orc_patrols / 2
end
--- Get the chance of orc patrols
function _M:canEastPatrol()
return self.east_orc_patrols
end
--- Setup a backup guardian for the given zone
function _M:activateBackupGuardian(guardian, on_level, zonelevel, rumor, action)
if self.is_advanced then return end
print("Zone guardian dead, setting up backup guardian", guardian, zonelevel)
self.allow_backup_guardians[game.zone.short_name] =
{
name = game.zone.name,
guardian = guardian,
on_level = on_level,
new_level = zonelevel,
rumor = rumor,
action = action,
}
end
--- Get random emote for townpeople based on backup guardians
function _M:getBackupGuardianEmotes(t)
if not self.is_advanced then return t end
for zone, data in pairs(self.allow_backup_guardians) do
print("possible chatter", zone, data.rumor)
t[#t+1] = data.rumor
end
return t
end
--- Activate a backup guardian & settings, if available
function _M:zoneCheckBackupGuardian()
if not self.is_advanced then print("Not gone east, no backup guardian") return end
local guard_data = self.allow_backup_guardians[game.zone.short_name]
-- Adjust level of the zone
-- Note: this permanently changes the zone properties when a BackupGuardian is spawned
if guard_data then
game.zone.base_level = guard_data.new_level
game:applyDifficulty(game.zone, guard_data.new_level) -- apply difficulty if required
if guard_data.action then guard_data.action(false) end
end
-- Spawn the new guardian
if guard_data and guard_data.on_level == game.level.level then
-- Place the guardian, we do not check for connectivity, vault or whatever, the player is supposed to be strong enough to get there
local m = game.zone:makeEntityByName(game.level, "actor", guard_data.guardian)
if m then
local x, y = rng.range(0, game.level.map.w - 1), rng.range(0, game.level.map.h - 1)
local tries = 0
while not m:canMove(x, y) and tries < 100 do
x, y = rng.range(0, game.level.map.w - 1), rng.range(0, game.level.map.h - 1)
tries = tries + 1
end
if tries < 100 then
game.zone:addEntity(game.level, m, "actor", x, y)
print("Backup Guardian allocated: ", guard_data.guardian, m.uid, m.name)
end
else
print("WARNING: Backup Guardian not found: ", guard_data.guardian)
end
if guard_data.action then guard_data.action(true) end
self.allow_backup_guardians[game.zone.short_name] = nil
end
end
--- A boss refused to drop his artifact! Bastard! Add it to the world pool
function _M:addWorldArtifact(o)
self.world_artifacts_pool[o.define_as] = o
end
--- Load all added artifacts
-- This is called from the world-artifacts.lua file
function _M:getWorldArtifacts()
return self.world_artifacts_pool
end
local randart_name_rules = {
default2 = {
phonemesVocals = "a, e, i, o, u, y",
phonemesConsonants = "b, c, ch, ck, cz, d, dh, f, g, gh, h, j, k, kh, l, m, n, p, ph, q, r, rh, s, sh, t, th, ts, tz, v, w, x, z, zh",
syllablesStart = "Aer, Al, Am, An, Ar, Arm, Arth, B, Bal, Bar, Be, Bel, Ber, Bok, Bor, Bran, Breg, Bren, Brod, Cam, Chal, Cham, Ch, Cuth, Dag, Daim, Dair, Del, Dr, Dur, Duv, Ear, Elen, Er, Erel, Erem, Fal, Ful, Gal, G, Get, Gil, Gor, Grin, Gun, H, Hal, Han, Har, Hath, Hett, Hur, Iss, Khel, K, Kor, Lel, Lor, M, Mal, Man, Mard, N, Ol, Radh, Rag, Relg, Rh, Run, Sam, Tarr, T, Tor, Tul, Tur, Ul, Ulf, Unr, Ur, Urth, Yar, Z, Zan, Zer",
syllablesMiddle = "de, do, dra, du, duna, ga, go, hara, kaltho, la, latha, le, ma, nari, ra, re, rego, ro, rodda, romi, rui, sa, to, ya, zila",
syllablesEnd = "bar, bers, blek, chak, chik, dan, dar, das, dig, dil, din, dir, dor, dur, fang, fast, gar, gas, gen, gorn, grim, gund, had, hek, hell, hir, hor, kan, kath, khad, kor, lach, lar, ldil, ldir, leg, len, lin, mas, mnir, ndil, ndur, neg, nik, ntir, rab, rach, rain, rak, ran, rand, rath, rek, rig, rim, rin, rion, sin, sta, stir, sus, tar, thad, thel, tir, von, vor, yon, zor",
rules = "$s$v$35m$10m$e",
},
default = {
phonemesVocals = "a, e, i, o, u, y",
syllablesStart = "Ad, Aer, Ar, Bel, Bet, Beth, Ce'N, Cyr, Eilin, El, Em, Emel, G, Gl, Glor, Is, Isl, Iv, Lay, Lis, May, Ner, Pol, Por, Sal, Sil, Vel, Vor, X, Xan, Xer, Yv, Zub",
syllablesMiddle = "bre, da, dhe, ga, lda, le, lra, mi, ra, ri, ria, re, se, ya",
syllablesEnd = "ba, beth, da, kira, laith, lle, ma, mina, mira, na, nn, nne, nor, ra, rin, ssra, ta, th, tha, thra, tira, tta, vea, vena, we, wen, wyn",
rules = "$s$v$35m$10m$e",
},
fire = {
syllablesStart ="Phoenix, Stoke, Fire, Blaze, Burn, Bright, Sear, Heat, Scald, Hell, Hells, Inferno, Lava, Pyre, Furnace, Cinder, Singe, Flame, Scorch, Brand, Kindle, Flash, Smolder, Torch, Ash, Abyss, Char, Kiln, Sun, Magma, Flare",
syllablesEnd = "arc, bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bolt, bone, bore, brace, braid, braze, breacher, breaker, breeze, brawn, burst, bringer, bearer, bender, blight, break, born, black, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, noon, nail, nigh, night, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rain, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, star, streak, sting, stinger, strike, striker, stun, sun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, umbra, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, winter, wire, wisp, wish, witch, wolf, woe, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr",
rules = "$s$e",
},
cold = {
syllablesStart ="Frost, Ice, Freeze, Sleet, Snow, Chill, Shiver, Winter, Blizzard, Glacier, Tundra, Floe, Hail, Frozen, Frigid, Rime, Haze, Rain, Tide, Quench",
syllablesEnd = "arc, bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bolt, bone, bore, brace, braid, braze, breacher, breaker, breeze, brawn, burst, bringer, bearer, bender, blight, brand, break, born, black, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, furnace, flash, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, noon, nail, nigh, night, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, pyre, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rain, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, sear, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, star, streak, sting, stinger, strike, striker, stun, sun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, umbra, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, wire, wisp, wish, witch, wolf, woe, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr",
rules = "$s$e",
},
lightning = {
syllablesStart ="Tempest, Storm, Lightning, Arc, Shock, Thunder, Charge, Cloud, Air, Nimbus, Gale, Crackle, Shimmer, Flash, Spark, Blast, Blaze, Strike, Sky, Bolt",
syllablesEnd = "bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bone, bore, brace, braid, braze, breacher, breaker, breeze, brawn, burst, bringer, bearer, bender, blight, brand, break, born, black, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, furnace, flash, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, noon, nail, nigh, night, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, pyre, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rain, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, sear, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, star, streak, sting, stinger, stun, sun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, umbra, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, winter, wire, wisp, wish, witch, wolf, woe, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr",
rules = "$s$e",
},
light = {
syllablesStart ="Light, Shine, Day, Sun, Morning, Star, Blaze, Glow, Gleam, Bright, Prism, Dazzle, Glint, Dawn, Noon, Glare, Flash, Radiance, Blind, Glimmer, Splendour, Glitter, Kindle, Lustre",
syllablesEnd = "arc, bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bolt, bone, bore, brace, braid, braze, breacher, breaker, breeze, brawn, burst, bringer, bearer, bender, blight, brand, break, born, black, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, furnace, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, nail, nigh, night, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, pyre, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rain, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, sear, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, streak, sting, stinger, strike, striker, stun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, umbra, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, winter, wire, wisp, wish, witch, wolf, woe, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr",
rules = "$s$e",
},
dark = {
syllablesStart ="Night, Umbra, Void, Dark, Gloom, Woe, Dour, Shade, Dusk, Murk, Bleak, Dim, Soot, Pitch, Fog, Black, Coal, Ebony, Shadow, Obsidian, Raven, Jet, Demon, Duathel, Unlight, Eclipse, Blind, Deeps",
syllablesEnd = "arc, bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bolt, bone, bore, brace, braid, braze, breacher, breaker, breeze, brawn, burst, bringer, bearer, bender, blight, brand, break, born, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, furnace, flash, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, noon, nail, nigh, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, pyre, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rain, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, sear, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, star, streak, sting, stinger, strike, striker, stun, sun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, winter, wire, wisp, wish, witch, wolf, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr",
rules = "$s$e",
},
nature = {
syllablesStart ="Nature, Green, Loam, Earth, Heal, Root, Growth, Grow, Bark, Bloom, Satyr, Rain, Pure, Wild, Wind, Cure, Cleanse, Forest, Breeze, Oak, Willow, Tree, Balance, Flower, Ichor, Offal, Rot, Scab, Squalor, Taint, Undeath, Vile, Weep, Plague, Pox, Pus, Gore, Sepsis, Corruption, Filth, Muck, Fester, Toxin, Venom, Scorpion, Serpent, Viper, Cobra, Sulfur, Mire, Ooze, Wretch, Carrion, Bile, Bog, Sewer, Swamp, Corpse, Scum, Mold, Spider, Phlegm, Mucus, Morbus, Murk, Smear, Cyst",
syllablesEnd = "arc, bane, bait, bile, biter, blast, bliss, blood, blow, bloom, butcher, blur, bolt, bone, bore, brace, braid, braze, breacher, breaker, brawn, burst, bringer, bearer, bender, blight, brand, break, born, black, bright, crypt, crack, clash, clamor, cut, cast, cutter, dredge, dash, dream, dare, death, edge, envy, fury, fear, fame, foe, furnace, flash, fiend, fist, gore, gash, gasher, grind, grinder, guile, grit, glean, glory, glamour, hack, hacker, hash, hue, hunger, hunt, hunter, ire, idol, immortal, justice, jeer, jam, kill, killer, kiss, 's kiss, karma, kin, king, knave, knight, lord, lore, lash, lace, lady, maim, mark, moon, master, mistress, mire, monster, might, marrow, mortal, minister, malice, naught, null, noon, nail, nigh, night, oath, order, oracle, oozer, obeisance, oblivion, onslaught, obsidian, peal, pyre, parry, power, python, prophet, pain, passion, pierce, piercer, pride, pulverizer, piety, panic, pain, punish, pall, quench, quencher, quake, quarry, queen, quell, queller, quick, quill, reaper, ravage, ravager, raze, razor, roar, rage, race, radiance, raider, rot, ransom, rune, reign, rupture, ream, rebel, raven, river, ripper, rip, ripper, rock, reek, reeve, resolve, rigor, rend, raptor, shine, slice, slicer, spar, spawn, spawner, spitter, squall, steel, stoker, snake, sorrow, sage, stake, serpent, shear, sin, sear, spire, stalker, shaper, strider, streak, streaker, saw, scar, schism, star, streak, sting, stinger, strike, striker, stun, sun, sweep, sweeper, swift, stone, seam, sever, smash, smasher, spike, spiker, thorn, terror, touch, tide, torrent, trial, typhoon, titan, tickler, tooth, treason, trencher, taint, trail, umbra, usher, valor, vagrant, vile, vein, veil, venom, viper, vault, vengeance, vortex, vice, wrack, walker, wake, waker, war, ward, warden, wasp, weeper, wedge, wend, well, whisper, wild, wilder, will, wind, wilter, wing, winnow, winter, wire, wisp, wish, witch, wolf, woe, wither, witherer, worm, wreath, worth, wreck, wrecker, wrest, writher, wyrd, zeal, zephyr,",
rules = "$s$e",
},
}
--- Unided name possibilities for randarts
local unided_names = {"glowing","scintillating","rune-covered","unblemished","jewel-encrusted","humming","gleaming","immaculate","flawless","crackling","glistening","plated","twisted","silvered","faceted","faded","sigiled","shadowy","laminated"}
--- defined power themes, affects equipment generation
_M.power_themes = {
'physical', 'mental', 'spell', 'defense', 'misc', 'fire',
'lightning', 'acid', 'mind', 'arcane', 'blight', 'nature',
'temporal', 'light', 'dark', 'antimagic', 'cold'
}
--- defined power sources, used for equipment generation, defined in class descriptors
_M.power_sources = table.map(function(k, v) return k, true end, table.keys_to_values({'technique','technique_ranged','nature','arcane','psionic','antimagic'}))
--- map attributes to power restrictions for an entity
-- returns an updated list of forbidden power types including attributes
-- used for checking for compatible equipment and npc randboss classes
function _M:attrPowers(e, not_ps)
not_ps = table.clone(not_ps or e.not_power_source or e.forbid_power_source) or {}
if e.attr then
if e:attr("has_arcane_knowledge") then not_ps.antimagic = true end
if e:attr("undead") then not_ps.antimagic = true end
if e:attr("forbid_arcane") then not_ps.arcane = true end
-- if e:attr("forbid_nature") then not_ps.nature = true end
end
return not_ps
end
--- Checks power_source compatibility between two entities
-- returns true if e2 is compatible with e1, false otherwise
-- by default, only checks .power_source vs. .forbid_power_source between entities
-- @param e1, e2 entities to check
-- @param require_power if true, will also check that e2.power_source (if present) has a match in e1.power_source
-- @param [opt = string] theme type of checks to perform, default to all
-- use updatePowers to resolve conflicts.
function _M:checkPowers(e1, e2, require_power, theme)
if not e1 or not e2 then return true end
-- print("Comparing power sources",e1.name, e2.name)
-- check for excluded power sources first
if theme == "antimagic_only" then -- check antimagic restrictions only
local not_ps = self:attrPowers(e1)
if e2.power_source and (e2.power_source.antimagic and not_ps.antimagic or e2.power_source.arcane and not_ps.arcane) then return false end
local not_ps = self:attrPowers(e2)
if e1.power_source and (e1.power_source.antimagic and not_ps.antimagic or e1.power_source.arcane and not_ps.arcane) then return false end
return true
else -- check for all conflicts
local not_ps = self:attrPowers(e2)
for ps, _ in pairs(e1.power_source or {}) do
if not_ps[ps] then return false end
end
not_ps = self:attrPowers(e1)
for ps, _ in pairs(e2.power_source or {}) do
if not_ps[ps] then return false end
end
-- check for required power_sources
if require_power and e1.power_source and e2.power_source then
for yes_ps, _ in pairs(e1.power_source) do
if (e2.power_source and e2.power_source[yes_ps]) then return true end
end
return false
end
end
return true
end
--- Adjusts power source parameters and themes to remove conflicts
-- @param forbid_ps = {arcane = true, technique = true, ...} forbidden power sources <none>
-- @param allow_ps = {arcane = true, technique = true, ...} allowed power sources <all allowed>
-- @param randthemes = number of themes to pick randomly from the global pool <0>
-- @param force_themes = themes to always include {"attack", "antimagic", ...} applied last (optional)
-- themes included can add to forbid_ps and allow_ps
-- precedence is: forbid_ps > allow_ps > force_themes
-- returns new forbid_ps, allow_ps, themes (made consistent)
function _M:updatePowers(forbid_ps, allow_ps, randthemes, force_themes)
local spec_powers = allow_ps and next(allow_ps)
local yes_ps = spec_powers and table.clone(allow_ps) or table.clone(self.power_sources)
local not_ps = forbid_ps and table.clone(forbid_ps) or {}
local allthemes, themes = table.clone(self.power_themes), {}
local force_themes = force_themes and table.clone(force_themes) or {}
for fps, _ in pairs(not_ps) do --enforce forbidden power restrictions
yes_ps[fps] = nil
if fps == "arcane" then
table.removeFromList(allthemes, 'spell', 'arcane', 'blight', 'temporal')
yes_ps.arcane = nil
elseif fps == "antimagic" then
table.removeFromList(allthemes, 'antimagic')
yes_ps.antimagic = nil
elseif fps == "nature" then
table.removeFromList(allthemes, 'nature')
elseif fps == "psionic" then
table.removeFromList(allthemes, 'mental', 'mind')
end
end
if spec_powers then --apply specified power sources
if yes_ps.antimagic then
not_ps.arcane = true
table.removeFromList(allthemes, 'spell', 'arcane', 'blight', 'temporal')
end
if yes_ps.arcane then
not_ps.antimagic = true
table.removeFromList(allthemes, 'antimagic')
end
if yes_ps.nature then
if not table.keys_to_values(allthemes).nature then table.insert(allthemes, 'nature') end
end
end
-- build themes list if needed beginning with those requested
local theme_count = (randthemes or 0) + #force_themes
for n = 1, theme_count do
local v = nil
if #force_themes > 0 then -- always add forced_themes if possible
v = rng.tableRemove(force_themes)
table.removeFromList(allthemes, v)
end
if not v then v = rng.tableRemove(allthemes) end -- pick from remaining themes
themes[#themes+1] = v
-- enforce theme-theme exclusions
if v == 'antimagic' then
table.removeFromList(allthemes, 'spell', 'arcane', 'blight', 'temporal')
yes_ps.antimagic, yes_ps.arcane = true, nil
not_ps.arcane = true
elseif v == 'spell' or v == 'arcane' or v == 'blight' or v == 'temporal' then
table.removeFromList(allthemes, 'antimagic')
yes_ps.antimagic, yes_ps.arcane = nil, true
not_ps.antimagic = true
elseif v == 'nature' then
table.removeFromList(allthemes, 'blight')
yes_ps.nature = true
elseif v == 'mind' or v == 'mental' then
yes_ps.psionic = true
elseif v == 'physical' then
yes_ps.technique, yes_ps.technique_ranged = true, true
end
end
return not_ps, yes_ps, themes
end
--- Generate randarts for this state with optional parameters:
-- @param data.base = base object to add powers to (base.randart_able must be defined) <random object>
-- @param data.base_filter = filter passed to makeEntity when making base object
-- @param data.lev = character level to generate for (affects point budget, #themes and #powers) <12-50>
-- @param data.power_points_factor = lev based power points multiplier <1>
-- @param data.nb_points_add = #extra budget points to spend on random powers <0>
-- @param data.nb_powers_add = #extra random powers to add <0>
-- @param data.powers_special = function(p) that must return true on each random power to add (from base.randart_able)
-- @param data.nb_themes = #power themes (power groups) for random powers to use <scales to 5 with lev>
-- @param data.nb_themes_add = #extra power themes to add <0>
-- @param data.force_themes = additional power theme(s) to use for random powers = {"attack", "arcane", ...}
-- @param data.egos = total #egos to include (forced + random) <3>
-- @param data.greater_egos_bias = #egos that should be greater egos <2/3 * data.egos>
-- @param data.force_egos = list of egos ("egoname1", "egoname2", ...) to add first (overrides restrictions)
-- @param data.ego_special = function(e) on ego table that must return true for allowed egos
-- @param data.forbid_power_source = disallowed power type(s) for egos
-- eg:{arcane = true, psionic = true, technique = true, nature = true, antimagic = true}
-- note some objects always have a power source by default (i.e. wands are always arcane powered)
-- @param data.power_source = allowed power type(s) <all allowed> if specified, only egos matching at least one of the power types will be added. themes (random or forced) can add allowed power_sources
-- @param data.namescheme = parameters to be passed to the NameGenerator <local randart_name_rules table>
-- @param data.add_pool if true, adds the randart to the world artifact pool <nil>
-- @param data.post = function(o) to be applied to the randart after all egos and powers have been added and resolved
function _M:generateRandart(data)
-- Setup basic parameters and override global variables to match data
data = data or {}
local lev = data.lev or rng.range(12, 50)
data.forbid_power_source = data.forbid_power_source or {}
local oldlev = game.level.level
local oldclev = resolvers.current_level
game.level.level = lev
resolvers.current_level = math.ceil(lev * 1.4)
-- Get a base object
local base = data.base or game.zone:makeEntity(game.level, "object", data.base_filter or {ignore_material_restriction=true, no_tome_drops=true, ego_filter={keep_egos=true, ego_chance=-1000}, special=function(e)
return (not e.unique and e.randart_able) and (not e.material_level or e.material_level >= 2) and true or false
end}, nil, true)
if not base or not base.randart_able then game.level.level = oldlev resolvers.current_level = oldclev return end
local o = base:cloneFull()
local display = o.display
-- Load possible random powers
local powers_list = engine.Object:loadList(o.randart_able, nil, nil,
function(e)
if data.powers_special and not data.powers_special(e) then e.rarity = nil end
if e.rarity then
e.rarity = math.ceil(e.rarity / 5)
end
end)
--print(" * loaded powers list:")
o.randart_able = nil
-----------------------------------------------------------
-- Pick Themes
-----------------------------------------------------------
local nb_themes = data.nb_themes
local nb_themes_add = data.nb_themes_add or 0
if not nb_themes then -- Gradually increase number of themes at higher levels so there are enough powers to spend points on
nb_themes = math.max(2,5*lev/(lev+50)) -- Maximum 5 themes possible
nb_themes= math.floor(nb_themes) + (rng.percent((nb_themes-math.floor(nb_themes))*100) and 1 or 0)
nb_themes = math.min(5, nb_themes + nb_themes_add)
end
-- update power sources and themes lists based on base object properties
local psource
if o.power_source then
psource = table.clone(o.power_source)
if data.power_source then table.merge(psource, data.power_source) end
-- forbid power sources that conflict with existing power source
data.forbid_power_source, psource = self:updatePowers(data.forbid_power_source, psource)
if data.power_source then data.power_source = psource end
end
-- resolve any power/theme conflicts with input data
local themes
data.forbid_power_source, psource, themes = self:updatePowers(data.forbid_power_source, data.power_source, nb_themes, data.force_themes)
if data.power_source then data.power_source = psource end
themes = table.map(function(k, v) return k, true end, table.keys_to_values(themes))
-----------------------------------------------------------
-- Determine power
-----------------------------------------------------------
-- Note double diminishing returns when coupled with scaling factor in merger (below)
-- Maintains randomness throughout level range ~50% variability in points
local points = math.max(0, math.ceil(0.1*lev^0.75*(8 + rng.range(1, 7)) * (data.power_points_factor or 1))+(data.nb_points_add or 0))
local nb_powers = 1 + rng.dice(math.max(1, math.ceil(0.281*lev^0.6)), 2) + (data.nb_powers_add or 0)
local nb_egos = data.egos or 3
local gr_egos = data.greater_egos_bias or math.floor(nb_egos*2/3) -- 2/3 greater egos by default
local powers = {}
print("Begin randart generation:", "level = ", lev, "egos =", nb_egos,"gr egos =", gr_egos, "rand themes = ", nb_themes, "points = ", points, "nb_powers = ",nb_powers)
if data.force_themes and #data.force_themes > 0 then print(" * forcing themes:",table.concat(data.force_themes,",")) end
print(" * using themes", table.concat(table.keys(themes), ','))
local force_egos = table.clone(data.force_egos)
if force_egos then print(" * forcing egos:", table.concat(force_egos, ',')) end
if data.forbid_power_source and next(data.forbid_power_source) then print(" * forbid power sources:", table.concat(table.keys(data.forbid_power_source), ',')) end
if data.power_source and next(data.power_source) then print(" * allowed power sources:", table.concat(table.keys(data.power_source), ',')) end
o.cost = o.cost + points * 7
local use_themes = next(themes) and true or false
-- Select some powers
local themes_fct = function(e)
if use_themes then
for theme, _ in pairs(e.theme) do if themes[theme] then return true end end
return false
end
return true
end
local power_themes = {}
local lst = game.zone:computeRarities("powers", powers_list, game.level, themes_fct) --Note: probabilities diminish as level exceeds 50 (limited to ~1000 by mod.class.zone:adjustComputeRaritiesLevel(level, type, lev))
for i = 1, nb_powers do
local p = game.zone:pickEntity(lst)
if p then
for t, _ in pairs(p.theme) do if themes[t] and randart_name_rules[t] then power_themes[t] = (power_themes[t] or 0) + 1 end end
powers[#powers+1] = p:clone()
end
end
-- print("Selected powers:") for i, p in ipairs(powers) do print(" * ",p.name, table.concat(table.keys(p.theme or {}), ",")) end
power_themes = table.listify(power_themes)
table.sort(power_themes, function(a, b) return a[2] < b[2] end)
-----------------------------------------------------------
-- Make up a name based on themes
-----------------------------------------------------------
local themename = power_themes[#power_themes]
themename = themename and themename[1] or nil
local ngd = NameGenerator.new(rng.chance(2) and randart_name_rules.default or randart_name_rules.default2)
local ngt = (themename and randart_name_rules[themename] and NameGenerator.new(randart_name_rules[themename])) or ngd
local name
local namescheme = data.namescheme or ((ngt ~= ngd) and rng.range(1, 4) or rng.range(1, 3))
if namescheme == 1 then
name = "%s '"..ngt:generate().."'"
elseif namescheme == 2 then
name = ngt:generate().." the %s"
elseif namescheme == 3 then
name = ngt:generate()
elseif namescheme == 4 then
name = ngd:generate().." the "..ngt:generate()
end
o.unided_namescheme = rng.table(unided_names).." %s"
o.unided_name = o.unided_namescheme:format(o.unided_name or o.name)
o.namescheme = name
o.define_as = name:format(o.name):upper():gsub("[^A-Z]", "_")
o.unique = name:format(o.name)
o.name = name:format(o.name)
o.randart = true
o.no_unique_lore = true
o.rarity = rng.range(200, 290)
print("Creating randart "..name.."("..o.unided_name..") with "..(themename or "no themename"))
-----------------------------------------------------------
-- Add ego properties (modified by power_source restrictions)
-----------------------------------------------------------
if o.egos and nb_egos > 0 then
local picked_egos = {}
local legos = {}
local been_greater = 0
game.zone:getEntities(game.level, "object") -- make sure ego definitions are loaded
-- merge all egos into one list to correctly calculate rarities
table.append(legos, game.level:getEntitiesList("object/"..o.egos..":prefix") or {})
table.append(legos, game.level:getEntitiesList("object/"..o.egos..":suffix") or {})
table.append(legos, game.level:getEntitiesList("object/"..o.egos..":") or {})
-- print(" * loaded ", #legos, "ego definitions from ", o.egos)
for i = 1, nb_egos or 3 do
local list = {}
local gr_ego, ignore_filter = false, false
if rng.percent(100*lev/(lev+50)) and been_greater < gr_egos then -- Phase out (but don't eliminate) lesser egos with level
gr_ego = true
end
if force_egos then -- use forced egos list first
local found = false
repeat
local fego = rng.tableRemove(force_egos)
if not fego then break end
for z, e in ipairs(legos) do
if e.e.name:find(fego, nil, true) then
-- print(" * found forced ego", e.e.name)
list[1] = e.e
found = true
gr_ego, ignore_filter = false, true -- make sure forced ego is not filtered out later
break
end
end
until found or #force_egos <= 0
if #force_egos == 0 then force_egos = nil end
end
if #list == 0 then -- no forced egos, copy the whole list
for z = 1, #legos do
list[#list+1] = legos[z].e
end
end
local ef = self:egoFilter(game.zone, game.level, "object", "randartego", o, {special=data.ego_special, forbid_power_source=data.forbid_power_source, power_source=data.power_source}, picked_egos, {})
local filter = function(e) -- check ego definition properties
if ignore_filter then return true end
if not ef.special or ef.special(e) then
if gr_ego and not e.greater_ego then return false end
return game.state:checkPowers(ef, e, true) -- check power_source compatibility
end
end
local pick_egos = game.zone:computeRarities("object", list, game.level, filter, nil, nil)
local ego = game.zone:pickEntity(pick_egos)
if ego then
table.insert(picked_egos, ego)
print(" ** selected ego", ego.name, (ego.greater_ego and "(greater)" or "(normal)"), ego.power_source and table.concat(table.keys(ego.power_source), ","))
if ego.greater_ego then been_greater = been_greater + 1 end
-- OMFG this is ugly, there is a very rare combination that can result in a crash there, so we .. well, ignore it :/
-- Sorry.
-- Fixed against overflow
local ok, err = pcall(game.zone.applyEgo, game.zone, o, ego, "object", true)
if not ok then
data.fails = (data.fails or 0) + 1
print("randart creation error", err)
print("game.zone.applyEgo failed at creating a randart, retrying", data.fails)
game.level.level = oldlev
resolvers.current_level = oldclev
if data.fails < 4 then return self:generateRandart(data) else return end
end
else -- no ego found: increase budget for random powers to compensate
local xpoints = gr_ego and 8 or 5
print((" ** no ego found (+%d points)"):format(xpoints))
points = points + (xpoints * 2)
end
end
-- o.egos = nil o.egos_chance = nil o.force_ego = nil
end
-- Re-resolve with the (possibly) new resolvers
o:resolve()
-----------------------------------------------------------
-- Imbue random powers into the randart according to themes
-----------------------------------------------------------
-- Note: The same power can be selected twice for both the base power list as well as the bias power list, this will lead to wasted points very easily at low theme/high power point counts
local max_reached = false
local function merger(d, e, k, dst, src, rules, state) --scale: factor to adjust power limits for levels higher than 50
if (not state.path or #state.path == 0) and not state.copy then
if k == "copy" then -- copy into root
state.copy = true
table.applyRules(dst, e, rules, state)
end
end
local scale = state.scaleup or 1
if type(e) == "table" and e.__resolver and e.__resolver == "randartmax" and d then
d.v = d.v + e.v
d.max = e.max
if e.max < 0 then
if d.v < e.max * scale then --Adjust maximum values for higher levels
d.v = e.max * scale
max_reached = true
end
else
if d.v > e.max * scale then --Adjust maximum values for higher levels
d.v = e.max * scale
max_reached = true
end
end
return true
end
end
-- Distribute points: half to any powers and half to a shortened list of powers to focus their effects
local selected_powers = {}
local hpoints = math.ceil(points / 2)
local i = 0
local fails = 0
while hpoints > 0 and #powers >0 and fails <= #powers do
i = util.boundWrap(i + 1, 1, #powers)
local p = powers[i]
if p and p.points <= hpoints*2 then -- Intentionally allow the budget to be exceeded slightly to guarantee powers at low levels
local state = {scaleup = math.max(1,(lev/(p.level_range[2] or 50))^0.5)} --Adjust scaleup factor for each power based on lev and level_range max
print(" * adding power: "..p.name.."("..p.points.." points), "..hpoints.." remaining")
selected_powers[p.name] = selected_powers[p.name] or {}
table.ruleMergeAppendAdd(selected_powers[p.name], p, {merger}, state)
if max_reached or p.unique then
print("Removing power from the list, ", p.name, "==", powers[i], "remaining:")
for i, v in ripairs(powers) do
if v.name == p.name then table.remove(powers, i) end
end
max_reached = false
end
hpoints = hpoints - p.points
p.points = p.points * 1.5 --increased cost (=diminishing returns) on extra applications of the same power
else
fails = fails + 1
end
end
-- o:resolve() o:resolve(nil, true)
-- Bias towards a shortened list of powers
local bias_powers = {}
local nb_bias = math.max(1,rng.range(math.ceil(#powers/2), 20*lev /(lev+50))) --Limit bias powers to 20 (50/5 * 2) powers
for i = 1, nb_bias do bias_powers[#bias_powers+1] = rng.table(powers) end
local hpoints = math.ceil(points / 2)
local i = 0
fails = 0
while hpoints > 0 and fails <= #bias_powers do
i = util.boundWrap(i + 1, 1, #bias_powers)
local p = bias_powers[i] and bias_powers[i]
if p and p.points <= hpoints * 2 then
local state = {scaleup = math.max(1,(lev/(p.level_range[2] or 50))^0.5)} --Adjust scaleup factor for each power based on lev and level_range max
print(" * adding bias power: "..p.name.."("..p.points.." points), "..hpoints.." remaining")
selected_powers[p.name] = selected_powers[p.name] or {}
table.ruleMergeAppendAdd(selected_powers[p.name], p, {merger}, state)
if max_reached or p.unique then
print("Removing power from bias list , ", p.name)
for i, v in ripairs(bias_powers) do
if v.name == p.name then table.remove(bias_powers, i) end
end
max_reached = false
end
hpoints = hpoints - p.points
p.points = p.points * 1.2 --increased cost (=diminishing returns) on extra applications of the same power, but less on the biased powers
else
fails = fails + 1
end
end
for _, ego in pairs(selected_powers) do
ego.instant_resolve = true -- resolve to be able to add
ego = engine.Entity.new(ego) -- get a real uid
game.zone:applyEgo(o, ego, "object", true)
end
o:resolve()
o:resolve(nil, true)
-- Always assign at least one power source based on themes and restrictions
if not o.power_source then
local not_ps = data.forbid_power_source or {}
local ps = data.power_source or {}
if themes.physical or themes.defense then ps.technique = true end
if themes.mental then ps[rng.percent(50) and 'nature' or 'psionic'] = true end
if themes.spell or themes.arcane or themes.blight or themes.temporal then
ps.arcane = true not_ps.antimagic = true
end
if themes.nature then ps.nature = true end
if themes.antimagic then
ps.antimagic = true not_ps.arcane = true
end
if not next(ps) then ps[rng.tableIndex(data.power_source or self.power_sources)] = true end
ps = table.minus_keys(ps, not_ps)
if not next(ps) then ps = {unknown = true} end
print(" * using implied power source(s) ", table.concat(table.keys(ps), ','))
o.power_source = ps
end
o.display = display
if data.post then
data.post(o)
end
if data.add_pool then self:addWorldArtifact(o) end
-- restore global variables
game.level.level = oldlev
resolvers.current_level = oldclev
return o
end
--- Adds randart properties (egos and random powers) to an existing object
-- @param o is the object to be updated (o.egos and o.randart_able should be defined as needed)
-- @param data is the table of randart parameters passed to generateRandart
-- usable powers and set properties are not overwritten if present
function _M:addRandartProperties(o, data)
print(" ** adding randart properties to ", o.name, o.uid)
data.base = o
-- properties to not overwrite
local protect_props = {name = true, uid=true, rarity = true, unided_name = true, define_as = true, unique = o.unique, randart = o.unique, no_unique_lore = true, require=true, egos = true, randart_able = true}
if o.use_power or o.use_talent or o.use_simple then -- allow only one use power
table.merge(protect_props, {use_power = true, use_talent = true, use_simple = true,
use_no_energy=true, use_no_blind = o.use_no_blind, use_no_silence = o.use_no_silence, use_no_wear = o.use_no_wear,
talent_cooldown = true, power = true, max_power=true, power_regen = true, charm_on_use = o.charm_on_use})
end
if o.set_list then -- preserve set properties Note: mindstar set flags ARE copied
table.merge(protect_props, {set_list = true, on_set_complete = true, on_set_broken = true})
end
print(" ** addRandartProperties: property merge restrictions: ", table.concat(table.keys(protect_props), ','))
local art = game.state:generateRandart(data)
if art then
table.merge(o, art, true, protect_props, nil)
else
print(" ** FAILED to generate randart properties to add to ", o.name, o.uid)
end
end
local wda_cache = {}
--- Runs the worldmap directory AI
function _M:worldDirectorAI()
if not game.level.data.wda or not game.level.data.wda.script then return end
local script = wda_cache[game.level.data.wda.script]
if not script then
local function getBaseName(name)
local base = "/data"
local _, _, addon, rname = name:find("^([^+]+)%+(.+)$")
if addon and rname then
base = "/data-"..addon
name = rname
end
return base.."/wda/"..name..".lua"
end
local f, err = loadfile(getBaseName(game.level.data.wda.script))
if not f then error(err) end
wda_cache[game.level.data.wda.script] = f
script = f
end
game.level.level = game.player.level
setfenv(script, setmetatable({wda=game.level.data.wda}, {__index=_G}))
local ok, err = pcall(script)
if not ok and err then error(err) end
end
function _M:spawnWorldAmbush(enc, dx, dy, kind)
game:onTickEnd(function()
local gen = { class = "engine.generator.map.Forest",
edge_entrances = {4,6},
sqrt_percent = 50,
zoom = 10,
floor = "GRASS",
wall = "TREE",
down = "DOWN",
up = "GRASS_UP_WILDERNESS",
}
local g1 = game.level.map(dx, dy, engine.Map.TERRAIN)
local g2 = game.level.map(game.player.x, game.player.y, engine.Map.TERRAIN)
local g = g1
if not g or not g.can_encounter then g = g2 end
if not g or not g.can_encounter then return false end
if g.can_encounter == "desert" then gen.floor = "SAND" gen.wall = "PALMTREE" end
local terrains = mod.class.Grid:loadList{"/data/general/grids/basic.lua", "/data/general/grids/forest.lua", "/data/general/grids/sand.lua"}
terrains[gen.up].change_level_shift_back = true
local zone = mod.class.Zone.new("ambush", {
name = "Ambush!",
level_range = {game.player.level, game.player.level},
level_scheme = "player",
max_level = 1,
actor_adjust_level = function(zone, level, e) return zone.base_level + e:getRankLevelAdjust() + level.level-1 + rng.range(-1,2) end,
width = enc.width or 20, height = enc.height or 20,
-- no_worldport = true,
all_lited = true,
ambient_music = "last",
max_material_level = util.bound(math.ceil(game.player.level / 10), 1, 5),
min_material_level = util.bound(math.ceil(game.player.level / 10), 1, 5) - 1,
generator = {
map = gen,
actor = { class = "mod.class.generator.actor.Random", nb_npc = enc.nb or {1,1}, filters=enc.filters },
},
reload_lists = false,
npc_list = mod.class.NPC:loadList("/data/general/npcs/all.lua", nil, nil, function(e) e.make_escort=nil end),
grid_list = terrains,
object_list = mod.class.Object:loadList("/data/general/objects/objects.lua"),
trap_list = {},
post_process = function(level)
-- Find a good starting location, on the opposite side of the exit
local sx, sy = level.map.w-1, rng.range(0, level.map.h-1)
level.spots[#level.spots+1] = {
check_connectivity = "entrance",
x = sx,
y = sy,
}
level.default_down = level.default_up
level.default_up = {x=sx, y=sy}
end,
})
self.farm_factor = self.farm_factor or {}
self.farm_factor[kind] = self.farm_factor[kind] or 1
zone.objects_cost_modifier = self.farm_factor[kind]
zone.exp_worth_mult = self.farm_factor[kind]
self.farm_factor[kind] = self.farm_factor[kind] * 0.9
game.player:runStop()
game.player.energy.value = game.energy_to_act
game.paused = true
game:changeLevel(1, zone, {temporary_zone_shift=true})
engine.ui.Dialog:simplePopup("Ambush!", "You have been ambushed!")
end)
end
function _M:handleWorldEncounter(target)
local enc = target.on_encounter
if type(enc) == "function" then return enc() end
if type(enc) == "table" then
if enc.type == "ambush" then
local x, y = target.x, target.y
target:die()
self:spawnWorldAmbush(enc, x, y, target.name or "generic")
end
end
end
--------------------------------------------------------------------
-- Ambient sounds stuff
--------------------------------------------------------------------
function _M:makeAmbientSounds(level, t)
local s = {}
level.data.ambient_bg_sounds = s
for chan, data in pairs(t) do
data.name = chan
s[#s+1] = data
end
end
function _M:playAmbientSounds(level, s, nb_keyframes)
for i = 1, #s do
local data = s[i]
if data._sound then if not data._sound:playing() then data._sound = nil end end
if not data._sound and nb_keyframes > 0 and rng.chance(math.ceil(data.chance / nb_keyframes)) then
local f = rng.table(data.files)
data._sound = game:playSound(f)
local pos = {x=0,y=0,z=0}
if data.random_pos then
local a, r = rng.float(0, 2 * math.pi), rng.float(1, data.random_pos.rad or 10)
pos.x = math.cos(a) * r
pos.y = math.sin(a) * r
end
-- print("===playing", data.name, f, data._sound)
if data._sound then
if data.volume_mod then data._sound:volume(data._sound:volume() * data.volume_mod) end
if data.pitch then data._sound:pitch(data.pitch) end
end
end
end
end
--------------------------------------------------------------------
-- Weather stuff
--------------------------------------------------------------------
function _M:makeWeather(level, nb, params, typ)
if not config.settings.tome.weather_effects then return end
local ps = {}
params.width = level.map.w*level.map.tile_w
params.height = level.map.h*level.map.tile_h
for i = 1, nb do
local p = table.clone(params, true)
p.particle_name = p.particle_name:format(nb)
ps[#ps+1] = Particles.new(typ or "weather_storm", 1, p)
end
level.data.weather_particle = ps
end
function _M:displayWeather(level, ps, nb_keyframes)
local dx, dy = level.map:getScreenUpperCorner() -- Display at map border, always, so it scrolls with the map
for j = 1, #ps do
ps[j].ps:toScreen(dx, dy, true, 1)
end
end
function _M:makeWeatherShader(level, shader, params)
if not config.settings.tome.weather_effects then return end
local ps = level.data.weather_shader or {}
ps[#ps+1] = Shader.new(shader, params)
level.data.weather_shader = ps
end
function _M:displayWeatherShader(level, ps, x, y, nb_keyframes)
local dx, dy = level.map:getScreenUpperCorner() -- Display at map border, always, so it scrolls with the map
local sx, sy = level.map._map:getScroll()
local mapcoords = {(-sx + level.map.mx * level.map.tile_w) / level.map.viewport.width , (-sy + level.map.my * level.map.tile_h) / level.map.viewport.height}
for j = 1, #ps do
if ps[j].shad then
ps[j]:setUniform("mapCoord", mapcoords)
ps[j].shad:use(true)
core.display.drawQuad(x, y, level.map.viewport.width, level.map.viewport.height, 255, 255, 255, 255)
ps[j].shad:use(false)
end
end
end
local function doTint(from, to, amount)
local tint = {r = 0, g = 0, b = 0}
tint.r = (from.r * (1 - amount) + to.r * amount)
tint.g = (from.g * (1 - amount) + to.g * amount)
tint.b = (from.b * (1 - amount) + to.b * amount)
return tint
end
--- Compute a day/night cycle
-- Works by changing the tint of the map gradualy
function _M:dayNightCycle()
local map = game.level.map
local shown = map.color_shown
local obscure = map.color_obscure
if not config.settings.tome.daynight then
-- Restore defaults
map._map:setShown(unpack(shown))
map._map:setObscure(unpack(obscure))
return
end
local hour, minute = game.calendar:getTimeOfDay(game.turn)
hour = hour + (minute / 60)
local tint = {r = 0.1, g = 0.1, b = 0.1}
local startTint = {r = 0.1, g = 0.1, b = 0.1}
local endTint = {r = 0.1, g = 0.1, b = 0.1}
if hour <= 4 then
tint = {r = 0.1, g = 0.1, b = 0.1}
elseif hour > 4 and hour <= 7 then
startTint = { r = 0.1, g = 0.1, b = 0.1 }
endTint = { r = 0.3, g = 0.3, b = 0.5 }
tint = doTint(startTint, endTint, (hour - 4) / 3)
elseif hour > 7 and hour <= 12 then
startTint = { r = 0.3, g = 0.3, b = 0.5 }
endTint = { r = 0.9, g = 0.9, b = 0.9 }
tint = doTint(startTint, endTint, (hour - 7) / 5)
elseif hour > 12 and hour <= 18 then
startTint = { r = 0.9, g = 0.9, b = 0.9 }
endTint = { r = 0.9, g = 0.9, b = 0.6 }
tint = doTint(startTint, endTint, (hour - 12) / 6)
elseif hour > 18 and hour < 24 then
startTint = { r = 0.9, g = 0.9, b = 0.6 }
endTint = { r = 0.1, g = 0.1, b = 0.1 }
tint = doTint(startTint, endTint, (hour - 18) / 6)
end
map._map:setShown(shown[1] * (tint.r+0.4), shown[2] * (tint.g+0.4), shown[3] * (tint.b+0.4), shown[4])
map._map:setObscure(obscure[1] * (tint.r+0.2), obscure[2] * (tint.g+0.2), obscure[3] * (tint.b+0.2), obscure[4])
end
--------------------------------------------------------------------
-- Donations
--------------------------------------------------------------------
function _M:checkDonation(back_insert)
-- Multiple checks to see if this is a "good" time
-- This is only called when something nice happens (like an achievement)
-- We then check multiple conditions to make sure the player is in a good state of mind
-- Steam users have paid
if core.steam then
print("Donation check: steam user")
return
end
-- If this is a reccuring donator, do not bother her/him
if profile.auth and tonumber(profile.auth.donated) and profile.auth.sub == "yes" then
print("Donation check: already a reccuring donator")
return
end
-- Dont ask often
if profile.auth and tonumber(profile.auth.donated) then
local last = profile.mod.donations and profile.mod.donations.last_ask or 0
local min_interval = 30 * 24 * 60 * 60 -- 1 month
if os.time() < last + min_interval then
print("Donation check: too soon (donator)")
return
end
else
local last = profile.mod.donations and profile.mod.donations.last_ask or 0
local min_interval = 7 * 24 * 60 * 60 -- 1 week
if os.time() < last + min_interval then
print("Donation check: too soon (player)")
return
end
end
-- Not as soon as they start playing, wait 15 minutes
if os.time() - game.real_starttime < 15 * 60 then
print("Donation check: not started tome long enough")
return
end
-- Total playtime must be over a few hours
local total = profile.generic.modules_played and profile.generic.modules_played.tome or 0
if total + (os.time() - game.real_starttime) < 4 * 60 * 60 then
print("Donation check: total time too low")
return
end
-- Dont ask low level characters, they are probably still pissed to not have progressed further
if game.player.level < 10 then
print("Donation check: too low level")
return
end
-- Dont ask people in immediate danger
if game.player.life / game.player.max_life < 0.7 then
print("Donation check: too low life")
return
end
-- Dont ask people that already have their hands full
local nb_foes = 0
for i = 1, #game.player.fov.actors_dist do
local act = game.player.fov.actors_dist[i]
if act and game.player:reactionToward(act) < 0 and not act.dead then
if act.rank and act.rank > 3 then nb_foes = nb_foes + 1000 end -- Never with bosses in sight
nb_foes = nb_foes + 1
end
end
if nb_foes > 2 then
print("Donation check: too many foes")
return
end
-- Request money! Even a god has to eat :)
profile:saveModuleProfile("donations", {last_ask=os.time()})
if back_insert then
game:registerDialogAt(Donation.new(), 2)
else
game:registerDialog(Donation.new())
end
end
--------------------------------------------------------------
-- Loot filters
--------------------------------------------------------------
-- These are referenced by the "tome_drops" field in object filters
local drop_tables = {
normal = {
[1] = {
uniques = 0.5,
double_greater = 0,
greater_normal = 0,
greater = 0,
double_ego = 20,
ego = 45,
basic = 38,
money = 7,
lore = 2,
},
[2] = {
uniques = 0.7,
double_greater = 0,
greater_normal = 0,
greater = 10,
double_ego = 35,
ego = 30,
basic = 41,
money = 8,
lore = 2.5,
},
[3] = {
uniques = 1,
double_greater = 10,
greater_normal = 15,
greater = 25,
double_ego = 25,
ego = 25,
basic = 10,
money = 8.5,
lore = 2.5,
},
[4] = {
uniques = 1.1,
double_greater = 15,
greater_normal = 35,
greater = 25,
double_ego = 20,
ego = 5,
basic = 5,
money = 8,
lore = 3,
},
[5] = {
uniques = 1.2,
double_greater = 35,
greater_normal = 30,
greater = 20,
double_ego = 10,
ego = 5,
basic = 5,
money = 8,
lore = 3,
},
},
store = {
[1] = {
uniques = 0.5,
double_greater = 10,
greater_normal = 15,
greater = 25,
double_ego = 45,
ego = 10,
basic = 0,
money = 0,
lore = 0,
},
[2] = {
uniques = 0.5,
double_greater = 20,
greater_normal = 18,
greater = 25,
double_ego = 35,
ego = 8,
basic = 0,
money = 0,
lore = 0,
},
[3] = {
uniques = 0.5,
double_greater = 30,
greater_normal = 22,
greater = 25,
double_ego = 25,
ego = 6,
basic = 0,
money = 0,
lore = 0,
},
[4] = {
uniques = 0.5,
double_greater = 40,
greater_normal = 30,
greater = 25,
double_ego = 20,
ego = 4,
basic = 0,
money = 0,
lore = 0,
},
[5] = {
uniques = 0.5,
double_greater = 50,
greater_normal = 30,
greater = 25,
double_ego = 10,
ego = 0,
basic = 0,
money = 0,
lore = 0,
},
},
boss = {
[1] = {
uniques = 3,
double_greater = 0,
greater_normal = 0,
greater = 5,
double_ego = 45,
ego = 45,
basic = 0,
money = 4,
lore = 0,
},
[2] = {
uniques = 4,
double_greater = 0,
greater_normal = 8,
greater = 15,
double_ego = 40,
ego = 35,
basic = 0,
money = 4,
lore = 0,
},
[3] = {
uniques = 5,
double_greater = 10,
greater_normal = 22,
greater = 25,
double_ego = 25,
ego = 20,
basic = 0,
money = 4,
lore = 0,
},
[4] = {
uniques = 6,
double_greater = 40,
greater_normal = 30,
greater = 25,
double_ego = 20,
ego = 0,
basic = 0,
money = 4,
lore = 0,
},
[5] = {
uniques = 7,
double_greater = 10,
greater_normal = 30,
greater = 25,
double_ego = 10,
ego = 0,
basic = 0,
money = 4,
lore = 0,
},
},
}
-- These are referenced by the "tome_mod" field in object filters (multipliers for drop_tables)
local loot_mod = {
uvault = { -- Uber vault
uniques = 40,
double_greater = 8,
greater_normal = 5,
greater = 3,
double_ego = 0,
ego = 0,
basic = 0,
money = 0,
lore = 0,
material_mod = 1,
},
gvault = { -- Greater vault
uniques = 10,
double_greater = 2,
greater_normal = 2,
greater = 2,
double_ego = 1,
ego = 0,
basic = 0,
money = 0,
lore = 0,
material_mod = 1,
},
vault = { -- Default vault
uniques = 5,
double_greater = 2,
greater_normal = 3,
greater = 3,
double_ego = 2,
ego = 0,
basic = 0,
money = 0,
lore = 0,
material_mod = 1,
},
}
--- get the default drop table for the current level and zone
local default_drops = function(zone, level, what)
if zone.default_drops then return zone.default_drops end
local lev = util.bound(math.ceil(zone:level_adjust_level(level, "object") / 10), 1, 5)
-- print("[TOME ENTITY FILTER] making default loot table for", what, lev)
return table.clone(drop_tables[what][lev])
end
function _M:defaultEntityFilter(zone, level, type)
if type ~= "object" then return end
-- By default we dont apply special filters, but we always provide one so that entityFilter is called
return {
tome = default_drops(zone, level, "normal"),
}
end
--- Alter any entity filters to process tome specific loot tables (Objects only)
-- Here be magic! We tweak and convert and turn and create filters! It's magic but it works :)
-- Filter fields interpreted:
-- force_tome_drops: set true to use the tome default drop tables (defined above)
-- no_tome_drops: set true to prevent auto loading default tome drop tables
-- tome: specific tome drop table to use (set == true to use the default "normal" table for the zone/level)
-- tome_mod: specific table of multipliers for each type of drop or a string indexing a loot_mod table (defined above)
function _M:entityFilterAlter(zone, level, type, filter)
if type ~= "object" then return filter end
if filter.force_tome_drops or (not filter.tome and not filter.defined and not filter.special and not filter.unique and not filter.ego_chance and not filter.ego_filter and not filter.no_tome_drops) then
filter = table.clone(filter)
filter.tome = default_drops(zone, level, filter.tome_drops or "normal")
end
if filter.tome then
local t = (filter.tome == true) and default_drops(zone, level, "normal") or filter.tome
filter.tome = nil
if filter.tome_mod then
t = table.clone(t)
if _G.type(filter.tome_mod) == "string" then filter.tome_mod = loot_mod[filter.tome_mod] end
for k, v in pairs(filter.tome_mod) do
-- print(" ***** LOOT MOD", k, v)
t[k] = (t[k] or 0) * v
end
end
-- If we request a specific type/subtype, we don't want categories that could make that not happen
if filter.type or filter.subtype or filter.name then t.money = 0 t.lore = 0 end
local u = t.uniques or 0
local dg = u + (t.double_greater or 0)
local ge = dg + (t.greater_normal or 0)
local g = ge + (t.greater or 0)
local de = g + (t.double_ego or 0)
local e = de + (t.ego or 0)
local m = e + (t.money or 0)
local l = m + (t.lore or 0)
local total = l + (t.basic or 0)
local r = rng.float(0, total)
if r < u then
print("[TOME ENTITY FILTER] selected Uniques", r, u)
filter.unique = true
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "lore"
elseif r < dg then
print("[TOME ENTITY FILTER] selected Double Greater", r, dg)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance={tries = { {ego_chance=100, properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source}, {ego_chance=100, properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source} } }
elseif r < ge then
print("[TOME ENTITY FILTER] selected Greater + Ego", r, ge)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance={tries = { {ego_chance=100, properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source}, {ego_chance=100, not_properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source} }}
elseif r < g then
print("[TOME ENTITY FILTER] selected Greater", r, g)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance={tries = { {ego_chance=100, properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source} } }
elseif r < de then
print("[TOME ENTITY FILTER] selected Double Ego", r, de)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance={tries = { {ego_chance=100, not_properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source}, {ego_chance=100, not_properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source} }}
elseif r < e then
print("[TOME ENTITY FILTER] selected Ego", r, e)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance={tries = { {ego_chance=100, not_properties={"greater_ego"}, power_source=filter.power_source, forbid_power_source=filter.forbid_power_source} } }
elseif r < m then
print("[TOME ENTITY FILTER] selected Money", r, m)
filter.special = function(e) return e.type == "money" or e.type == "gem" end
elseif r < l then
print("[TOME ENTITY FILTER] selected Lore", r, l)
filter.special = function(e) return e.lore and true or false end
else
print("[TOME ENTITY FILTER] selected basic", r, total)
filter.not_properties = filter.not_properties or {}
filter.not_properties[#filter.not_properties+1] = "unique"
filter.ego_chance = -1000
end
end
if filter.random_object then
print("[TOME ENTITY FILTER] random object requested, removing ego chances")
filter.ego_chance = -1000
end
-- By default we dont apply special filters, but we always provide one so that entityFilter is called
return filter
end
--- Provide some additional filter checks to apply when generating an entity
-- called in Zone:makeEntity by the zone.check_filter function generated when loading a zone
-- filter fields interpreted:
-- ignore_material_restriction: set true to ignore zone material level restrictions (Objects)
-- tome_mod.material_mod: increase maximum allowed material level
-- forbid_power_source: table of power sources not allowed
-- power_source: table of power sources required
function _M:entityFilter(zone, e, filter, type)
if filter.forbid_power_source then
if e.power_source then
for k, _ in pairs(filter.forbid_power_source) do
if e.power_source[k] then return false end
end
end
end
if filter.power_source and e.power_source then
local ok = false
for k, _ in pairs(filter.power_source) do
if e.power_source[k] then ok = true break end
end
if not ok then return false end
end
if type == "object" then
if not filter.ignore_material_restriction then
local min_mlvl = util.getval(zone.min_material_level)
local max_mlvl = util.getval(zone.max_material_level)
if filter.tome_mod and filter.tome_mod.material_mod then max_mlvl = util.bound((max_mlvl or 3) + filter.tome_mod.material_mod, 1, 5) end
if min_mlvl and not e.material_level_min_only then
if not e.material_level then return true end
if e.material_level < min_mlvl then return false end
end
if max_mlvl then
if not e.material_level then return true end
if e.material_level > max_mlvl then return false end
end
end
if e.lore and e.rarity and util.getval(zone.no_random_lore) then return false end
if filter.random_object and not e.randart_able then return false end
return true
else
return true
end
end
-- Randbosses tend to cause problems early game so we check for problematic cases and reduce their power at low levels here
-- Called when adding to level after the actor is fully resolved and sustains are activated (these caps are often hit because of sustains)
local standard_rnd_boss_adjust = function(b)
if b.level <= 30 then
-- Damage reduction is applied in all cases, acknowledging the frontloaded strength of randbosses and the potential for players to lack tools early
b.inc_damage = b.inc_damage or {}
--local change = (70 * (30 - b.level + 1) / 30) + 20
local change = 95 - b.level * 3
b.inc_damage.all = math.max(-80, (b.inc_damage.all or 0) - change) -- Minimum of 20% damage
-- Things prone to binary outcomes (0 damage, 0 hit rate, ...) like armor and defense are only reduced if they exceed a cap per level regardless of source
-- This lets us not worry about stuff like Shield Wall+lucky equipment creating early threats that some builds cannot hurt
-- Note that while these seem strict they are *not* saying these values are unreasonable early for anything, they're saying they're unreasonable for randbosses specifically
local max = b.level / 2
local flat = b:combatGetFlatResist()
change = (max - flat)
if flat > max then
b.flat_damage_armor.all = b.flat_damage_armor.all - (flat - max)
print("[standard_rnd_boss_adjust]: Adjusting flat armor", flat, "Max", max, "Change", change)
end
if b.level <= 20 then
local armor = b:combatArmor()
max = b.level
change = (max - armor)
if armor > max then
b.combat_armor = b.combat_armor - (armor - max)
print("[standard_rnd_boss_adjust]: Adjusting armor", armor, "Max", max, "Change", change)
end
local defense = b:combatDefense()
max = b.level
change = (max - defense)
if defense > max then
b.combat_def = b.combat_def - (defense - max)
print("[standard_rnd_boss_adjust]: Adjusting defense", defense, "Max", max, "Change", change)
end
-- Temporarily just hard removing this early game pending this stat not being spammed everywhere causing tons of damage most people don't even notice is happening
local retal = rng.table(table.listify(b.on_melee_hit))
if retal then
b.on_melee_hit = {}
--b.on_melee_hit[retal[1]] = retal[2]
end
end
-- Early game melee don't have much mobility which makes randbosses too good at running and pulling more enemies in or being generally frustrating
b.ai_tactic.escape = -1
b.ai_tactic.safe_range = 1
-- Cap the talent level of crippling debuffs (stun, ...) at 1 + floor(level / 10)
-- rnd_boss_restrict is the right way to handle this for most things
-- Tactical tables can have a variety of structures, so we just look in all subtables for a key named "stun"
for id, level in pairs(b.talents) do
local talent = b:getTalentFromId(id)
if talent and talent.tactical and _G.type(talent.tactical) == "table" then
table.check(
talent.tactical,
function(t, where, v, tv)
if tv == "string" and (v:lower() == "stun") then
b.talents[id] = math.min(b.talents[id], math.floor(b.level / 10) + 1)
return false
else
return true
end
end)
end
end
print("[entityFilterPost]: Done nerfing randboss")
end
end -- End of standard_rnd_boss_adjust
--- make some changes to an entity based on its filter parameters before finishing (resolving) it
-- called in Zone:makeEntity by the zone.post_filter function generated when loading a zone
-- filter fields interpreted:
-- random_boss: data to convert a non-unique actor to a random boss with game.state:createRandomBoss
-- random_elite: data to merge to convert a non-unique actor to a random elite with game.state:createRandomBoss
-- random_object: data to convert a non-unique object into random_object using game.state:generateRandart
function _M:entityFilterPost(zone, level, type, e, filter)
if type == "actor" then
if filter.random_boss and not e.unique then
if _G.type(filter.random_boss) == "boolean" then filter.random_boss = {}
else filter.random_boss = table.clone(filter.random_boss, true) end
filter.random_boss.level = filter.random_boss.level or zone:level_adjust_level(level, zone, type)
filter.random_boss.rnd_boss_final_adjust = filter.random_boss.rnd_boss_final_adjust or game.state.birth.random_boss_adjust_fct or standard_rnd_boss_adjust
e = self:createRandomBoss(e, filter.random_boss)
elseif filter.random_elite and not e.unique then
if _G.type(filter.random_elite) == "boolean" then filter.random_elite = {}
else filter.random_elite = table.clone(filter.random_elite, true) end
local lev = filter.random_elite.level or zone:level_adjust_level(level, zone, type)
local base = {
nb_classes=1,
rank=3.2, ai = "tactical",
life_rating = filter.random_elite.life_rating or function(v) return v * 1.5 + 2 end,
loot_quality = "store",
loot_quantity = 0,
drop_equipment = false,
no_loot_randart = true,
resources_boost = 1.5,
talent_cds_factor = (lev <= 10) and 3 or ((lev <= 20) and 2 or nil),
class_filter = filter.class_filter,
no_class_restrictions = filter.no_class_restrictions,
level = lev,
nb_rares = filter.random_elite.nb_rares or 1,
check_talents_level = true,
user_post = filter.post,
post = function(b, data)
-- Drop
for i = 1, data.nb_rares do -- generate rares as weak (1 ego) randarts with more and stronger powers
local fil = {lev=lev, egos=1, greater_egos_bias = 0, power_points_factor = 3, nb_themes_add = 1, nb_powers_add = 2, forbid_power_source=b.not_power_source,
base_filter = {no_tome_drops=true, ego_filter={keep_egos=true, ego_chance=-1000},
special=function(e)
return (not e.unique and e.randart_able) and (not e.material_level or e.material_level >= 1) and true or false
end}
}
local o = game.state:generateRandart(fil, nil, true)
if o then
-- print("[entityFilterPost]: Generated random object for", tostring(b.name))
o.unique, o.randart, o.rare = nil, nil, true
if o.__original then
local e = o.__original
e.unique, e.randart, e.rare = nil, nil, true
end
b:addObject(b.INVEN_INVEN, o)
game.zone:addEntity(game.level, o, "object")
else
print("[entityFilterPost]: Failed to generate random object for", tostring(b.name))
end
end
if data.user_post then data.user_post(b, data) end
end,
rnd_boss_final_adjust = filter.random_elite.rnd_boss_final_adjust or game.state.birth.random_boss_adjust_fct or standard_rnd_boss_adjust
}
e = self:createRandomBoss(e, table.merge(base, filter.random_elite, true))
end
elseif type == "object" then
if filter.random_object and not e.unique and e.randart_able then -- convert the object to a (weak) Randart
local f_data = _G.type(filter.random_object) == "table" and filter.random_object or {}
-- default parameters
local data = {base = e, egos = 1, nb_powers_add = 1, nb_points_add = 2,
lev = math.max(1, game.zone:level_adjust_level(game.level, game.zone, "object")),
post = function(o)
if f_data.post then f_data.post(o) end
o.rare = true o.unique = nil o.randart = nil
end,
namescheme = 3,
}
-- update with filter specifications
table.merge(data, f_data, false, {base=true, post=true, base_filter=true})
print("[entityFilterPost]: filter.random_object forcing conversion to Randart:", e.name) table.print(data)
e = game.state:generateRandart(data)
if not e then
print("[GameState:entityFilterPost] failed to generate random object, data:") table.print(data)
print("traceback:") print(debug.traceback())
end
end
end
return e
end
--- Modify/create an ego filter(objects only, used when adding egos)
-- called in Zone:finishEntity by the zone.ego_filter function generated when loading a zone
-- checks power_source compatibility for egos as they are added to the object
function _M:egoFilter(zone, level, type, etype, e, ego_filter, egos_list, picked_etype)
if type ~= "object" then return ego_filter end
if not ego_filter then ego_filter = {}
else ego_filter = table.clone(ego_filter, true) end
local arcane_check = false
local nature_check = false
local am_check = false
local unique_check = false
for i = 1, #egos_list do
local e = egos_list[i]
if e.power_source and e.power_source.arcane then arcane_check = true end
if e.power_source and e.power_source.nature then nature_check = true end
if e.power_source and e.power_source.antimagic then am_check = true end
if e.unique_ego then unique_check = true end
end
local fcts = {}
if arcane_check then
fcts[#fcts+1] = function(ego) return not ego.power_source or not ego.power_source.nature or rng.percent(20) end
fcts[#fcts+1] = function(ego) return not ego.power_source or not ego.power_source.antimagic end
end
if nature_check then
fcts[#fcts+1] = function(ego) return not ego.power_source or not ego.power_source.arcane or rng.percent(20) end
end
if am_check then
fcts[#fcts+1] = function(ego) return not ego.power_source or not ego.power_source.arcane end
end
-- If unique_ego is a string it represents a category a single item can only have 1 ego from, this is useful for stuff that overwrites each other like item actives, etc
-- If unique_ego is a non-string we just prevent it from being applied to the same item twice
if unique_check then
fcts[#fcts+1] = function(ego)
if _G.type(ego.unique_ego) == "string" then
for k,v in pairs(e.ego_list) do
if v and v[1] and v[1].unique_ego and v[1].unique_ego == ego.unique_ego then
return false
end
end
end
-- Use keywords as a proxy for name, a bit simpler than going through Object.ego_list
for k,v in pairs(ego.keywords) do
if e.keywords and e.keywords[k] then return false end
end
return true
end
end
if #fcts > 0 then
local old = ego_filter.special
ego_filter.special = function(ego)
for i = 1, #fcts do
if not fcts[i](ego) then return false end
end
if old and not old(ego) then return false end
return true
end
end
return ego_filter
end
--------------------------------------------------------------
-- Random zones
--------------------------------------------------------------
local random_zone_layouts = {
-- Forest
{ name="forest", rarity=3, gen=function(data) return {
class = "engine.generator.map.Forest",
edge_entrances = {data.less_dir, data.more_dir},
zoom = rng.range(2,6),
sqrt_percent = rng.range(20, 50),
noise = "fbm_perlin",
floor = data:getFloor(),
wall = data:getWall(),
up = data:getUp(),
down = data:getDown(),
} end },
-- Cavern
{ name="cavern", rarity=3, gen=function(data)
local floors = data.w * data.h * 0.4
return {
class = "engine.generator.map.Cavern",
zoom = rng.range(10, 20),
min_floor = rng.range(floors / 2, floors),
floor = data:getFloor(),
wall = data:getWall(),
up = data:getUp(),
down = data:getDown(),
} end },
-- Rooms
{ name="rooms", rarity=3, gen=function(data)
local rooms = {"random_room"}
if rng.percent(30) then rooms = {"forest_clearing"} end
return {
class = "engine.generator.map.Roomer",
nb_rooms = math.floor(data.w * data.h / 250),
rooms = rooms,
lite_room_chance = rng.range(0, 100),
['.'] = data:getFloor(),
['#'] = data:getWall(),
up = data:getUp(),
down = data:getDown(),
door = data:getDoor(),
} end },
-- Maze
{ name="maze", rarity=3, gen=function(data)
return {
class = "engine.generator.map.Maze",
floor = data:getFloor(),
wall = data:getWall(),
up = data:getUp(),
down = data:getDown(),
door = data:getDoor(),
} end, guardian_alert=true },
-- Sets
{ name="sets", rarity=3, gen=function(data)
local set = rng.table{
{"3x3/base", "3x3/tunnel", "3x3/windy_tunnel"},
{"5x5/base", "5x5/tunnel", "5x5/windy_tunnel", "5x5/crypt"},
{"7x7/base", "7x7/tunnel"},
}
return {
class = "engine.generator.map.TileSet",
tileset = set,
['.'] = data:getFloor(),
['#'] = data:getWall(),
up = data:getUp(),
down = data:getDown(),
door = data:getDoor(),
["'"] = data:getDoor(),
} end },
-- Building
--[[ not yet { name="building", rarity=4, gen=function(data)
return {
class = "engine.generator.map.Building",
lite_room_chance = rng.range(0, 100),
max_block_w = rng.range(14, 20), max_block_h = rng.range(14, 20),
max_building_w = rng.range(4, 8), max_building_h = rng.range(4, 8),
floor = data:getFloor(),
wall = data:getWall(),
up = data:getUp(),
down = data:getDown(),
door = data:getDoor(),
} end },
]]
-- "Octopus"
{ name="octopus", rarity=6, gen=function(data)
return {
class = "engine.generator.map.Octopus",
main_radius = {0.3, 0.4},
arms_radius = {0.1, 0.2},
arms_range = {0.7, 0.8},
nb_rooms = {5, 9},
['.'] = data:getFloor(),
['#'] = data:getWall(),
up = data:getUp(),
down = data:getDown(),
door = data:getDoor(),
} end },
}
local random_zone_themes = {
-- Trees
{ name="trees", rarity=3, gen=function() return {
load_grids = {"/data/general/grids/forest.lua"},
getDoor = function(self) return "GRASS" end,
getFloor = function(self) return function() if rng.chance(20) then return "FLOWER" else return "GRASS" end end end,
getWall = function(self) return "TREE" end,
getUp = function(self) return "GRASS_UP"..self.less_dir end,
getDown = function(self) return "GRASS_DOWN"..self.more_dir end,
} end },
-- Walls
{ name="walls", rarity=2, gen=function() return {
load_grids = {"/data/general/grids/basic.lua"},
getDoor = function(self) return "DOOR" end,
getFloor = function(self) return "FLOOR" end,
getWall = function(self) return "WALL" end,
getUp = function(self) return "UP" end,
getDown = function(self) return "DOWN" end,
} end },
-- Underground
{ name="underground", rarity=5, gen=function() return {
load_grids = {"/data/general/grids/underground.lua"},
getDoor = function(self) return "UNDERGROUND_FLOOR" end,
getFloor = function(self) return "UNDERGROUND_FLOOR" end,
getWall = function(self) return "UNDERGROUND_TREE" end,
getUp = function(self) return "UNDERGROUND_LADDER_UP" end,
getDown = function(self) return "UNDERGROUND_LADDER_DOWN" end,
} end },
-- Crystals
{ name="crystal", rarity=4, gen=function() return {
load_grids = {"/data/general/grids/underground.lua"},
getDoor = function(self) return "CRYSTAL_FLOOR" end,
getFloor = function(self) return "CRYSTAL_FLOOR" end,
getWall = function(self) return {"CRYSTAL_WALL","CRYSTAL_WALL2","CRYSTAL_WALL3","CRYSTAL_WALL4","CRYSTAL_WALL5","CRYSTAL_WALL6","CRYSTAL_WALL7","CRYSTAL_WALL8","CRYSTAL_WALL9","CRYSTAL_WALL10","CRYSTAL_WALL11","CRYSTAL_WALL12","CRYSTAL_WALL13","CRYSTAL_WALL14","CRYSTAL_WALL15","CRYSTAL_WALL16","CRYSTAL_WALL17","CRYSTAL_WALL18","CRYSTAL_WALL19","CRYSTAL_WALL20",} end,
getUp = function(self) return "CRYSTAL_LADDER_UP" end,
getDown = function(self) return "CRYSTAL_LADDER_DOWN" end,
} end },
-- Sand
{ name="sand", rarity=3, gen=function() return {
load_grids = {"/data/general/grids/sand.lua"},
getDoor = function(self) return "UNDERGROUND_SAND" end,
getFloor = function(self) return "UNDERGROUND_SAND" end,
getWall = function(self) return "SANDWALL" end,
getUp = function(self) return "SAND_LADDER_UP" end,
getDown = function(self) return "SAND_LADDER_DOWN" end,
} end },
-- Desert
{ name="desert", rarity=3, gen=function() return {
load_grids = {"/data/general/grids/sand.lua"},
getDoor = function(self) return "SAND" end,
getFloor = function(self) return "SAND" end,
getWall = function(self) return "PALMTREE" end,
getUp = function(self) return "SAND_UP"..self.less_dir end,
getDown = function(self) return "SAND_DOWN"..self.more_dir end,
} end },
-- Slime
{ name="slime", rarity=4, gen=function() return {
load_grids = {"/data/general/grids/slime.lua"},
getDoor = function(self) return "SLIME_DOOR" end,
getFloor = function(self) return "SLIME_FLOOR" end,
getWall = function(self) return "SLIME_WALL" end,
getUp = function(self) return "SLIME_UP" end,
getDown = function(self) return "SLIME_DOWN" end,
} end },
}
function _M:createRandomZone(zbase)
zbase = zbase or {}
------------------------------------------------------------
-- Select theme
------------------------------------------------------------
local themes = {}
for i, theme in ipairs(random_zone_themes) do for j = 1, 100 / theme.rarity do themes[#themes+1] = theme end end
local theme = rng.table(themes)
print("[RANDOM ZONE] Using theme", theme.name)
local data = theme.gen()
local grids = {}
for i, file in ipairs(data.load_grids) do
mod.class.Grid:loadList(file, nil, grids)
end
------------------------------------------------------------
-- Misc data
------------------------------------------------------------
data.depth = zbase.depth or rng.range(2, 4)
data.min_lev, data.max_lev = zbase.min_lev or game.player.level, zbase.max_lev or game.player.level + 15
data.w, data.h = zbase.w or rng.range(40, 60), zbase.h or rng.range(40, 60)
data.max_material_level = util.bound(math.ceil(data.min_lev / 10), 1, 5)
data.min_material_level = data.max_material_level - 1
data.less_dir = rng.table{2, 4, 6, 8}
data.more_dir = ({[2]=8, [8]=2, [4]=6, [6]=4})[data.less_dir]
-- Give a random tint
data.tint_s = {1, 1, 1, 1}
if rng.percent(10) then
local sr, sg, sb
sr = rng.float(0.3, 1)
sg = rng.float(0.3, 1)
sb = rng.float(0.3, 1)
local max = math.max(sr, sg, sb)
data.tint_s[1] = sr / max
data.tint_s[2] = sg / max
data.tint_s[3] = sb / max
end
data.tint_o = {data.tint_s[1] * 0.6, data.tint_s[2] * 0.6, data.tint_s[3] * 0.6, 0.6}
------------------------------------------------------------
-- Select layout
------------------------------------------------------------
local layouts = {}
for i, layout in ipairs(random_zone_layouts) do for j = 1, 100 / layout.rarity do layouts[#layouts+1] = layout end end
local layout = rng.table(layouts)
print("[RANDOM ZONE] Using layout", layout.name)
------------------------------------------------------------
-- Select Music
------------------------------------------------------------
local musics = {}
for i, file in ipairs(fs.list("/data/music/")) do
if file:find("%.ogg$") then musics[#musics+1] = file end
end
------------------------------------------------------------
-- Create a boss
------------------------------------------------------------
local npcs = mod.class.NPC:loadList("/data/general/npcs/random_zone.lua")
local list = {}
for _, e in ipairs(npcs) do
if e.rarity and e.level_range and e.level_range[1] <= data.min_lev and (not e.level_range[2] or e.level_range[2] >= data.min_lev) and e.rank > 1 and not e.unique then
list[#list+1] = e
end
end
local base = rng.table(list)
local boss, boss_id = self:createRandomBoss(base, {level=data.min_lev + data.depth + rng.range(2, 4)})
npcs[boss_id] = boss
------------------------------------------------------------
-- Entities
------------------------------------------------------------
local base_nb = math.sqrt(data.w * data.h)
local nb_npc = { math.ceil(base_nb * 0.4), math.ceil(base_nb * 0.6) }
local nb_trap = { math.ceil(base_nb * 0.1), math.ceil(base_nb * 0.2) }
local nb_object = { math.ceil(base_nb * 0.06), math.ceil(base_nb * 0.12) }
if rng.percent(20) then nb_trap = {0,0} end
if rng.percent(10) then nb_object = {0,0} end
------------------------------------------------------------
-- Name
------------------------------------------------------------
local ngd = NameGenerator.new(randart_name_rules.default2)
local name = ngd:generate()
local short_name = name:lower():gsub("[^a-z]", "_")
------------------------------------------------------------
-- Final glue
------------------------------------------------------------
local zone = mod.class.Zone.new(short_name, {
name = name,
level_range = {data.min_lev, data.max_lev},
level_scheme = "player",
max_level = data.depth,
actor_adjust_level = function(zone, level, e) return zone.base_level + e:getRankLevelAdjust() + level.level-1 + rng.range(-1,2) end,
width = data.w, height = data.h,
color_shown = data.tint_s,
color_obscure = data.tint_o,
ambient_music = rng.table(musics),
min_material_level = data.min_material_level,
max_material_level = data.max_material_level,
no_random_lore = true,
persistent = "zone_temporary",
reload_lists = false,
generator = {
map = layout.gen(data),
actor = { class = "mod.class.generator.actor.Random", nb_npc = nb_npc, guardian = boss_id, abord_no_guardian=true, guardian_alert=layout.guardian_alert },
trap = { class = "engine.generator.trap.Random", nb_trap = nb_trap, },
object = { class = "engine.generator.object.Random", nb_object = nb_object, },
},
levels = { [1] = { generator = { map = { up = data:getFloor() } } } },
basic_floor = util.getval(data:getFloor()),
npc_list = npcs,
grid_list = grids,
object_list = mod.class.Object:loadList("/data/general/objects/objects.lua"),
trap_list = mod.class.Trap:loadList("/data/general/traps/alarm.lua"),
})
return zone, boss
end
--- Add one or more character classes to an actor, updating stats, talents, and equipment
-- @param b = actor(boss) to update
-- @param data = optional parameters:
-- @param data.update_body a table of inventories to add, set true to add a full suite of inventories
-- @param data.force_classes = specific subclasses to apply first, ignoring restrictions
-- {"Rogue", "Necromancer", Corruptor = true, Bulwark = true, ...}
-- applied in order of numerical index, then randomly
-- @param data.nb_classes = random classes to add (in addition to any forced classes) <2>
-- @param data.class_filter = function(cdata, b) that must return true for any class picked.
-- (cdata, b = subclass definition in engine.Birther.birth_descriptor_def.subclass, boss (before classes are applied))
-- @param data.no_class_restrictions set true to skip class compatibility checks <nil>
-- @param data.autolevel = autolevel scheme to use for stats (set false to keep current) <"random_boss">
-- @param data.spend_points = spend any unspent stat points (after adding all classes)
-- @param data.add_trees = {["talent tree name 1"]=true/mastery bonus, ["talent tree name 2"]=true/mastery bonus, ..} additional talent trees to learn
-- @param data.check_talents_level set true to enforce talent level restrictions <nil>
-- @param data.auto_sustain set true to activate sustained talents at birth <nil>
-- @param data.forbid_equip set true to not apply class equipment resolvers or equip inventory <nil>
-- @param data.loot_quality = drop table to use for equipment <"boss">
-- @param data.drop_equipment set true to force dropping of equipment <nil>
-- @param instant set true to force instant learning of talents and generating golem <nil>
function _M:applyRandomClass(b, data, instant)
if not data.level then data.level = b.level end
------------------------------------------------------------
-- Apply talents from classes
------------------------------------------------------------
-- Apply a class
local Birther = require "engine.Birther"
b.learn_tids = {}
local function apply_class(class)
local mclasses = Birther.birth_descriptor_def.class
local mclass = nil
for name, data in pairs(mclasses) do
if data.descriptor_choices and data.descriptor_choices.subclass and data.descriptor_choices.subclass[class.name] then mclass = data break end
end
if not mclass then return end
print("[applyRandomClass]", b.uid, b.name, "Adding class", class.name, mclass.name)
-- add class to list and build inherent power sources
b.descriptor = b.descriptor or {}
b.descriptor.classes = b.descriptor.classes or {}
table.append(b.descriptor.classes, {class.name})
-- build inherent power sources and forbidden power sources
-- b.forbid_power_source --> b.not_power_source used for classes
b.power_source = table.merge(b.power_source or {}, class.power_source or {})
b.not_power_source = table.merge(b.not_power_source or {}, class.not_power_source or {})
-- update power source parameters with the new class
b.not_power_source, b.power_source = self:updatePowers(self:attrPowers(b, b.not_power_source), b.power_source)
print(" power types: not_power_source =", table.concat(table.keys(b.not_power_source),","), "power_source =", table.concat(table.keys(b.power_source),","))
-- Update/initialize base stats, set stats auto_leveling
if class.stats or b.auto_stats then
b.stats, b.auto_stats = b.stats or {}, b.auto_stats or {}
for stat, v in pairs(class.stats or {}) do
local stat_id = b.stats_def[stat].id
b.stats[stat_id] = (b.stats[stat_id] or 10) + v
for i = 1, v do b.auto_stats[#b.auto_stats+1] = stat_id end
end
end
if data.autolevel ~= false then b.autolevel = data.autolevel or "random_boss" end
-- Class talent categories
for tt, d in pairs(mclass.talents_types or {}) do b:learnTalentType(tt, true) b:setTalentTypeMastery(tt, (b:getTalentTypeMastery(tt) or 1) + d[2]) end
for tt, d in pairs(mclass.unlockable_talents_types or {}) do b:learnTalentType(tt, true) b:setTalentTypeMastery(tt, (b:getTalentTypeMastery(tt) or 1) + d[2]) end
for tt, d in pairs(class.talents_types or {}) do b:learnTalentType(tt, true) b:setTalentTypeMastery(tt, (b:getTalentTypeMastery(tt) or 1) + d[2]) end
for tt, d in pairs(class.unlockable_talents_types or {}) do b:learnTalentType(tt, true) b:setTalentTypeMastery(tt, (b:getTalentTypeMastery(tt) or 1) + d[2]) end
-- Non-class talent categories
if data.add_trees then
for tt, d in pairs(data.add_trees) do
if not b:knowTalentType(tt) then
if type(d) ~= "number" then d = rng.range(1, 3)*0.1 end
b:learnTalentType(tt, true)
b:setTalentTypeMastery(tt, (b:getTalentTypeMastery(tt) or 1) + d)
end
end
end
-- Add starting equipment
local apply_resolvers = function(k, resolver)
if type(resolver) == "table" and resolver.__resolver then
if resolver.__resolver == "equip" then
if not data.forbid_equip then
resolver[1].id = nil
-- Make sure we equip some nifty stuff instead of player's starting iron stuff
for i, d in ipairs(resolver[1]) do
d.name, d.id = nil, nil
d.ego_chance = nil
d.ignore_material_restriction = true
d.forbid_power_source = table.clone(b.not_power_source, nil, {nature=true})
d.tome_drops = data.loot_quality or "boss"
d.force_drop = (data.drop_equipment == nil) and true or data.drop_equipment
end
b[#b+1] = resolver
end
elseif resolver.__resolver == "auto_equip_filters" then
if not data.forbid_equip then
b[#b+1] = resolver
end
elseif resolver._allow_random_boss then -- explicitly allowed resolver
b[#b+1] = resolver
end
elseif k == "innate_alchemy_golem" then
b.innate_alchemy_golem = true
elseif k == "birth_create_alchemist_golem" then
b.birth_create_alchemist_golem = resolver
if instant then b:check("birth_create_alchemist_golem") end
elseif k == "soul" then
b.soul = util.bound(1 + math.ceil(data.level / 10), 1, 10) -- Does this need to scale?
elseif k == "can_tinker" then
b[k] = table.clone(resolver)
end
end
for k, resolver in pairs(mclass.copy or {}) do apply_resolvers(k, resolver) end
for k, resolver in pairs(class.copy or {}) do apply_resolvers(k, resolver) end
-- Assign a talent resolver for class starting talents (this makes them autoleveling)
local tres = nil
for k, resolver in pairs(b) do if type(resolver) == "table" and resolver.__resolver and resolver.__resolver == "talents" then tres = resolver break end end
if not tres then tres = resolvers.talents{} b[#b+1] = tres end
for tid, v in pairs(class.talents or {}) do
local t = b:getTalentFromId(tid)
if not t.no_npc_use and not t.no_npc_autolevel and (not t.random_boss_rarity or rng.chance(t.random_boss_rarity)) and not (t.rnd_boss_restrict and t.rnd_boss_restrict(b, t, data) ) then
local max = (t.points == 1) and 1 or math.ceil(t.points * 1.2)
local step = max / 50
tres[1][tid] = v + math.ceil(step * data.level)
end
end
-- Select additional talents from the class
local known_types = {}
for tt, d in pairs(b.talents_types) do
known_types[tt] = b:numberKnownTalent(tt)
end
local list = {}
for _, t in pairs(b.talents_def) do
if b.talents_types[t.type[1]] then
if t.no_npc_use or t.not_on_random_boss then
known_types[t.type[1]] = known_types[t.type[1]] + 1 -- allows higher tier talents to be learnt
else
local ok = true
if t.rnd_boss_restrict and t.rnd_boss_restrict(b, t, data) then
ok = false
print("[applyRandomClass] Random boss forbade talent because of special talent restriction", t.name, t.id, data.level)
end
if data.check_talents_level and rawget(t, 'require') then
local req = t.require
if type(req) == "function" then req = req(b, t) end
if req and req.level and util.getval(req.level, 1) > math.ceil(data.level/2) then
print("[applyRandomClass] Random boss forbade talent because of level", t.name, t.id, data.level)
ok = false
end
end
if t.type[1]:find("/other$") then
print("[applyRandomClass] Random boss forbase talent because category /other", t.name, t.id, t.type[1])
ok = false
end
if ok then list[t.id] = true end
end
end
end
local nb = 4 + 0.38*data.level^.75 -- = 11 at level 50
nb = math.max(rng.range(math.floor(nb * 0.7), math.ceil(nb * 1.3)), 1)
print("Adding "..nb.." random class talents to boss")
local count, fails = 0, 0
while count < nb do
local tid = rng.tableIndex(list, b.learn_tids)
if not tid or fails > nb * 5 then break end
local t = b:getTalentFromId(tid)
if t then
if t.type[2] and known_types[t.type[1]] < t.type[2] - 1 then -- not enough of talents of type
fails = fails + 1
else -- ok to add
count = count + 1
local max = (t.points == 1) and 1 or math.ceil(t.points * 1.2)
local step = max / 50
local lev = math.ceil(step * data.level)
print(count, " * talent:", tid, lev)
if instant then -- affected by game difficulty settings
if b:getTalentLevelRaw(tid) < lev then b:learnTalent(tid, true, lev - b:getTalentLevelRaw(tid)) end
if t.mode == "sustained" and data.auto_sustain then b:forceUseTalent(tid, {ignore_energy=true}) end
else -- applied when added to the level (unaffected by game difficulty settings)
b.learn_tids[tid] = lev
end
known_types[t.type[1]] = known_types[t.type[1]] + 1
list[tid] = nil
end
else list[tid] = nil
end
end
print(" ** Finished adding", count, "of", nb, "random class talents")
return true
end
-- add a full set of inventories if needed
if data.update_body then
b.body = type(data.update_body) == "table" and data.update_body or { INVEN = 1000, QS_MAINHAND = 1, QS_OFFHAND = 1, MAINHAND = 1, OFFHAND = 1, FINGER = 2, NECK = 1, LITE = 1, BODY = 1, HEAD = 1, CLOAK = 1, HANDS = 1, BELT = 1, FEET = 1, TOOL = 1, QUIVER = 1, QS_QUIVER = 1 }
b:initBody()
end
-- Select classes
local classes = Birther.birth_descriptor_def.subclass
if data.force_classes then -- apply forced classes first, by index, then in random order
local c_list = table.clone(data.force_classes)
local force_classes = {}
for i, c_name in ipairs(c_list) do
force_classes[i] = c_list[i]
c_list[i] = nil
end
table.append(force_classes, table.shuffle(table.keys(c_list)))
for i, c_name in ipairs(force_classes) do
if classes[c_name] then
apply_class(table.clone(classes[c_name], true))
else
print(" ###Forced class", c_name, "NOT DEFINED###")
end
end
end
local list = {}
for name, cdata in ipairs(classes) do
if not cdata.not_on_random_boss and (not cdata.random_rarity or rng.chance(cdata.random_rarity)) and (not data.class_filter or data.class_filter(cdata, b)) then list[#list+1] = cdata
end
end
local to_apply = data.nb_classes or 2
while to_apply > 0 do
local c = rng.tableRemove(list)
if not c then break end --repeat attempts until list is exhausted
if data.no_class_restrictions or self:checkPowers(b, c) then -- recheck power restricts here to account for any previously picked classes
if apply_class(table.clone(c, true)) then to_apply = to_apply - 1 end
else
print(" * class", c.name, " rejected due to power source")
end
end
if data.spend_points then -- spend any remaining unspent stat points
repeat
local last_stats = b.unused_stats
engine.Autolevel:autoLevel(b)
until last_stats == b.unused_stats or b.unused_stats <= 0
end
end
--- Creates a random Boss (or elite) actor (pre-NPC autolevel method)
-- @param base = base actor to add classes/talents to
-- calls _M:applyRandomClass(b, data, instant) to add classes, talents, and equipment based on class descriptors
-- handles data.nb_classes, data.force_classes, data.class_filter, ...
-- optional parameters:
-- @param data.init = function(data, b) to run before generation
-- @param data.level = minimum level range for actor generation <1>
-- @param data.rank = rank <3.5-4>
-- @param data.life_rating = function(b.life_rating) <1.7 * base.life_rating + 4-9>
-- @param data.resources_boost = multiplier for maximum resource pool sizes <3>
-- @param data.talent_cds_factor = multiplier for all talent cooldowns <1>
-- @param data.ai = ai_type <"tactical" if rank>3 or base.ai>
-- @param data.ai_tactic = tactical weights table for the tactical ai <nil - generated based on talents>
-- @param data.no_loot_randart set true to not drop a randart <nil>
-- @param data.on_die set true to run base.rng_boss_on_die and base.rng_boss_on_die_custom on death <nil>
-- @param data.name_scheme <randart_name_rules.default>
-- @param data.post = function(b, data) to run last to finish generation
function _M:createRandomBoss(base, data)
local b = base:clone()
data = data or {level=1}
if data.init then data.init(data, b) end
data.nb_classes = data.nb_classes or 2
if b.rnd_boss_init then b.rnd_boss_init(b, data) end -- Used for problematic randboss bases, banning classes/talents, ...
------------------------------------------------------------
-- Basic stuff, name, rank, ...
------------------------------------------------------------
local ngd, name
if base.random_name_def then
ngd = NameGenerator2.new("/data/languages/names/"..base.random_name_def:gsub("#sex#", base.female and "female" or "male")..".txt")
name = ngd:generate(nil, base.random_name_min_syllables, base.random_name_max_syllables)
else
ngd = NameGenerator.new(randart_name_rules.default)
name = ngd:generate()
end
if data.name_scheme then
b.name = data.name_scheme:gsub("#rng#", name):gsub("#base#", b.name)
else
b.name = name.." the "..b.name
end
print("[createRandomBoss] Creating random boss ", b.name, data.level, "level", data.nb_classes, "classes")
if data.force_classes then print(" * force_classes:", (string.fromTable(data.force_classes))) end
b.unique = b.name
b.randboss = true
local boss_id = "RND_BOSS_"..b.name:upper():gsub("[^A-Z]", "_")
b.define_as = boss_id
b.color = colors.VIOLET
b.rank = data.rank or (rng.percent(30) and 4 or 3.5) -- 30% chance of boss rank
b.level_range[1] = data.level
b.fixed_rating = true
if data.life_rating then
b.life_rating = data.life_rating(b.life_rating)
else
b.life_rating = b.life_rating * 1.7 + rng.range(4, 9)
end
b.max_life = b.max_life or 150
b.max_inscriptions = 5 -- Note: This usually won't add inscriptions to NPC bases without them
-- Avoid cloning randbosses
if b.can_multiply or b.clone_on_hit then
b.can_multiply = nil
b.clone_on_hit = nil
end
-- Force resolving some stuff
if type(b.max_life) == "table" and b.max_life.__resolver then b.max_life = resolvers.calc[b.max_life.__resolver](b.max_life, b, b, b, "max_life", {}) end
-- All bosses have all body parts .. yes snake bosses can use archery and so on ..
-- This is to prevent them from having unusable talents
b.inven = {}
b.body = { INVEN = 1000, QS_MAINHAND = 1, QS_OFFHAND = 1, MAINHAND = 1, OFFHAND = 1, FINGER = 2, NECK = 1, LITE = 1, BODY = 1, HEAD = 1, CLOAK = 1, HANDS = 1, BELT = 1, FEET = 1, TOOL = 1, QUIVER = 1, QS_QUIVER = 1 }
b:initBody()
-- don't auto equip inventory if forbidden
if data.forbid_equip then b.inven[b.INVEN_INVEN]._no_equip_objects = true end
b:resolve()
-- Start with sustains sustained
b[#b+1] = resolvers.sustains_at_birth()
-- Leveling stats
b.autolevel = "random_boss"
b.auto_stats = {}
-- Randbosses resemble players so they should use the same resist cap rules
-- This is particularly important because at high levels boss ranks get a lot of free resist all
b.resists_cap = { all = 70 }
b.move_others = true
b.open_door = true
-- Update default equipment, if any, to "boss" levels
for k, resolver in ipairs(b) do
if type(resolver) == "table" and resolver.__resolver == "equip" then
resolver[1].id = nil
for i, d in ipairs(resolver[1]) do
d.name, d.id = nil, nil
d.ego_chance = nil
d.ignore_material_restriction = true
d.forbid_power_source = b.not_power_source
d.tome_drops = data.loot_quality or "boss"
d.force_drop = (data.drop_equipment == nil) and true or data.drop_equipment
end
end
end
-- Boss worthy drops
b[#b+1] = resolvers.drops{chance=100, nb=data.loot_quantity or 3, {tome_drops=data.loot_quality or "boss"} }
if not data.no_loot_randart then b[#b+1] = resolvers.drop_randart{} end
-- On die
if data.on_die then
b.rng_boss_on_die = b.on_die
b.rng_boss_on_die_custom = data.on_die
b.on_die = function(self, src)
self:check("rng_boss_on_die_custom", src)
self:check("rng_boss_on_die", src)
end
end
------------------------------------------------------------
-- Apply talents from classes
------------------------------------------------------------
self:applyRandomClass(b, data)
b.rnd_boss_on_added_to_level = b.on_added_to_level
b.on_added_final = data.rnd_boss_final_adjust
b._rndboss_resources_boost = data.resources_boost or 3
b._rndboss_talent_cds = data.talent_cds_factor
b.on_added_to_level = function(self, ...)
self:check("birth_create_alchemist_golem")
self:check("rnd_boss_on_added_to_level", ...)
self.rnd_boss_on_added_to_level = nil
self.on_added_to_level = nil
-- Increase talent cds
if self._rndboss_talent_cds then
local fact = self._rndboss_talent_cds
for tid, _ in pairs(self.talents) do
local t = self:getTalentFromId(tid)
if t.mode ~= "passive" then
local bcd = self:getTalentCooldown(t) or 0
self.talent_cd_reduction[tid] = (self.talent_cd_reduction[tid] or 0) - math.ceil(bcd * (fact - 1))
end
end
end
-- Enhance resource pools (cheat a bit with recovery)
for res, res_def in ipairs(self.resources_def) do
if res_def.randomboss_enhanced then
local capacity
if self[res_def.minname] and self[res_def.maxname] then -- expand capacity
capacity = (self[res_def.maxname] - self[res_def.minname]) * self._rndboss_resources_boost
end
if res_def.invert_values then
if capacity then self[res_def.minname] = self[res_def.maxname] - capacity end
self[res_def.regen_prop] = self[res_def.regen_prop] - (res_def.min and res_def.max and (res_def.max-res_def.min)*.01 or 1) * self._rndboss_resources_boost
else
if capacity then self[res_def.maxname] = self[res_def.minname] + capacity end
self[res_def.regen_prop] = self[res_def.regen_prop] + (res_def.min and res_def.max and (res_def.max-res_def.min)*.01 or 1) * self._rndboss_resources_boost
end
end
end
self:resetToFull()
end
-- Update AI
if data.ai then b.ai = data.ai
else b.ai = (b.rank > 3) and "tactical" or b.ai
end
b.ai_state = { talent_in=1 }
if not b.no_overwrite_ai_move then
b.ai_state.ai_move = "move_astar_advanced"
end
if data.ai_tactic then
b.ai_tactic = data.ai_tactic
else
b[#b+1] = resolvers.talented_ai_tactic() --calculate ai_tactic table based on talents
end
-- Anything else
if data.post then data.post(b, data) end
return b, boss_id
end
--- Add one or more character classes to an actor, updating stats, talents, and equipment,
-- Updates autoleveling data so that class skills are advanced with level
-- @see Actor:levelupClass
-- @param b = actor(boss) to update
-- @param data = optional parameters:
-- @field data.update_body a table of inventories to add, set true to add a full suite of inventories
-- @field data.start_level: actor level to being leveling in the class(es) <1>
-- @field data.level_rate: level of character class as % of actor level <100>
-- @field data.force_classes = specific subclasses to apply first, ignoring restrictions
-- {"Rogue" <=={Rogue = 100}>, {Necromancer = 75}, Corruptor = true <==100>, Bulwark = 50, ...}
-- applied in order of numerical index, then randomly, numbers are the specified level_rate for each class
-- @field data.nb_classes = random classes to add (in addition to any forced classes) <2>
-- fractional classes are applied first with reduced level_rate
-- @field data.class_filter = function(cdata, b) that must return true for any class picked.
-- (cdata, b = subclass definition in engine.Birther.birth_descriptor_def.subclass, boss (before classes are applied))
-- @field data.no_class_restrictions set true to skip class compatibility checks <nil>
-- @field data.autolevel = autolevel scheme to use for stats (set false to keep current) <"random_boss">
-- @field data.spend_points = spend any unspent stat points (after adding all classes)
-- @field data.add_trees = {["talent tree name 1"]=true/mastery bonus, ["talent tree name 2"]=true/mastery bonus, ..} additional talent trees to learn
-- @field data.check_talents_level set true to enforce talent level restrictions based on class level <nil>
-- @field data.auto_sustain set true to activate sustained talents at birth <nil>
-- @field data.forbid_equip set true to ignore class equipment resolvers (and filters) or equip inventory <nil>
-- @field data.loot_quality = drop table to use for equipment <"boss">
-- @field data.drop_equipment set true to force dropping of equipment <nil>
-- @field data.calculate_tactical: set true to recalculate ai_tactic weights based on learned talents <nil>
-- @param instant set true to force instant learning of talents and generating golem <nil>
function _M:applyRandomClassNew(b, data, instant)
if not data.level then data.level = b.level end -- use the level specified if needed
if data.calculate_tactical then self.ai_calculate_tactical = true end
------------------------------------------------------------
-- Apply talents from classes
------------------------------------------------------------
-- Apply a class
local Birther = require "engine.Birther"
local function apply_class(class, level_rate)
local mclasses = Birther.birth_descriptor_def.class
local mclass = nil
for name, data in pairs(mclasses) do
if data.descriptor_choices and data.descriptor_choices.subclass and data.descriptor_choices.subclass[class.name] then mclass = data break end
end
if not mclass then
print("[applyRandomClass] ### ABORTING ###", b.uid, b.name, "No main class type for", class.name)
return
end
print("[applyRandomClass]", b.uid, b.name, "Adding class", class.name, mclass.name, "level_rate", level_rate)
-- Add starting equipment and update filters as needed
local apply_resolvers = function(k, resolver)
if type(resolver) == "table" and resolver.__resolver then
if resolver.__resolver == "equip" then
if not data.forbid_equip then
resolver[1].id = nil
-- Make sure we equip some nifty stuff instead of player's starting iron stuff
for i, d in ipairs(resolver[1]) do
d.name, d.id = nil, nil
d.ego_chance = nil
d.ignore_material_restriction = true
d.forbid_power_source = table.clone(b.not_power_source, nil, {nature=true})
d.tome_drops = data.loot_quality or "boss"
d.force_drop = (data.drop_equipment == nil) and true or data.drop_equipment
end
b[#b+1] = resolver
end
elseif resolver.__resolver == "auto_equip_filters" then
if not data.forbid_equip then
b[#b+1] = resolver
end
elseif resolver._allow_random_boss then -- explicitly allowed resolver
b[#b+1] = resolver
end
elseif k == "innate_alchemy_golem" then
b.innate_alchemy_golem = true
elseif k == "birth_create_alchemist_golem" then
b.birth_create_alchemist_golem = resolver
if instant then b:check("birth_create_alchemist_golem") end
elseif k == "soul" then
b.soul = util.bound(1 + math.ceil(data.level / 10), 1, 10) -- Does this need to scale?
elseif k == "can_tinker" then
b[k] = table.clone(resolver)
end
end
for k, resolver in pairs(mclass.copy or {}) do apply_resolvers(k, resolver) end
for k, resolver in pairs(class.copy or {}) do apply_resolvers(k, resolver) end
b.auto_classes = b.auto_classes or {}
local c_data = {
class = class.name,
ttypes = data.add_trees, -- adds specified talent trees
spend_points = data.spend_points,
start_level = data.start_level,
level_rate = level_rate or 100,
auto_sustain = data.auto_sustain,
check_talents_level = data.check_talents_level,
level_by_class = data.level_by_class,
calculate_tactical = data.calculate_tactical,
}
table.insert(b.auto_classes, c_data)
return true
end
-- add a full set of inventories if needed
if data.update_body then
b.body = type(data.update_body) == "table" and data.update_body or { INVEN = 1000, QS_MAINHAND = 1, QS_OFFHAND = 1, MAINHAND = 1, OFFHAND = 1, FINGER = 2, NECK = 1, LITE = 1, BODY = 1, HEAD = 1, CLOAK = 1, HANDS = 1, BELT = 1, FEET = 1, TOOL = 1, QUIVER = 1, QS_QUIVER = 1 }
b:initBody()
end
-- Select classes
local classes = Birther.birth_descriptor_def.subclass
-- apply forced classes first, by index, then in random order, extracting specified or implied level rates
if data.force_classes then
local c_list = table.clone(data.force_classes, true)
local force_classes = {}
for i, c_name in ipairs(c_list) do
if type(c_name) == "table" then
force_classes[i] = c_list[i]
else
force_classes[i] = {[c_name]=data.level_rate or 100} -- default 100% level_rate
end
c_list[i] = nil
end
local rng_fc = {}
for c_name, lr in pairs(c_list) do
table.insert(rng_fc, {[c_name]=(type(lr) == "number" and lr or data.level_rate or 100)})
end
table.append(force_classes, table.shuffle(rng_fc))
for i, cl in ipairs(force_classes) do
local c_name, lr = next(cl)
if classes[c_name] then
apply_class(table.clone(classes[c_name], true), lr)
else
print(" ###Forced class", c_name, "NOT DEFINED###")
end
end
end
local list = {}
for name, cdata in ipairs(classes) do
if not cdata.not_on_random_boss and (not cdata.random_rarity or rng.chance(cdata.random_rarity)) and (not data.class_filter or data.class_filter(cdata, b)) then list[#list+1] = cdata
end
end
-- apply random classes
local to_apply = data.nb_classes or 1.5 -- 1.5 is one primary class and one secondary class @ 50% stats/talents
print("[applyRandomClass] applying", to_apply, "classes at", data.level_rate, "%%")
while to_apply > 0 do
local c = rng.tableRemove(list)
if not c then break end --repeat attempts until list is exhausted
if data.no_class_restrictions or self:checkPowers(b, c) then -- recheck power restricts here to account for any previously picked classes
-- if nb_classes is not an integer, apply partial classes first so that resolvers for later classes take precedence
local lr = to_apply - math.floor(to_apply)
lr = lr == 0 and 1 or lr
if apply_class(table.clone(