-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlevel_editor.py
More file actions
5651 lines (4705 loc) · 241 KB
/
level_editor.py
File metadata and controls
5651 lines (4705 loc) · 241 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
from ursina import *
from ursina.shaders import unlit_shader, lit_with_shadows_shader, matcap_shader, triplanar_shader, normals_shader
from time import perf_counter
import csv
import builtins
import pyperclip
import inspect
class LevelEditor(Entity):
"""
LevelEditor is a comprehensive tool for managing, editing, and visualizing game scenes within a grid-based layout.
It provides tools for object manipulation (move, scale, rotate), selection, camera controls, and scene hierarchy management.
This editor is integrated into the Ursina Engine framework.
"""
def __init__(self, **kwargs):
"""
Initialize the LevelEditor with all its tools, UI, scene grid, and camera setup.
"""
super().__init__()
builtins.LEVEL_EDITOR = self # Register the global editor instance (type: ignore due to dynamic global use)
# Scene and grid setup
self.scene_folder = application.asset_folder / 'scenes'
self.scenes = [[LevelEditorScene(x, y, f'untitled_scene[{x},{y}]') for y in range(8)] for x in range(8)]
self.current_scene = None
# Visual editing grid
self.grid = Entity(
parent=self,
model=Grid(16, 16),
rotation_x=90,
scale=64,
collider='box',
color=color.white33,
enabled=False
)
self.origin_mode = 'center'
self.editor_camera = EditorCamera(parent=self, rotation_x=20, eternal=False, rotation_smoothing=0)
original_editor_camera_rotation_speed = self.editor_camera.rotation_speed
# Disable rotation when left mouse is pressed
def _update():
self.editor_camera.rotation_speed = original_editor_camera_rotation_speed * int(not mouse.left)
Entity(parent=self.editor_camera, update=_update)
# UI and visual selection setup
self.ui = Entity(parent=camera.ui, name='LEVEL_EDITOR.ui') # type: ignore
self.point_renderer = Entity(
parent=self,
model=Mesh([], mode='point', thickness=.1, render_points_in_3d=True),
texture='circle_outlined',
always_on_top=True,
unlit=True,
render_queue=1
)
# --- Dynamic scaling attributes for point_renderer ---
self.point_renderer._init_w, self.point_renderer._init_h = window.size
h = self.point_renderer._init_h or 1
self.point_renderer._base_thickness = (40 / h) * 2 # 2px, adjust as needed
self.point_renderer.model.thickness = self.point_renderer._base_thickness
# ----------------------------------------------------
# Cube outlines for selection highlighting
self.cubes = [
Entity(wireframe=True, color=color.azure, parent=self, enabled=True) for _ in range(128)
]
# UI menus
self.origin_mode_menu = ButtonGroup(['last', 'center', 'individual'], min_selection=1,
position=window.top_left + Vec2(.45, 0), parent=self.ui)
# After creating self.origin_mode_menu
self.origin_mode_menu._init_w, self.origin_mode_menu._init_h = window.size
h = self.origin_mode_menu._init_h or 1
self.origin_mode_menu._base_ui_scale = (10 / h) * 2
self.origin_mode_menu.scale = self.origin_mode_menu._base_ui_scale
def _origin_mode_menu_update():
cur_w, _ = window.size
ratio = cur_w / (self.origin_mode_menu._init_w or cur_w)
self.origin_mode_menu.scale = self.origin_mode_menu._base_ui_scale * ratio
self.origin_mode_menu.update = _origin_mode_menu_update
self.origin_mode_menu.scale = self.origin_mode_menu._base_ui_scale
self.origin_mode_menu.on_value_changed = self.render_selection
self.local_global_menu = ButtonGroup(['local', 'global'], default='global', min_selection=1,
position=window.top_left + Vec2(.25, 0), parent=self.ui)
# Dynamic scaling for local_global_menu
self.local_global_menu._init_w, self.local_global_menu._init_h = window.size
h = self.local_global_menu._init_h or 1
self.local_global_menu._base_ui_scale = (10 / h) * 2 # Use 10px or adjust as needed
self.local_global_menu.scale = self.local_global_menu._base_ui_scale
def _local_global_menu_update():
cur_w, _ = window.size
ratio = cur_w / (self.local_global_menu._init_w or cur_w)
self.local_global_menu.scale = self.local_global_menu._base_ui_scale * ratio
self.local_global_menu.update = _local_global_menu_update
self.local_global_menu.on_value_changed = self.render_selection
self.target_fov = 90
# Gizmos and manipulation tools
self.sun_handler = SunHandler()
self.sky = Sky(parent=scene)
self.gizmo = Gizmo()
self.rotation_gizmo = RotationGizmo()
self.scale_gizmo = ScaleGizmo()
self.box_gizmo = BoxGizmo()
self.gizmo_toggler = GizmoToggler()
self.quick_grabber = QuickGrabber()
self.quick_scaler = QuickScaler()
self.quick_rotator = QuickRotator()
self.rotate_to_view = RotateRelativeToView(target_entity=None)
self.selector = Selector()
self.selection_box = SelectionBox(model=Quad(0, mode='line'), origin=(-.5, -.5, 0),
scale=(0, 0, 1), color=color.white33, mode='new')
# Prefab loading and prefab tool setup
self.prefab_folder = application.asset_folder / 'prefabs'
from ursina.editor.prefabs.poke_shape import PokeShape
self.built_in_prefabs = [ClassSpawner, WhiteCube, TriplanarCube, Pyramid, PokeShape]
self.prefabs = []
# Editor tools
self.spawner = Spawner()
self.deleter = Deleter()
self.grouper = Grouper()
self.level_menu = LevelMenu()
self.goto_scene = self.level_menu.goto_scene
self.duplicator = Duplicator()
self.copier = Copier()
# Property and context menus
self.model_menu = ModelMenu()
self.texture_menu = TextureMenu()
self.color_menu = ColorMenu()
self.shader_menu = ShaderMenu()
self.collider_menu = ColliderMenu()
self.class_menu = ClassMenu()
self.menu_handler = MenuHandler()
self.right_click_menu = RightClickMenu()
self.hierarchy_list = HierarchyList()
self.inspector = Inspector()
self.point_of_view_selector = PointOfViewSelector()
self.help = Help()
self.search = Search() # <-- Add this line
# After creating self.help
self.help._init_w, self.help._init_h = window.size
h = self.help._init_h or 1
self.help._base_ui_scale = (8 / h) * 2 # 25px diameter, adjust as needed
self.help.scale = self.help._base_ui_scale
# For the tooltip
self.help.tooltip._init_w, self.help.tooltip._init_h = window.size
self.help.tooltip._base_ui_scale = (12 / h) * 2 # 50px text height, adjust as needed
self.help.tooltip.scale = self.help.tooltip._base_ui_scale
self._edit_mode = True
def add_entity(self, entity):
"""
Add an entity to the current scene and assign default editing properties.
"""
try:
for key, value in dict(original_parent=LEVEL_EDITOR, selectable=True, # type: ignore
collision=False, collider_type='None').items(): # type: ignore
if not hasattr(entity, key):
setattr(entity, key, value)
if self.current_scene and self.current_scene.scene_parent: # type: ignore
entity.parent = self.current_scene.scene_parent # type: ignore
self.current_scene.entities.append(entity) # type: ignore
else:
print("Error adding entity: No current scene or scene parent.")
except Exception as e:
print(f"Error adding entity: {e}")
@property
def entities(self):
"""
Get the list of entities in the current scene.
"""
return self.current_scene.entities if self.current_scene else []
@entities.setter
def entities(self, value):
"""
Set the list of entities in the current scene.
"""
if self.current_scene:
self.current_scene.entities = value
@property
def selection(self):
"""
Get the list of currently selected entities.
"""
return self.current_scene.selection if self.current_scene else []
@selection.setter
def selection(self, value):
"""
Set the list of selected entities.
"""
if self.current_scene:
self.current_scene.selection = value
def on_enable(self):
"""
Called when the LevelEditor is enabled. Adjusts camera FOV and enables UI.
"""
self._camera_original_fov = camera.fov
camera.fov = self.target_fov
if hasattr(self, 'ui'):
self.ui.enabled = True
def on_disable(self):
"""
Called when the LevelEditor is disabled. Restores original camera FOV and disables UI.
"""
camera.fov = getattr(self, '_camera_original_fov', camera.fov)
if hasattr(self, 'ui'):
self.ui.enabled = False
def update(self):
"""
Update is called every frame. It handles input-based rendering triggers.
"""
for key in 'gsxyz':
if held_keys[key]:
self.render_selection()
return
if mouse.left:
self.render_selection()
cur_w, _ = window.size
ratio = cur_w / (self.point_renderer._init_w or cur_w)
self.point_renderer.model.thickness = max(0.01, self.point_renderer._base_thickness * ratio)
# Dynamic scaling for help button
ratio = cur_w / (self.help._init_w or cur_w)
self.help.scale = max(0.05, self.help._base_ui_scale * ratio)
# Dynamic scaling for tooltip
ratio_tooltip = cur_w / (self.help.tooltip._init_w or cur_w)
self.help.tooltip.scale = max(0.7, self.help.tooltip._base_ui_scale * ratio_tooltip)
# Dynamic scaling for right-click menu
ratio = cur_w / (self.right_click_menu.radial_menu._init_w or cur_w)
self.right_click_menu.radial_menu.scale = self.right_click_menu.radial_menu._base_ui_scale * ratio
# Optionally, scale each button
for button in self.right_click_menu.radial_menu.buttons:
ratio_btn = cur_w / (button._init_w or cur_w)
button.scale = button._base_ui_scale * ratio_btn
# Dynamic scaling for serach input field
ratio = cur_w / (self.search.input_field._init_w or cur_w)
self.search.input_field.scale = self.search.input_field._base_ui_scale * ratio
def input(self, key):
"""
Handle input keys for editor commands like save, undo, redo, toggle edit mode, and zoom UI.
"""
combined_key = input_handler.get_combined_key(key)
if combined_key == 'control+s':
if not self.current_scene:
print("No current_scene, can't save.")
return
self.current_scene.save()
if self.current_scene:
if combined_key == 'control+z':
self.current_scene.undo.undo()
elif combined_key == 'control+y':
self.current_scene.undo.redo()
if self.selection and combined_key == 'f':
self.editor_camera.animate_position(self.gizmo.world_position, duration=.1, curve=curve.linear)
elif combined_key == 'control+e':
self.edit_mode = not self.edit_mode
elif combined_key == 'control++':
for e in self.ui.children:
e.scale *= 1.1
elif combined_key == 'control+-':
for e in self.ui.children:
e.scale /= 1.1
@property
def edit_mode(self):
"""
Get the current edit mode state.
"""
return self._edit_mode
@edit_mode.setter
def edit_mode(self, value):
"""
Toggle between edit and play mode, updating all UI and entity visibility and behavior accordingly.
"""
if not self.current_scene:
return
if not value and self._edit_mode:
# Enter play mode
for e in self.children:
e.ignore = True
e.visible = False
self.editor_camera.original_target_z = self.editor_camera.target_z
self.editor_camera.enabled = False
self.ui.enabled = False
for e in self.current_scene.entities:
if hasattr(e, 'edit_mode') and e.edit_mode:
e.edit_mode = False
e.editor_collider = e.collider
if e.collider:
e.editor_collider = e.collider.name
if hasattr(e, 'collider_type') and e.collider_type != 'None':
e.collider = e.collider_type
else:
e.collider = None
if hasattr(e, 'start') and callable(e.start):
e.start()
elif value and not self._edit_mode:
# Return to editor mode
self.ui.enabled = True
for e in self.current_scene.entities:
if hasattr(e, 'stop') and callable(e.stop):
e.stop()
e.collider = e.editor_collider
for e in self.children:
e.ignore = False
e.visible = True
self.editor_camera.enabled = True
self.editor_camera.target_z = self.editor_camera.original_target_z
camera.z = self.editor_camera.target_z
self._edit_mode = value
def render_selection(self, update_gizmo_position=True):
"""
Update the visual and logical selection indicators, including gizmo and cubes.
"""
# Remove invalid entities
null_entities = [e for e in self.entities if e is None]
for e in null_entities:
print('Error: found None entity in entities')
self.entities.remove(e)
self.point_renderer.model.vertices = []
self.point_renderer.model.colors = []
for e in self.entities:
if not e or (e.model and e.model.name == 'cube'):
continue
self.point_renderer.model.vertices.append(e.world_position)
if e not in self.selection:
gizmo_color = getattr(e.__class__, 'gizmo_color', color.orange)
else:
gizmo_color = getattr(e.__class__, 'gizmo_color_selected', color.azure)
self.point_renderer.model.colors.append(gizmo_color)
self.point_renderer.model.triangles = []
self.point_renderer.model.generate()
# Remove nulls from selection
self.selection = [e for e in self.selection if e]
if update_gizmo_position and self.selection:
if self.origin_mode_menu.value in ('last', 'individual'):
self.gizmo.world_position = self.selection[-1].world_position
elif self.origin_mode_menu.value == 'center':
self.gizmo.world_position = sum([e.world_position for e in self.selection]) / len(self.selection)
if self.local_global_menu.value == 'local' and self.origin_mode_menu.value == 'last':
self.gizmo.world_rotation = self.selection[-1].world_rotation
else:
self.gizmo.world_rotation = Vec3(0, 0, 0)
# Render selection cube overlays
[e.disable() for e in self.cubes]
for i, e in enumerate([e for e in self.selection if e.collider]):
if i < len(self.cubes):
self.cubes[i].world_transform = e.world_transform
self.cubes[i].origin = e.origin
self.cubes[i].model = copy(e.model)
self.cubes[i].enabled = True
LEVEL_EDITOR.hierarchy_list.render_selection() # type: ignore
class ErrorEntity(Entity):
"""
A fallback entity used to represent an error state in the level editor.
This class is typically instantiated when an entity fails to load properly,
such as due to missing model or texture references. It serves as a visual
cue in the scene that something has gone wrong.
Attributes:
model (str): The model used to represent the error entity. Defaults to 'wireframe_cube'.
color (color): The color of the entity, defaulting to red to indicate an error.
kwargs: Additional keyword arguments passed to the base Entity class.
"""
def __init__(self, model='wireframe_cube', color=color.red, **kwargs):
try:
# Attempt to initialize the error entity with the given model and color.
# This makes it visually distinct in the scene.
super().__init__(model=model, color=color, **kwargs)
except Exception as e:
# In case something goes wrong during initialization, print a descriptive error.
print(f"[ErrorEntity] Failed to initialize ErrorEntity with model='{model}': {e}")
# Optionally, fall back to a default cube if 'wireframe_cube' is missing.
try:
super().__init__(model='cube', color=color.red, **kwargs)
except Exception as fallback_error:
print(f"[ErrorEntity] Failed to fallback to default cube model: {fallback_error}")
class LevelEditorScene:
"""
Represents a single scene in the level editor grid.
This class manages the loading, saving, and unloading of a scene's entity state,
including undo tracking and metadata like coordinates and scene name.
Attributes:
coordinates (list[int, int]): The grid position (x, y) of the scene.
name (str): The name of the scene.
path (Path or None): Path to the saved scene file (.csv).
entities (list): List of entities currently in the scene.
selection (list): List of currently selected entities.
scene_parent (Entity): The root entity for all scene content.
undo (Undo): Undo handler for tracking changes within this scene.
"""
def __init__(self, x, y, name, **kwargs):
self.coordinates = [x, y]
self.name = name
self.path = None # Must be set to a valid path before saving/loading
self.entities = []
self.selection = []
self.scene_parent = None
self.undo = Undo()
# self.undo_handler may be assigned externally
def save(self):
"""
Save the scene's entities to a CSV file.
Entities must provide a `get_changes(cls)` method to serialize properties.
Skips saving if no `path` is set and no entities are available.
"""
if not self.path and not self.entities:
print('[LevelEditorScene] Cannot save: No path and no entities.')
return
try:
LEVEL_EDITOR.scene_folder.mkdir(parents=True, exist_ok=True) # type: ignore
except Exception as e:
print(f'[LevelEditorScene] Failed to create scene folder: {e}')
return
list_of_dicts = []
fields = ['class']
for e in LEVEL_EDITOR.current_scene.entities: # type: ignore
if hasattr(e, 'is_gizmo'):
continue # Skip gizmo tools
changes = e.get_changes(e.__class__)
# Replace None with False (likely a serialization decision)
for key, value in changes.items():
if value is None:
changes[key] = False
changes['class'] = e.__class__.__name__
if hasattr(e, 'collider_type'):
# Wrap collider_type in quotes to preserve string literal during eval
changes['collider_type'] = f"'{e.collider_type}'"
print('[LevelEditorScene] changes:', changes)
list_of_dicts.append(changes)
# Collect all unique fields
for key in changes:
if key not in fields:
fields.append(key)
name = LEVEL_EDITOR.current_scene.name # type: ignore
self.path = LEVEL_EDITOR.scene_folder / f'{name}.csv' # type: ignore
try:
with self.path.open('w', encoding='UTF8') as file:
writer = csv.DictWriter(file, fieldnames=fields, delimiter=';')
writer.writeheader()
writer.writerows(list_of_dicts)
print(f'[LevelEditorScene] Saved scene: {self.path}')
except Exception as e:
print(f'[LevelEditorScene] Failed to save scene: {e}')
def load(self):
"""
Load the scene from the CSV file at `self.path`.
Each line is parsed into an entity. If the class can't be found,
a fallback ErrorEntity is used instead.
"""
if not self.path:
print('[LevelEditorScene] Cannot load: path is None.')
return
if self.scene_parent:
print('[LevelEditorScene] Error: scene already loaded.')
return
# Collect all currently imported classes
imported_classes = {}
for module_name, module in list(sys.modules.items()):
if hasattr(module, '__file__') and module.__file__ and not module.__file__.startswith(sys.prefix):
for _, obj in inspect.getmembers(module):
if inspect.isclass(obj):
imported_classes[obj.__name__] = obj
t = perf_counter()
try:
with self.path.open('r') as f:
self.scene_parent = Entity() # Root container for scene
reader = csv.DictReader(f, delimiter=';')
fields = reader.fieldnames[1:] # Skip "class" column
for line in reader:
# Convert line values to evaluated Python objects
kwargs = {k: v for k, v in line.items() if v and k != 'class'}
kwargs.setdefault('parent', self.scene_parent)
for key, value in kwargs.items():
if key == 'parent':
continue
try:
kwargs[key] = eval(value)
except Exception:
pass # Leave as string if eval fails
# --- Fix: Ensure parent is always an Entity, not a string ---
if isinstance(kwargs.get('parent'), str):
kwargs['parent'] = self.scene_parent
class_name = line["class"]
target_class = imported_classes.get(class_name, ErrorEntity)
try:
instance = target_class(**kwargs)
except Exception as e:
print(f'[LevelEditorScene] Failed to instantiate {class_name}: {e}')
instance = ErrorEntity()
self.entities.append(instance)
# Post-load adjustments
for e in self.entities:
if not getattr(e, 'shader', None):
e.shader = lit_with_shadows_shader
e.selectable = True
e.original_parent = e.parent
if not hasattr(e, 'collider_type'):
e.collider_type = None
# Auto-assign colliders to cube models
if e.model and e.model.name == 'cube':
e.collider = 'box'
e.collision = False
if self.scene_parent:
print(f'[LevelEditorScene] Loaded scene "{self.name}" in {perf_counter() - t:.3f} seconds.')
return self.scene_parent
except Exception as e:
print(f'[LevelEditorScene] Failed to load scene: {e}')
def unload(self):
"""
Unload the scene by destroying all its entities and resetting state.
"""
try:
# Reparent selection cubes to editor to keep them alive
for e in LEVEL_EDITOR.cubes: # type: ignore
e.parent = LEVEL_EDITOR # type: ignore
# Destroy all scene entities
for e in list(self.entities):
destroy(e)
# Reset scene state
self.selection = []
self.entities = []
if self.scene_parent:
destroy(self.scene_parent)
self.scene = None
except Exception as e:
print(f'[LevelEditorScene] Error during unload: {e}')
class Undo(Entity):
"""
Tracks undo/redo actions for the level editor by storing a history of actions
and restoring the state of entities when triggered.
Attributes:
undo_data (list): A list of actions recorded for undo/redo.
undo_index (int): The index of the current undo position.
"""
def __init__(self, **kwargs):
super().__init__(parent=LEVEL_EDITOR, undo_data=[], undo_index=-1) # type: ignore
def record_undo(self, data):
"""
Record a new undo step.
Args:
data (any): Action data to be recorded. Format depends on action type.
"""
print('[Undo] Record undo:', data)
# Truncate forward history if undo() was used before recording again
self.undo_data = self.undo_data[:self.undo_index + 1]
self.undo_data.append(data)
self.undo_index += 1
def undo(self):
"""
Undo the last recorded action, if any.
"""
if self.undo_index < 0:
return
current_undo_data = self.undo_data[self.undo_index]
try:
if current_undo_data[0] == 'restore entities':
# Restore previously deleted entities
for id, recipe in zip(current_undo_data[1], current_undo_data[2]):
try:
clone = eval(recipe)
clone.selectable = True
clone.original_parent = clone.parent
clone.shader = lit_with_shadows_shader
LEVEL_EDITOR.entities.insert(id, clone) # type: ignore
except Exception as e:
print(f'[Undo] Failed to restore entity from recipe: {e}')
elif current_undo_data[0] == 'delete entities':
# Delete newly created entities
target_entities = [LEVEL_EDITOR.entities[id] for id in current_undo_data[1]] # type: ignore
for e in target_entities:
if e in LEVEL_EDITOR.selection: # type: ignore
LEVEL_EDITOR.selection.remove(e) # type: ignore
for e in LEVEL_EDITOR.cubes: # type: ignore
e.parent = LEVEL_EDITOR # type: ignore
for e in target_entities:
if e in LEVEL_EDITOR.entities: # type: ignore
LEVEL_EDITOR.entities.remove(e) # type: ignore
destroy(e)
else:
# Revert attribute changes (generic)
for data in current_undo_data:
id, attr, original, _ = data
try:
setattr(LEVEL_EDITOR.entities[id], attr, original) # type: ignore
except Exception as e:
print(f'[Undo] Failed to revert {attr} on entity {id}: {e}')
except Exception as e:
print(f'[Undo] Undo operation failed: {e}')
LEVEL_EDITOR.render_selection() # type: ignore
self.undo_index -= 1
def redo(self):
"""
Redo the last undone action, if available.
"""
if self.undo_index + 2 > len(self.undo_data):
return
current_undo_data = self.undo_data[self.undo_index + 1]
try:
if current_undo_data[0] == 'delete entities':
# Re-instantiate entities that were deleted
for id, recipe in zip(current_undo_data[1], current_undo_data[2]):
try:
clone = eval(recipe)
clone.selectable = True
clone.original_parent = clone.parent
clone.shader = lit_with_shadows_shader
LEVEL_EDITOR.entities.insert(id, clone) # type: ignore
except Exception as e:
print(f'[Undo] Failed to redo delete entity: {e}')
elif current_undo_data[0] == 'restore entities':
# Delete re-restored entities again
target_entities = [LEVEL_EDITOR.entities[id] for id in current_undo_data[1]] # type: ignore
for e in target_entities:
if e in LEVEL_EDITOR.selection: # type: ignore
LEVEL_EDITOR.selection.remove(e) # type: ignore
for e in LEVEL_EDITOR.cubes: # type: ignore
e.parent = LEVEL_EDITOR # type: ignore
for e in target_entities:
if e in LEVEL_EDITOR.entities: # type: ignore
LEVEL_EDITOR.entities.remove(e) # type: ignore
destroy(e)
else:
# Re-apply attribute changes
for data in current_undo_data:
id, attr, _, new = data
try:
setattr(LEVEL_EDITOR.entities[id], attr, new) # type: ignore
except Exception as e:
print(f'[Undo] Failed to reapply {attr} on entity {id}: {e}')
except Exception as e:
print(f'[Undo] Redo operation failed: {e}')
LEVEL_EDITOR.render_selection() # type: ignore
self.undo_index += 1
axis_colors = {
'x' : color.magenta,
'y' : color.yellow,
'z' : color.cyan
}
if not load_model('arrow', application.internal_models_compressed_folder):
p = Entity(enabled=False)
Entity(parent=p, model='cube', scale=(1,.05,.05))
Entity(parent=p, model=Cone(4), x=.5, scale=.2, rotation=(0,90,0))
arrow_model = p.combine()
arrow_model.save('arrow.ursinamesh', folder=application.internal_models_compressed_folder, max_decimals=4)
if not load_model('scale_gizmo', application.internal_models_compressed_folder):
p = Entity(enabled=False)
Entity(parent=p, model='cube', scale=(.05,.05,1))
Entity(parent=p, model='cube', z=.5, scale=.2)
arrow_model = p.combine()
arrow_model.save('scale_gizmo.ursinamesh', folder=application.internal_models_compressed_folder, max_decimals=4)
class GizmoArrow(Draggable):
"""
A draggable arrow gizmo used in the level editor for transforming selected entities.
Attributes:
record_undo (bool): Whether dragging should record undo operations.
original_rotation (Quaternion): The rotation state when initialized.
"""
def __init__(self, model='arrow', collider='box', **kwargs):
"""
Initialize the GizmoArrow with default arrow model and unlit shader.
Args:
model (str): Model used for the gizmo. Defaults to 'arrow'.
collider (str): Collider shape. Defaults to 'box'.
**kwargs: Additional arguments passed to the Draggable initializer.
"""
super().__init__(
model=model,
origin_x=-0.55,
always_on_top=True,
render_queue=1,
is_gizmo=True,
shader=unlit_shader,
**kwargs
)
# Allow override of any custom attributes passed via kwargs
for key, value in kwargs.items():
setattr(self, key, value)
self.record_undo = True
self.original_rotation = self.rotation
def drag(self):
"""
Triggered when the gizmo is dragged.
Assigns proper parent and state to each selected entity.
"""
self.world_parent = LEVEL_EDITOR # type: ignore
LEVEL_EDITOR.gizmo.world_parent = self # type: ignore
for e in LEVEL_EDITOR.selection: # type: ignore
# Determine original parent for undo
if not hasattr(e.parent, 'is_gizmo') or not e.parent.is_gizmo:
e.original_parent = e.parent
else:
e.original_parent = scene # fallback to root
# Assign new world parent based on editor mode
if LEVEL_EDITOR.local_global_menu.value == 'global': # type: ignore
e.world_parent = self
else:
e.world_parent = LEVEL_EDITOR.gizmo.fake_gizmo # type: ignore
e.always_on_top = False
e._original_world_transform = e.world_transform
def drop(self):
"""
Triggered when the gizmo is released after dragging.
Restores parent relationships and records undo if transform changed.
"""
LEVEL_EDITOR.gizmo.world_parent = LEVEL_EDITOR # type: ignore
for e in LEVEL_EDITOR.selection: # type: ignore
e.world_parent = e.original_parent
print('[Drop] Original parent restored:', e.original_parent, isinstance(e.original_parent, GizmoArrow))
if not LEVEL_EDITOR.selection: # type: ignore
return
# Check if transform has changed
first = LEVEL_EDITOR.selection[0] # type: ignore
try:
changed = any(
distance(first.world_transform[i], first._original_world_transform[i]) > 0.0001
for i in range(3)
)
except Exception as e:
print(f'[Drop] Error comparing transforms: {e}')
changed = False
# Record undo if applicable
if self.record_undo and changed:
changes = []
for e in LEVEL_EDITOR.selection: # type: ignore
try:
index = LEVEL_EDITOR.entities.index(e) # type: ignore
changes.append([index, 'world_transform', e._original_world_transform, e.world_transform])
except ValueError:
print(f'[Drop] Entity not found in LEVEL_EDITOR.entities: {e}')
LEVEL_EDITOR.current_scene.undo.record_undo(changes) # type: ignore
# Reset gizmo
self.parent = LEVEL_EDITOR.gizmo.arrow_parent # type: ignore
self.position = (0, 0, 0)
self.rotation = self.original_rotation
LEVEL_EDITOR.render_selection() # type: ignore
def input(self, key):
"""
Handle input events, such as snapping steps.
Args:
key (str): Input key string.
"""
super().input(key)
if key == 'control':
self.step = (1, 1, 1)
elif key == 'control up':
self.step = (0, 0, 0)
class Gizmo(Entity):
"""
The main gizmo controller used in the level editor for manipulating entities.
Supports move handles for the X, Y, Z axes, XZ plane, and local/global transform handling
using a 'fake gizmo' trick to allow local axis dragging.
"""
def __init__(self, **kwargs):
"""
Initialize the Gizmo object, including subgizmos for each axis and a fake gizmo
used for local space transformations.
"""
super().__init__(parent=LEVEL_EDITOR, enabled=False) # type: ignore
self.arrow_parent = Entity(parent=self)
# Helper object used for locking movement to an axis (in local mode)
self.lock_axis_helper_parent = Entity(parent=LEVEL_EDITOR) # type: ignore
self.lock_axis_helper = Entity(parent=self.lock_axis_helper_parent)
# Subgizmos for individual axes and plane
self.subgizmos = {
'xz': GizmoArrow(
parent=self.arrow_parent,
gizmo=self,
model='cube',
collider='plane',
scale=0.6,
scale_y=0.05,
origin=(-0.75, 0, -0.75),
color=lerp(color.magenta, color.cyan, 0.5),
plane_direction=(0, 1, 0)
),
'x': GizmoArrow(
parent=self.arrow_parent,
gizmo=self,
color=axis_colors['x'],
lock=(0, 1, 1)
),
'y': GizmoArrow(
parent=self.arrow_parent,
gizmo=self,
rotation=(0, 0, -90),
color=axis_colors['y'],
lock=(1, 0, 1)
),
'z': GizmoArrow(
parent=self.arrow_parent,
gizmo=self,
rotation=(0, -90, 0),
color=axis_colors['z'],
plane_direction=(0, 1, 0),
lock=(1, 1, 0)
),
}
# Set highlight and original scale for visual feedback
for arrow in self.arrow_parent.children:
arrow.highlight_color = color.white
arrow.original_scale = arrow.scale
self.subgizmos['xz'].original_scale = self.subgizmos['xz'].scale
self.subgizmos['x'].original_scale = self.subgizmos['x'].scale
self.subgizmos['y'].original_scale = self.subgizmos['y'].scale
self.subgizmos['z'].original_scale = self.subgizmos['z'].scale
# Fake gizmo: used for local transform locking without visual clutter
self.fake_gizmo = Entity(parent=LEVEL_EDITOR, enabled=False) # type: ignore
self.fake_gizmo.subgizmos = {}
for key, original in self.subgizmos.items():
self.fake_gizmo.subgizmos[key] = duplicate(original, parent=self.fake_gizmo, collider=None, ignore=True)
def input(self, key):
"""
Called before subgizmo input is processed.
Handles drag initiation and drop logic based on mouse input and mode.
"""
if key == 'left mouse down' and mouse.hovered_entity in self.subgizmos.values():
self.drag()
if key == 'left mouse up' and LEVEL_EDITOR.local_global_menu.value == 'local': # type: ignore
self.drop()
def drag(self, show_gizmo_while_dragging=True):
"""
Called when user starts dragging one of the subgizmos.
Prepares gizmo and sets plane direction / locking depending on local/global mode.
"""