-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEBL_compiler.py
1382 lines (1213 loc) · 46.9 KB
/
EBL_compiler.py
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
import entity_templates
import eternalevents
from pathlib import Path
import json
import hashlib
from eternalevents import is_number_or_keyword
from eternaltools import oodle, entity_tools
from entity_templates import EntityTemplate
import entities_parser as parser
import ebl_grammar
import compiler_constants as cc
from compiler_constants import ANIM_OFFSETS_FILE
from copy import deepcopy
import datetime
import os
import pyperclip3
from textwrap import indent
from dataclasses import dataclass
from typing import List, Union, Tuple
import re
import time
import pprint
from ebl_grammar import EblTypeError
from entities_parser import EntitiesSyntaxError
run_count = 0
horde_index = 0
def reset_all():
global run_count
run_count += 1
global ebl_cache
global new_ebl_cache
global variables
global decorator_changes
global decorator_entity_names
global mod_entity_idx
global Settings
global spawn_target_hashes
global horde_index
mod_entity_idx = 0
horde_index = 0
variables = {}
ebl_cache = {}
new_ebl_cache = {}
decorator_changes = []
decorator_entity_names = {}
spawn_target_hashes = []
Settings = {}
ignored_entities = []
def cache_result():
global ebl_cache
global new_ebl_cache
def decorator(func):
def new_func(*args):
keystr = (
str(args)
+ func.__name__
+ str(variables)
+ str(ignored_entity_names)
+ str(Settings)
)
key = hashlib.md5(keystr.encode()).hexdigest()
try:
test_keys = ebl_cache.keys()
except NameError:
return func(*args)
if key in ebl_cache:
# print("found cached result!")
new_ebl_cache[key] = ebl_cache[key]
return ebl_cache[key]
result = func(*args)
new_ebl_cache[key] = result
return result
return new_func
return decorator
# EBL = Eternal Builder Language, describes changes to .entities files
ebl = ebl_grammar.NodeVisitor()
ebl.grammar = ebl_grammar.grammar
blacklist_entities = []
variables = {}
Settings = {}
spawn_target_hashes = []
templates = entity_templates.BUILTIN_TEMPLATES
decorator_changes = []
decorator_entity_names = {}
ignored_entities = []
ignored_entity_names = []
debug_vars = False
worker_object = None
do_verbose_logging = True
def ui_log(s):
try:
worker_object.worker_log(str(s))
except Exception:
print(s)
def ui_log_verbose(s):
if do_verbose_logging:
ui_log(s)
def debug_print(string):
if debug_vars:
ui_log(string)
@dataclass
class Assignment:
name: str
value: str
# syntax is object.func(value)
@dataclass
class EntityEdit:
object: str
func: str
value: list
def parse_event(event: str) -> Tuple[str, list]:
event, _ = event.replace("\n", "").split(")", 1)
name, args = event.split("(", 1)
args = re.findall(r"([^(,)]+)(?!.*\()", args)
args = [arg.strip() for arg in args]
return name, args
# these are not technically variables, but go off I guess
def add_variable(varname, value):
if varname in variables:
debug_print(f"Modified macro {varname} = {value}")
else:
ui_log_verbose(f"Added macro {varname} = {value}")
value = str(value)
ignore_quotes = "+" not in str(value)
variables[varname] = concat_strings(format_args(value), ignore_quotes)
debug_print(
f"""Concatenated strings in assignment {varname} = {variables[varname]}"""
)
return True
def list_entitydefs(entitydefs: list) -> str:
res = f"num = {len(entitydefs)};\n"
for i, name in enumerate(entitydefs):
res += f'item[{i}] = {{\n\tname = "{name}";\n}}\n'
return res
def list_targets(entitydefs: list) -> str:
res = f"num = {len(entitydefs)};\n"
for i, name in enumerate(entitydefs):
res += f'item[{i}] = "{name}";\n'
return res
def str_to_class(classname):
return getattr(eternalevents, classname)
def get_event_args(event: eternalevents.EternalEvent):
return [arg for arg in event.__dict__.values()]
LINE_PATTERN = re.compile(r"//(.*)(?=[\r\n]+)")
MULTILINE_PATTERN = re.compile(r"/\*.*?\*/", flags=re.DOTALL)
def strip_comments(s):
s += "\n"
s = re.sub(MULTILINE_PATTERN, "", s)
return re.sub(LINE_PATTERN, "", s).strip()
def split_ebl_at_headers(filename) -> list:
"""
Splits an EBL file into segments at headers
returns a list of tuples with EBL code and encounter name
Also strips comments!
:param filename:
:return:
"""
with open(filename) as fp:
segments = re.split(
cc.EBL_HEADERS_REGEX, strip_comments(fp.read()), flags=re.MULTILINE
)
if segments[0].startswith("SETTINGS"):
ui_log("SETTINGS found!")
global Settings
for line in segments[0].splitlines():
if line == "SETTINGS":
continue
line = line.strip()
if line:
if "=" not in line:
continue
setting, value = line.split("=", 1)
Settings[setting.strip()] = value.strip()
ui_log(line)
else:
ui_log("No SETTINGS found")
res = []
# yield tuples containing name, header command, and body text
for cmd, body in zip(*[iter(segments[1:])] * 2):
cmd = cmd.strip()
name = body.split("\n")[0].strip()
if not name:
if cmd == "INIT":
name = None
else:
raise EblTypeError(f"No entity name specified in header {cmd}")
body = "\n".join(body.split("\n")[1:])
res += [(name, (cmd, body))]
modified_segments = res.copy()
for key, val in res:
if val[0] == "IMPORT":
try:
with open(key) as fp:
pass
except FileNotFoundError:
ui_log(f"WARNING: Imported file {key} not found!")
return []
modified_segments = split_ebl_at_headers(key) + modified_segments
ui_log(f"Imported {key}")
res = modified_segments
return res
def format_args(args, arg_count=-1) -> Union[list, str]:
"""Handles variables and fills in missing arguments"""
args = args if isinstance(args, list) else [args]
for idx, arg in enumerate(args):
if isinstance(arg, str):
args[idx] = ""
arg = arg.replace(cc.SPACE_CHAR, cc.SPACE_CHAR + " ").split()
for word in arg:
if word.endswith(cc.SPACE_CHAR):
suffix = ""
else:
suffix = " "
old_word = word
word = word.replace(cc.SPACE_CHAR, "")
if word in cc.ENCOUNTER_SPAWN_NAMES:
args[idx] += "ENCOUNTER_SPAWN_" + word + suffix
elif word in cc.ENCOUNTER_SPAWN_ALIASES:
args[idx] += (
"ENCOUNTER_SPAWN_" + cc.ENCOUNTER_SPAWN_ALIASES[word] + suffix
)
else:
args[idx] += old_word + suffix
args[idx] = args[idx].strip()
if arg is None:
args[idx] = ""
while len(args) < arg_count:
args += [""]
return args[0] if arg_count == -1 else args
# TODO: use the structural pattern matching feature when it comes out lol
def create_events(data) -> list:
"""
Consumes parsed EBL and generates a list of EternalEvents
we do a little recursion
"""
if isinstance(data, list):
output = []
for item in data:
event = create_events(item)
output += event
return output
if isinstance(data, dict):
if "variable" in data:
return [Assignment(data["variable"], data["value"])]
if "function" in data:
return [EntityEdit(data["object"], data["function"], data["value"])]
if data["event"] == "waitForBlock":
event_count = 0
for sublist in data["args"]:
for _ in sublist[0]["args"]:
event_count += 1
waitevent = {
"event": "waitMulitpleConditions",
"args": [event_count, cc.WAITFOR_KEYWORDS[data["keyword"]], "false"],
}
return create_events([waitevent] + data["args"])
if data["event"] == "waitFor":
return create_events(data["args"])
if data["event"] in eternalevents.ebl_to_event:
cls_name, arg_count = eternalevents.ebl_to_event[data["event"]]
event_cls = str_to_class(cls_name)
else:
raise EblTypeError(f"""Undefined event {data["event"]}!""")
# data is event
# Assume nested argument list means a list of parameters
args_list = data["args"]
if any(isinstance(item, list) for item in args_list):
result = []
for args in args_list:
if "decorator" in data and data["decorator"]:
args = add_decorator_command(data["decorator"], event_cls(*args))
args = format_args(args, arg_count)
result += [event_cls(*args)]
return result
else:
if "decorator" in data and data["decorator"]:
args_list = add_decorator_command(
data["decorator"], event_cls(*args_list)
)
args_list = format_args(args_list, arg_count)
event_cls = event_cls(*args_list)
return [event_cls]
return data
mod_entity_idx = 0
def add_decorator_command(
decorator: str, event_cls: eternalevents.EternalEvent
) -> list:
"""
Adds a decorator command from an event
returns a list of modified args based on the event
:param decorator:
:param event_cls:
:return:
"""
cmds = decorator
modified_args = get_event_args(event_cls)
original_event = deepcopy(event_cls)
global decorator_changes
global mod_entity_idx
cmd_list = [cmd.strip() for cmd in cmds.split(";")]
for cmd in cmd_list:
cmd_name, _ = cmd.split(" ", 1) if " " in cmd else (cmd.strip(), "")
is_possessed = False
# Decide what to do based on event type, then decorator type
event_cls_name = type(event_cls).__name__
if event_cls_name in eternalevents.SPAWN_TARGET_EVENTS:
if event_cls_name == "SpawnSingleAI":
spawn_type = format_args(event_cls.spawnType)
elif event_cls_name == "SpawnArchvile":
spawn_type = "ENCOUNTER_SPAWN_ARCHVILE"
elif event_cls_name == "SpawnPossessedAI":
spawn_type = format_args(event_cls.ai_spawnType)
is_possessed = True
spawn_type = spawn_type.removeprefix("ENCOUNTER_SPAWN_")
if cmd_name == "anim":
if event_cls_name not in eternalevents.SPAWN_TARGET_EVENTS:
raise EntitiesSyntaxError(
f"Cannot apply anim to event call {event_cls_name}"
)
old_spawntarget = concat_strings(
original_event.spawnTarget, is_expression=True
)
new_entity_name = f"eblmod_spawn_target_{mod_entity_idx}"
event_cls.spawnTarget = new_entity_name
if is_possessed:
event_cls.ai_spawnTarget = new_entity_name
decorator_changes.append(
(
old_spawntarget,
cmd + " " + spawn_type,
new_entity_name,
)
)
elif cmd_name == "portal":
pass
else:
ui_log(f"WARNING: event {type(event_cls).__name__} has no associated tags")
return modified_args
mod_entity_idx += 1
modified_args = get_event_args(event_cls)
return modified_args
def apply_decorator_command(
entity: str,
cmd: str,
new_entity_name: str,
) -> Tuple[str, bool, bool]:
"""
Returns a copy of the given entity with decorator commands applied
:param entity:
:param cmd:
:param new_entity_name:
:return:
"""
def sign(num):
return 1 if num > 0 else -1
do_not_modify = False
delete_original = False
if new_entity_name in decorator_entity_names:
delete_original = True
entity = decorator_entity_names[new_entity_name]
# print(f"existing decorator entity found: {new_entity_name}")
parsed_entity = parser.parse_entity(entity)
entitydef = ""
for key in parsed_entity:
if key.startswith("entityDef"):
entitydef = key
ui_log_verbose(f"Applying '{cmd}' to '{entitydef.removeprefix('entityDef ')}'")
# original_name = entitydef.removeprefix("entityDef ")
if not entitydef:
raise EntitiesSyntaxError("No entityDef component!")
if " " not in cmd:
cmd_name = cmd.strip()
args = []
else:
cmd_name, args = cmd.split(" ", 1)
args = [
concat_strings(arg.strip(), is_expression=True)
for arg in args.split()
if arg.strip()
]
if cmd_name == "anim":
anim_name, spawn_type = args
demon_name = cc.NAME_TO_ANIMWEB[spawn_type]
traversal_s = (
"traversals" if spawn_type in cc.TRAVERSALS_ENEMIES else "traversal"
)
traversal_path = (
f"animweb/characters/monsters/{demon_name}/{traversal_s}/" + anim_name
)
if demon_name == "cacodemon" or demon_name == "painelemental":
traversal_path = (
f"animweb/characters/monsters/{demon_name}/spawn/" + anim_name
)
if anim_name == "none":
traversal_path = ""
elif anim_name == "sneaky_spawn":
traversal_path = (
"animweb/characters/monsters/zombie_tier_1/spawn/sneaky_spawn_01"
)
elif anim_name not in cc.ANIM_TO_OFFSET:
traversal_path = f"animweb/characters/monsters/{demon_name}/" + anim_name
parsed_entity[entitydef]["edit"]["spawnEditable"]["spawnAnim"] = traversal_path
if anim_name == "none":
parsed_entity[entitydef]["edit"]["spawnEditable"][
"aiStateOverride"
] = "AIOVERRIDE_FORCE_AWARENESS_OF_PLAYER"
else:
parsed_entity[entitydef]["edit"]["spawnEditable"][
"aiStateOverride"
] = "AIOVERRIDE_PLAY_ENTRANCE_ANIMATION"
try:
x_off, y_off = cc.ANIM_TO_OFFSET[anim_name]
except KeyError:
ui_log(f"WARNING: anim {anim_name} not recognized")
x_off, y_off = cc.ANIM_TO_OFFSET.get(anim_name, (0, 0))
x_off, y_off = -x_off, -y_off
x, y, z = (
parsed_entity[entitydef]["edit"]["spawnPosition"].get("x", 0),
parsed_entity[entitydef]["edit"]["spawnPosition"].get("y", 0),
parsed_entity[entitydef]["edit"]["spawnPosition"].get("z", 0),
)
try:
forward_cos = parsed_entity[entitydef]["edit"]["spawnOrientation"]["mat"][
"mat[0]"
]["x"]
forward_sin = parsed_entity[entitydef]["edit"]["spawnOrientation"]["mat"][
"mat[0]"
]["y"]
except KeyError:
forward_cos = 1
forward_sin = 0
demon_width, ledge_offset = cc.NAME_TO_HORIZONTAL_OFFSET[spawn_type]
if anim_name not in cc.ANIM_TO_OFFSET:
demon_width = 0
if anim_name == "none":
demon_width = 0
if "ledge" in anim_name:
demon_width += ledge_offset
dx = forward_cos * sign(x_off) * (abs(x_off) + demon_width)
dy = y_off
dz = forward_sin * sign(x_off) * (abs(x_off) + demon_width)
offset_scalar_x = 1 / 100
offset_scalar_y = 1 / 100
# Z is up
parsed_entity[entitydef]["edit"]["spawnPosition"]["x"] = x + (
dx * offset_scalar_x
)
parsed_entity[entitydef]["edit"]["spawnPosition"]["y"] = y + (
dz * offset_scalar_x
)
parsed_entity[entitydef]["edit"]["spawnPosition"]["z"] = z + (
dy * offset_scalar_y
)
# change name
parsed_entity[f"entityDef {new_entity_name}"] = parsed_entity.pop(entitydef)
else:
ui_log(f"ERROR: Tag {cmd_name} is not recognized")
if not delete_original:
decorator_entity_names[new_entity_name] = entity_tools.generate_entity(
parsed_entity
)
return entity_tools.generate_entity(parsed_entity), do_not_modify, delete_original
def all_idai2s(*, dlc_level=2) -> List[str]:
res = ""
with open("idAI2_base.txt", "r") as fp_base:
ui_log("Added base game idAI2s")
res += fp_base.read() + "\n\n"
if dlc_level >= 2:
with open("idAI2_dlc2.txt") as fp_dlc2:
res += fp_dlc2.read() + "\n\n"
ui_log("Added DLC2 idAI2s")
if dlc_level >= 1:
with open("idAI2_dlc1.txt") as fp_dlc1:
res += fp_dlc1.read() + "\n\n"
ui_log("Added DLC1 idAI2s")
segments = re.split(r"^entity {", res, flags=re.MULTILINE)
result = [segments[0]] + [
"entity {" + re.sub(r"//.*$", "", segment) for segment in segments[1:]
]
return result
def concat_strings(s, is_expression=False):
"""Warning: hacky
Manipulates string by:
a) replacing variable names with corresponding values
b) handling the + operator and concatenating strings
:param s:
:param is_expression: whether all of s must be matched if there is no + in string
:return modified_string:
"""
def rreplace(_s: str, old, new, occurrence=0):
li = _s.rsplit(old, occurrence)
return new.join(li)
items = variables.items()
sorted_variables = sorted(items, key=lambda x: len(x[0]), reverse=True)
if "+" not in s:
for var, val in sorted_variables:
if is_expression: # only replace entire expression if matched
if var == s.strip():
s = s.replace(f"{var}", str(val))
break
else: # replace all instances of matches in quotes
if not is_number_or_keyword(val):
val = f'"{val}"'
s = s.replace(f'"{var}"', str(val))
return s.replace(cc.SPACE_CHAR, " ").replace(cc.LITERAL_CHAR, "")
result = ""
segments = s.split("+")
for idx, seg in enumerate(segments):
seg = seg.lstrip() if idx > 0 else seg
seg = seg.rstrip() if idx < len(segments) - 1 else seg
potential_matches = re.findall(r"[$^\w]+", seg)
first_match = potential_matches[0] if idx > 0 else None
last_match = potential_matches[-1] if idx < len(segments) - 1 else None
for j, match in enumerate([first_match, last_match]):
if not match:
continue
for var, val in sorted_variables:
if len(var) < len(match.strip()):
continue
if match.strip() == var:
val = format_args(val)
if j == 0:
seg = seg.replace(match, str(val), 1)
else:
seg = rreplace(seg, match, str(val), 1)
debug_print(
f"matched variable '{match}' and substituted '{str(val)}'"
)
debug_print(f"seg is now '{seg}'")
result += seg
return result.replace(cc.SPACE_CHAR, " ").replace(cc.LITERAL_CHAR, "")
@cache_result()
def parse_ebl(s):
return ebl.parse(s + "\n")
def compile_ebl(s, vars_only=False) -> str:
"""
Compiles EBL to encounterComponent events
:param s:
:param vars_only:
:return events:
"""
event_lists = parse_ebl(s)
events = []
if any(isinstance(item, list) for item in event_lists):
for event_list in event_lists:
new_events = create_events(event_list)
if new_events is None:
continue
events.append(new_events)
else:
events.append(create_events(event_lists))
rendered_events = []
for event_list in events:
item_index = 0
result = f"num = {len(event_list)};\n"
for event in event_list:
if isinstance(event, Assignment):
add_variable(event.name, event.value)
continue
if vars_only:
continue
event_string = concat_strings(str(event))
if isinstance(event_string, list):
print(f"{event_string=}")
result += (
f"item[{item_index}]" + " = {\n" + indent(event_string, "\t") + "}\n"
)
item_index += 1
rendered_events.append(result)
return rendered_events
@cache_result()
def replace_encounter(encounter: str, events: Union[list, str], dlc_level: int) -> str:
"""
Modifies encounter entity with list of EternalEvents
:param encounter:
:param events:
:param dlc_level:
:return new_entity_string:
"""
entity = parser.parse_entity(encounter)
entity_events = [
"{\n" + indent(events_list, "\t") + "}\n" for events_list in events
]
entitydef = ""
for key in entity:
if key.startswith("entityDef"):
entitydef = key
if not entitydef:
raise EntitiesSyntaxError("No entityDef component!")
for idx, script in enumerate(entity_events):
try:
dic = entity
for key in [
entitydef,
"edit",
"encounterComponent",
"entityEvents",
f"item[{idx}]",
]:
dic = dic.setdefault(key, {})
dic["events"] = script
dic["entity"] = entitydef.removeprefix("entityDef ")
entity[entitydef]["edit"]["aiTypeDefAssignments"] = cc.ACTORPOPULATION[
dlc_level
]
entity[entitydef]["edit"][
"combatRatingScale"
] = "COMBAT_RATING_SCALE_IGNORE"
except KeyError:
ui_log(f"ERROR: Unable to replace Script {idx} for encounter")
ui_log(entity[entitydef]["edit"])
result = entity_tools.generate_entity(entity)
return result
@cache_result()
def edit_entity_fields(name: str, base_entity: str, edits: str) -> str:
"""
Edits specific fields in the given entity
:param name:
:param base_entity:
:param edits:
:return edited_entity:
"""
entity = parser.parse_entity(base_entity.strip())
entitydef = ""
for key in entity:
if key.startswith("entityDef"):
entitydef = f"entityDef {name}"
entity[entitydef] = entity.pop(key)
break
if not entitydef:
# This should never happen when modifying a base entities file
raise EntitiesSyntaxError("No entityDef component!")
entity_edits = parse_ebl(edits)
for entity_edit in create_events(entity_edits):
# assignment or function
if type(entity_edit) is EntityEdit:
function_name = entity_edit.func
values = entity_edit.value
path = entity_edit.object
elif type(entity_edit) is Assignment:
function_name = "set"
values = [[entity_edit.value]]
# ui_log(values)
path = entity_edit.name
else:
raise EblTypeError(
"All lines under MODIFY header must be EntityEdits or Assignments"
)
keys = path.split("/")
unique_key_index = 0
for value in values:
dic = entity[entitydef]
if function_name == "add":
if len(value) != 1:
raise EblTypeError(
f'Edit function "{function_name}" takes one argument'
)
for key in keys:
dic = dic.setdefault(key, {})
value[0] = concat_strings(value[0], is_expression=True)
dic[f"__unique_{unique_key_index}__"] = value[0]
unique_key_index += 1
if function_name == "set":
if len(value) != 1:
raise EblTypeError(
f'Edit function "{function_name}" takes one argument'
)
for key in keys[:-1]:
dic = dic.setdefault(key, {})
if isinstance(value[0], str):
modded_val, _ = EntityTemplate.modify_args(None, [value[0]])
value[0] = modded_val[0]
value[0] = concat_strings(value[0], is_expression=True)
try:
value[0] = float(value[0])
except ValueError:
pass
if value[0] in ["true", "false"]:
value[0] = True if value[0] == "true" else False
if value[0] == "NULL":
value[0] = None
try:
dic[concat_strings(keys[-1])] = value[0]
except TypeError:
raise EblTypeError(
f"value {concat_strings(keys[-1])} does not exist in entity {name}"
)
if function_name == "pop":
if len(value) != 1:
raise EblTypeError(
f'Edit function "{function_name}" takes one argument'
)
value = concat_strings(value[0], is_expression=True)
for key in keys:
if key == "":
continue
dic = dic[key]
for key, val in dic.items():
debug_print(f"Checking value '{value}' against '{val}'")
if val == value:
debug_print("Matched!")
dic.pop(key)
break
if function_name == "delete":
if len(value) != 1:
raise EblTypeError(
f'Edit function "{function_name}" takes one argument'
)
value = concat_strings(value[0], is_expression=True)
for key in keys:
if key == "":
continue
dic = dic[key]
for key, val in dic.items():
debug_print(f"Checking key '{value}' against '{key}'")
if key == value:
debug_print("Matched!")
dic.pop(key)
break
result = entity_tools.generate_entity(entity)
result += "\n"
return result
@cache_result()
def format_spawn_target(
spawn_target: str, entitydefs: List[str], current_horde_index: int
) -> Tuple[str, int]:
"""
Adds custom idAI2s and applies changes to the given spawn target
Also generates extra spawn targets depending on Settings
:param spawn_target:
:param entitydefs:
:return modified_spawn_target:
"""
try:
entity = parser.parse_entity(spawn_target)
except Exception as e:
ui_log("ERROR: couldn't parse spawn target")
ui_log(spawn_target)
return spawn_target, current_horde_index
entitydef = ""
# name = ""
for idx, key in enumerate(entity):
if key == "layers":
entity.pop("layers")
break
if idx > 1:
break
for key in entity:
if key.startswith("entityDef"):
entitydef = key
# name = entitydef.replace("entityDef", "").strip()
if not entitydef:
ui_log("ERROR: no entityDef component!")
return spawn_target, current_horde_index
entity_name = entitydef.removeprefix("entityDef ")
# exit if ignored entity
if entity_name in ignored_entity_names:
return entity_tools.generate_entity(entity), current_horde_index
# exit if spawn_target_group_filter is set and entity is not included
if (
"spawn_target_group_filter" in Settings
and entity_name not in Settings["spawn_target_group_filter"]
):
ui_log(f"{entity_name} not in spawn_target_group_filter, skipping")
return entity_tools.generate_entity(entity), current_horde_index
if entity_name.startswith("custom_"):
ui_log(f"Skipping custom spawn target {entity_name}")
return entity_tools.generate_entity(entity), current_horde_index
try:
spawn_editable = entity[entitydef]["edit"]["spawnEditable"]
except KeyError:
pass
else:
no_spawnanim = not spawn_editable["spawnAnim"]
no_traversal_override = not spawn_editable["initialTargetOverride"]
no_wander = spawn_editable["aiStateOverride"] != "AIOVERRIDE_WANDER"
no_forced_awareness = (
spawn_editable["aiStateOverride"] != "AIOVERRIDE_FORCE_AWARENESS_OF_PLAYER"
)
# no_add_targets = spawn_editable["additionalTargets"]["num"] == 0
if no_spawnanim and no_traversal_override and no_wander and no_forced_awareness:
entity[entitydef]["edit"]["spawnEditable"][
"aiStateOverride"
] = "AIOVERRIDE_TELEPORT"
if not entity_name.startswith("bounty"):
try:
entity[entitydef]["edit"]["spawnConditions"]["reuseDelaySec"] = 3
entity[entitydef]["edit"]["spawnConditions"]["minDistance"] = int(
Settings["spawn_min_distance"]
)
entity[entitydef]["edit"]["spawnConditions"][
"playerToTest"
] = "PLAYER_SP"
except KeyError:
pass
try:
entity[entitydef]["edit"]["spawnConditions"]["maxDistance"] = int(
Settings["spawn_max_distance"]
)
entity[entitydef]["edit"]["spawnConditions"][
"playerToTest"
] = "PLAYER_SP"
except KeyError:
pass
listed_targets = list_targets(entitydefs)
targets = "{\n" + indent(listed_targets, "\t") + "}\n"
entity[entitydef]["edit"]["targets"] = targets
listed_entitydefs = list_entitydefs(entitydefs)
entitydefs = "{\n" + indent(listed_entitydefs, "\t") + "}\n"
entity[entitydef]["edit"]["entityDefs"] = entitydefs
global horde_index
entity_horde = {}
if (
"add_horde_bounty_targets" in Settings
and 'class = "idTarget_Spawn_Parent";' not in spawn_target
):
entity_horde = deepcopy(entity)
entitydefs = cc.HORDE_ENTITYDEFS_NO_AIR
if (
"add_ground_spawns_only" in Settings
and Settings["add_ground_spawns_only"] == "true"
):
if "//#EBL_IS_AIR_TARGET" not in spawn_target:
entitydefs = cc.HORDE_ENTITYDEFS_NO_AIR
# entity_horde[entitydef]["edit"]["targetSpawnParent"] = "ai_encounter_spawn_group_parent_bounty_base"
current_horde_index += 1
listed_targets = list_targets(entitydefs)
targets = "{\n" + indent(listed_targets, "\t") + "}\n"
entity_horde[entitydef]["edit"]["targets"] = targets
listed_entitydefs = list_entitydefs(entitydefs)
entitydefs = "{\n" + indent(listed_entitydefs, "\t") + "}\n"
entity_horde[entitydef]["edit"]["entityDefs"] = entitydefs
entity_horde[f"entityDef bounty{horde_index}"] = entity_horde[entitydef]
del entity_horde[entitydef]
entity_coin = {}
if (
"add_coin_targets" in Settings
and 'class = "idTarget_Spawn_Parent";' not in spawn_target
):
entity_coin = deepcopy(entity)
entitydefs = cc.HORDE_COIN
if (
"add_ground_spawns_only" in Settings
and Settings["add_ground_spawns_only"] == "true"
):
if "//#EBL_IS_AIR_TARGET" not in spawn_target:
entitydefs = cc.HORDE_COIN
listed_targets = list_targets(entitydefs)
targets = "{\n" + indent(listed_targets, "\t") + "}\n"
entity_coin[entitydef]["edit"]["targets"] = targets
listed_entitydefs = list_entitydefs(entitydefs)
entitydefs = "{\n" + indent(listed_entitydefs, "\t") + "}\n"
entity_coin[entitydef]["edit"]["entityDefs"] = entitydefs
entity_coin[f"entityDef coin{horde_index}"] = entity_coin[entitydef]
del entity_coin[entitydef]
result = entity_tools.generate_entity(entity)
result_horde = entity_tools.generate_entity(entity_horde) if entity_horde else ""
result_coin = entity_tools.generate_entity(entity_coin) if entity_coin else ""
return result + result_horde + result_coin, current_horde_index
def apply_entity_changes(name, entity: str, params: tuple[str, str], dlc_level) -> str:
"""
Applies changes to entity with given parameters
:param name:
:param entity:
:param params: (command, body_text)
:param dlc_level:
:return modified_entity:
"""