-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathws-edit.py
More file actions
1800 lines (1523 loc) · 70.1 KB
/
Copy pathws-edit.py
File metadata and controls
1800 lines (1523 loc) · 70.1 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
#!/usr/bin/env python3
# This is terrible, sloppy code that was cobbled together to get things done.
# Lots of workarounds to make this work with tkinter, which is inappropriate for rendering the main view
import os, json, subprocess, tkinter as tk, math
from tkinter import filedialog, messagebox, simpledialog, ttk
import tkinter.font as tkfont
from PIL import Image, ImageTk, ImageDraw, ImageFont
import sys
import threading
import textwrap
import secrets
import time
# Setup
generator_file = "ws-gen.py"
def module_output_path(preset_name):
return os.path.join("output", preset_name, "module_output")
#resample_filter = Image.Resampling.LANCZOS
#resample_filter = Image.Resampling.BILINEAR
resample_filter = Image.Resampling.BICUBIC
NODE_MARGIN = 5
NODE_WIDTH = 200
NODE_HEADER_HEIGHT = 30
NODE_PROPERTY_HEIGHT = 15
THUMBNAIL_SIZE = (200, 200)
# Valid map sizes.
VALID_MAP_SIZES = [64, 128, 256, 512, 1024, 1081, 2048, 4096]
init_log = []
# FONTS
try:
font_regular_10 = ImageFont.truetype("arial.ttf", 10)
font_regular_12 = ImageFont.truetype("arial.ttf", 12)
font_regular_16 = ImageFont.truetype("arial.ttf", 16)
font_bold_14 = ImageFont.truetype("arialbd.ttf", 16)
except:
font_regular_10 = ImageFont.load_default()
font_regular_12 = ImageFont.load_default()
font_regular_16 = ImageFont.load_default()
font_bold_14 = ImageFont.load_default()
g_editor = None
NODE_DEFINITIONS = {}
# ---------------------------
# Helper Functions
# ---------------------------
def get_node_rect(node):
w, h = node.get_intrinsic_size()
return (node.x, node.y, node.x + w, node.y + h)
def get_center(rect):
x1, y1, x2, y2 = rect
return ((x1+x2)/2, (y1+y2)/2)
def calc_border_point(rect, target):
x1, y1, x2, y2 = rect
cx, cy = (x1+x2)/2, (y1+y2)/2
hw = (x2 - x1)/2
hh = (y2 - y1)/2
tx, ty = target
dx = tx - cx
dy = ty - cy
if dx == 0 and dy == 0:
return (cx, cy)
scale = min(hw/abs(dx) if dx != 0 else float('inf'),
hh/abs(dy) if dy != 0 else float('inf'))
return (cx + dx * scale, cy + dy * scale)
def format_for_display(value):
"""Convert JSON values to user-friendly string representation."""
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, list):
return json.dumps(value) # Display lists as valid JSON (with brackets)
return str(value) # Default: show numbers and strings as-is
def parse_from_display(text, expected_type):
"""Convert user-edited text back into its expected JSON type."""
text = text.strip()
if expected_type is bool:
if text.lower() == "true":
return True
elif text.lower() == "false":
return False
raise ValueError("Boolean values must be 'true' or 'false'.")
elif expected_type is int:
try:
return int(text)
except ValueError:
raise ValueError(f"Expected an integer, got '{text}'.")
elif expected_type is float:
try:
return float(text)
except ValueError:
raise ValueError(f"Expected a float, got '{text}'.")
elif expected_type is list:
try:
return json.loads(text) # Ensure lists are stored as valid JSON arrays
except json.JSONDecodeError:
raise ValueError(f"Expected a valid JSON array, got '{text}'.")
return text # Default to string
##############################################################################################################################
##############################################################################################################################
# Connection Class
##############################################################################################################################
##############################################################################################################################
class Connection:
def __init__(self, source_node, source_port, target_node, target_port):
self.source_node = source_node
self.source_port = source_port
self.target_node = target_node
self.target_port = target_port
self.canvas_line = None
self.canvas_text_image = None
# Pre-render the text
font = font_regular_12
txt = str(self.source_node.properties.get(self.source_port, ""))
try:
bbox = font.getbbox(txt)
self.text_width = bbox[2] - bbox[0]
self.text_height = bbox[3] - bbox[1]
except Exception:
self.text_width, self.text_height = font.getsize(txt)
self.text_height = int(self.text_height * 1.5 + 1)
self.text_img = Image.new("RGBA", (self.text_width, self.text_height), (255,255,255,0))
self.text_img_photo = None
d = ImageDraw.Draw(self.text_img)
d.text((0,0), txt, font=font, fill="black")
def update_line(self, canvas):
# Compute world endpoints.
rect_source = get_node_rect(self.source_node)
if self.target_node is not None:
rect_target = get_node_rect(self.target_node)
else:
mouse_size = 10
rect_target = (
g_editor.view_cursor_x - mouse_size,
g_editor.view_cursor_y - mouse_size,
g_editor.view_cursor_x + mouse_size,
g_editor.view_cursor_y + mouse_size
)
center_target = get_center(rect_target)
source_point = calc_border_point(rect_source, center_target)
center_source = get_center(rect_source)
target_point = calc_border_point(rect_target, center_source)
# Transform to screen coordinates.
zoom = self.source_node.editor.current_zoom
cam_x = self.source_node.editor.camera_offset_x
cam_y = self.source_node.editor.camera_offset_y
sx, sy = source_point
tx, ty = target_point
sx_screen = (sx - cam_x) * zoom
sy_screen = (sy - cam_y) * zoom
tx_screen = (tx - cam_x) * zoom
ty_screen = (ty - cam_y) * zoom
if not self.canvas_line:
#self.canvas_line = canvas.create_line(0, 0, 0, 0, arrow=tk.LAST, fill="#555555", width=2 * self.current_zoom)
self.canvas_line = canvas.create_line(0, 0, 0, 0, arrow=tk.LAST, state="disabled")
# Update arrow line.
canvas.itemconfig(self.canvas_line, fill="#555555", width=2*zoom)
canvas.coords(self.canvas_line, sx_screen, sy_screen, tx_screen, ty_screen)
# Compute arrow angle.
dx = tx_screen - sx_screen
dy = ty_screen - sy_screen
angle = math.degrees(math.atan2(dy, dx))
if angle > 90 or angle < -90:
angle += 180
# Midpoint.
mid_x = (sx_screen + tx_screen) / 2
mid_y = (sy_screen + ty_screen) / 2
# Compute a normal vector.
angle_rad = math.radians(angle)
normal1 = (-math.sin(angle_rad), math.cos(angle_rad))
normal2 = (math.sin(angle_rad), -math.cos(angle_rad))
# Choose the normal with a negative y (upward).
normal = normal1 if normal1[1] < 0 else normal2
offset = 10 * zoom # scale offset with zoom.
text_x = mid_x + normal[0] * offset
text_y = mid_y + normal[1] * offset
new_size = (int(self.text_width * zoom), int(self.text_height * zoom))
scaled = self.text_img.resize(new_size, resample_filter)
rotated = scaled.rotate(-angle, resample = resample_filter, expand=1)
self.text_img_photo = ImageTk.PhotoImage(rotated)
if self.canvas_text_image:
canvas.itemconfig(self.canvas_text_image, image=self.text_img_photo)
canvas.coords(self.canvas_text_image, text_x, text_y)
else:
self.canvas_text_image = canvas.create_image(text_x, text_y, image=self.text_img_photo, anchor="center", state="disabled")
##############################################################################################################################
##############################################################################################################################
# Node Class
##############################################################################################################################
##############################################################################################################################
class Node:
def __init__(self, editor, node_type, properties=None, x=0, y=0):
self.editor = editor
self.canvas = editor.canvas
self.node_type = node_type
self.definition = NODE_DEFINITIONS[node_type]
self.properties = {}
self.id = secrets.token_urlsafe(3)
# Initialize inputs
for inp in self.definition.get("inputs", []):
self.properties[inp["name"]] = inp.get("default", None)
# Initialize outputs
for i, outp in enumerate(self.definition.get("outputs", [])):
if i == 0:
self.properties[outp["name"]] = f"{node_type}_{self.id}"
else:
self.properties[outp["name"]] = f"{node_type}_{self.id}_{i}"
# Initialize settings
for setting in self.definition.get("settings", []):
self.properties[setting["name"]] = setting.get("default")
# Initialize properties to outside specs
if properties:
for key, value in properties.items():
self.properties[key] = value
# Use saved position if available.
if properties and "x" in properties and "y" in properties:
self.x = properties["x"]
self.y = properties["y"]
else:
self.x = x
self.y = y
self.baked_texture = None
self.baked_dimensions = (0, 0)
self.scaled_photo_image = None
self.last_zoom = 0
self.canvas_image_item = None
self.selected = False
self._drag_start = None
self.editor.dragging = False
self.editor_entries = {}
self.editor_graphics_canvas = None
self.canvas_border_item = None
self.draw()
def get_filtered_properties(self):
result = {}
for key, value in self.properties.items():
if key != "type" and not key.startswith("_"):
result[key] = value
return result
def set_dirty(self):
self.editor.set_dirty(self)
def draw(self):
self.bake_texture()
self.update_display()
def update(self):
self.update_display()
def on_click_node(self, event):
self.dragging = False
# 1) Convert to world/logical coords
zoom = self.editor.current_zoom
world_x = self.canvas.canvasx(event.x) / zoom + self.editor.camera_offset_x
world_y = self.canvas.canvasy(event.y) / zoom + self.editor.camera_offset_y
# 2) Convert to node-local coords
local_x = world_x - self.x
local_y = world_y - self.y
# 3) Hit-test inputs
for name, (x0, y0, x1, y1) in self.input_regions.items():
if x0 <= local_x <= x1 and y0 <= local_y <= y1:
self.editor.set_selected_node(self)
return self.on_input_click(name)
# 4) Hit-test outputs
for name, (x0, y0, x1, y1) in self.output_regions.items():
if x0 <= local_x <= x1 and y0 <= local_y <= y1:
self.editor.set_selected_node(self)
return self.on_output_click(name)
# 5) Fallback to dragging:
self.editor.cancel_pending_connection()
self.editor.set_selected_node(self)
self.dragging = True
self.on_start_drag(event)
def on_start_drag(self, event):
if self.editor.is_panning or self.dragging == False:
return
zoom = self.editor.current_zoom
world_x = self.canvas.canvasx(event.x) / zoom + self.editor.camera_offset_x
world_y = self.canvas.canvasy(event.y) / zoom + self.editor.camera_offset_y
self._drag_start = (world_x, world_y)
self.editor.drag_data = {"node": self, "x": world_x, "y": world_y}
self.update_display()
def on_output_click(self, output_name):
"""
User clicked this node’s output: record it as the pending source.
"""
self.editor.cancel_pending_connection()
self.editor.pending_connection = {
"from_node": self,
"from_output": output_name
}
#print(f"Connection source set: {self}.{output_name}")
conn = Connection(self, output_name, None, None)
self.editor.connections.append(conn)
def on_input_click(self, input_name):
"""
User clicked an input: if a source is pending, complete the link
by copying the source’s output identifier into this input property.
"""
ec = getattr(self.editor, "pending_connection", None)
if not ec or "from_node" not in ec:
#print("No pending connection source; please click an output first.")
return
src_node = ec["from_node"]
src_field = ec["from_output"]
src_value = src_node.properties[src_field]
# Assign the connection by setting this input property
self.properties[input_name] = src_value
#print(f"Connected {src_node}.{src_field} → {self}.{input_name}")
# Clear pending state
self.editor.cancel_pending_connection()
# Refresh all nodes and their connections
for node in self.editor.nodes:
node.draw()
#self.editor.update_all_connections()
self.editor.rebuild_connections()
self.editor.set_unsaved()
self.set_dirty()
def on_drag(self, event):
if self.editor.is_panning or self.dragging == False:
return
zoom = self.editor.current_zoom
new_logical_x = self.canvas.canvasx(event.x) / zoom + self.editor.camera_offset_x
new_logical_y = self.canvas.canvasy(event.y) / zoom + self.editor.camera_offset_y
dx = new_logical_x - self.editor.drag_data["x"]
dy = new_logical_y - self.editor.drag_data["y"]
self.x += dx
self.y += dy
self.editor.drag_data["x"] = new_logical_x
self.editor.drag_data["y"] = new_logical_y
self.update_display()
self.editor.update_all_connections()
def on_release_drag(self, event):
if self.editor.is_panning or self.dragging == False:
return
self.editor.drag_data = {}
self._drag_start = None
self.update_display()
def select(self):
self.selected = True
self.update_display()
def deselect(self):
self.selected = False
self.update_display()
def to_json(self):
data = {"type": self.node_type}
data.update(self.properties)
data["_editor_px"] = self.x
data["_editor_py"] = self.y
return data
def get_intrinsic_size(self):
return self.baked_dimensions
def update_display(self):
zoom = self.editor.current_zoom
w, h = self.get_intrinsic_size()
new_size = (int(w * zoom), int(h * zoom))
if self.last_zoom != zoom or self.scaled_photo_image is None:
scaled_image = self.baked_texture.resize(new_size, resample_filter)
self.scaled_photo_image = ImageTk.PhotoImage(scaled_image)
cam_x = self.editor.camera_offset_x
cam_y = self.editor.camera_offset_y
scaled_x = (self.x - cam_x) * zoom
scaled_y = (self.y - cam_y) * zoom
if self.canvas_image_item is None:
# Add a tag to the node image.
self.canvas_image_item = self.canvas.create_image(scaled_x, scaled_y, anchor="nw", image=self.scaled_photo_image, tags=(f"node_{self.id}",))
self.canvas.tag_bind(self.canvas_image_item, "<ButtonPress-1>", self.on_click_node)
self.canvas.tag_bind(self.canvas_image_item, "<B1-Motion>", self.on_drag)
self.canvas.tag_bind(self.canvas_image_item, "<ButtonRelease-1>", self.on_release_drag)
else:
if self.last_zoom != zoom:
self.canvas.itemconfig(self.canvas_image_item, image=self.scaled_photo_image)
self.canvas.coords(self.canvas_image_item, scaled_x, scaled_y)
self.last_zoom = zoom
# Border rectangle for selection
x1, y1 = scaled_x, scaled_y
x2 = x1 + new_size[0]
y2 = y1 + new_size[1]
border_color = "blue" if self.selected else ""
if self.canvas_border_item is None:
self.canvas_border_item = self.canvas.create_rectangle(
x1, y1, x2, y2, outline=border_color, width=2
)
else:
self.canvas.coords(self.canvas_border_item, x1, y1, x2, y2)
self.canvas.itemconfig(self.canvas_border_item, outline=border_color)
# Ensure border is behind the image
if self.canvas_image_item is not None:
self.canvas.tag_lower(self.canvas_border_item, self.canvas_image_item)
def create_thumbnail_image(self, file_path, ph_font, width = THUMBNAIL_SIZE[0], height = THUMBNAIL_SIZE[1]):
if file_path and os.path.exists(file_path):
try:
img = Image.open(file_path).convert("RGBA")
orig_w, orig_h = img.size
max_w, max_h = (width, height)
if orig_w >= orig_h:
new_w = max_w
new_h = int(round(orig_h * (max_w / orig_w)))
else:
new_h = max_h
new_w = int(round(orig_w * (max_h / orig_h)))
return img.resize((new_w, new_h), resample_filter)
except Exception as e:
canvas = Image.new("RGBA", (width, height), "white")
draw = ImageDraw.Draw(canvas)
draw.rectangle([0, 0, width - 1, height - 1], outline="red")
draw.text((5, 5), "Error", fill="red", font=ph_font)
return canvas
else:
canvas = Image.new("RGBA", (width, height), "white")
draw = ImageDraw.Draw(canvas)
draw.rectangle([0, 0, width - 1, height - 1], outline="gray")
draw.text((5, 5), "No image yet\nRun generation to update", fill="gray", font=ph_font)
return canvas
def bake_texture(self):
# Create the thumbnail first so we know its dimensions.
preset_name = self.editor.current_preset_name()
outname = self.properties.get("out", None)
norm_path = None
if outname and preset_name:
norm_path = os.path.join(module_output_path(preset_name),
f"norm_{outname}.png")
ph_font = font_regular_10
norm_thumb = self.create_thumbnail_image(
norm_path, ph_font,
THUMBNAIL_SIZE[0], THUMBNAIL_SIZE[1]
)
thumb_w, thumb_h = norm_thumb.size
# Gather filtered properties (skip internal "_*" and type)
filtered_props = self.get_filtered_properties()
# Identify inputs and outputs by definition
input_names = [inp["name"] for inp in self.definition.get("inputs", [])]
output_names = [outp["name"] for outp in self.definition.get("outputs", [])]
# Separate settings/other props
settings_and_others = [
k for k in filtered_props
if k not in input_names + output_names and not k.startswith("_")
]
# Build ordered rows: inputs, outputs, then settings/others
all_rows = input_names + output_names + settings_and_others
# Fonts
header_font = font_bold_14
prop_font = font_regular_12
io_font = font_regular_16
# Compute header text size
hbbox = header_font.getbbox(self.node_type)
header_text_w = hbbox[2] - hbbox[0]
header_text_h = hbbox[3] - hbbox[1]
# Measure text heights for padding
io_tb = io_font.getbbox("Hg")
io_text_h = io_tb[3] - io_tb[1]
prop_tb = prop_font.getbbox("Hg")
prop_text_h = prop_tb[3] - prop_tb[1]
# Padding and extra spacing
IO_PADDING = 8 # total vertical padding for I/O rows
EXTRA_BOTTOM = 3 # extra space below text (increased for internal lower padding)
SPACING = 2 # vertical gap between boxes, accounts for border
# Compute per-row heights
IO_ROW_HEIGHT = max(NODE_PROPERTY_HEIGHT, io_text_h + IO_PADDING) + EXTRA_BOTTOM
OTHER_ROW_HEIGHT = NODE_PROPERTY_HEIGHT + EXTRA_BOTTOM
row_heights = [
IO_ROW_HEIGHT if key in input_names + output_names else OTHER_ROW_HEIGHT
for key in all_rows
]
# Total height for all property boxes + gaps
total_props_h = sum(row_heights) + SPACING * (len(row_heights) - 1)
# Determine overall dimensions
final_width = max(thumb_w, header_text_w, NODE_WIDTH) + 2 * NODE_MARGIN
final_height = (
NODE_MARGIN +
NODE_HEADER_HEIGHT +
NODE_MARGIN +
total_props_h +
NODE_MARGIN +
thumb_h +
NODE_MARGIN
)
# Create canvas
image = Image.new("RGBA", (final_width, final_height), "white")
draw = ImageDraw.Draw(image)
# Draw header
header_top = NODE_MARGIN
header_bottom = header_top + NODE_HEADER_HEIGHT
draw.rectangle(
[NODE_MARGIN, header_top, final_width - NODE_MARGIN, header_bottom],
fill="lightblue", outline="black"
)
header_x = NODE_MARGIN + ((final_width - 2 * NODE_MARGIN) - header_text_w) // 2
header_y = header_top + (NODE_HEADER_HEIGHT - header_text_h) // 2
draw.text((header_x, header_y), self.node_type,
fill="black", font=header_font)
# Prepare click regions
self.input_regions = {}
self.output_regions = {}
# Draw each property/I/O box
y = header_bottom + NODE_MARGIN
content_left = NODE_MARGIN
content_right = final_width - NODE_MARGIN
for key, row_h in zip(all_rows, row_heights):
y0 = y
y1 = y0 + row_h
# Determine background and region (colors flipped)
if key in input_names:
bg_color = "#fce8b2" # pale orange for inputs
self.input_regions[key] = (content_left, y0, content_right, y1)
font = io_font
elif key in output_names:
bg_color = "#c8f7c5" # pale green for outputs
self.output_regions[key] = (content_left, y0, content_right, y1)
font = io_font
else:
bg_color = "#f0f0f0" # very light gray for other properties
font = prop_font
# Draw background box
draw.rectangle([content_left, y0, content_right, y1],
fill=bg_color, outline="black")
# Draw text, vertically centered with extra bottom padding
text = f"{key}: {filtered_props.get(key)}"
tbbox = font.getbbox(text)
text_h = tbbox[3] - tbbox[1]
text_y = y0 + (row_h - text_h) // 2
draw.text((content_left + 4, text_y), text,
fill="black", font=font)
# Advance y by box height + spacing
y = y1 + SPACING
# Draw thumbnail
graphics_top = y + NODE_MARGIN
slot_x = NODE_MARGIN + ((final_width - 2 * NODE_MARGIN) - thumb_w) // 2
image.paste(norm_thumb, (slot_x, graphics_top))
# Outer border
draw.rectangle([0, 0, final_width - 1, final_height - 1],
outline="black")
# Store result
self.baked_texture = image
self.baked_dimensions = (final_width, final_height)
self.last_zoom = -100
def create_live_editor(self, parent):
w, h = self.get_intrinsic_size()
frame = tk.Frame(parent, width=w, height=h, relief="raised", borderwidth=2)
frame.pack_propagate(False)
# --- Header ---
header = tk.Label(frame, text=self.node_type, font=("Arial", 14, "bold"), bg="lightblue")
header.pack(fill="x", padx=NODE_MARGIN, pady=(NODE_MARGIN, 0))
# --- Module Documentation Widget using full width ---
module_doc = self.definition.get(
"doc",
"Module doc not found"
)
# Use a tk.Message instead of tk.Label to get a neat, full-width, auto-wrapping text display.
doc_message = tk.Message(frame,
text=module_doc,
width=int(THUMBNAIL_SIZE[0] * 1.5),#w - 2 * NODE_MARGIN,
bg="lightyellow",
font=("Arial", 10),
justify="center")
doc_message.pack(fill="x", padx=NODE_MARGIN, pady=(NODE_MARGIN, 0))
# --- Properties Section ---
prop_frame = tk.Frame(frame)
prop_frame.pack(fill="x", padx=NODE_MARGIN, pady=NODE_MARGIN)
self.editor_entries = {}
# Mouse-over tooltip now uses the same tone of yellow ("lightyellow")
self.tooltip = tk.Label(frame, text="", bg="lightyellow", relief="solid", borderwidth=1, wraplength=200)
self.tooltip.place_forget() # Hide initially
filtered_props = self.get_filtered_properties()
for key, value in filtered_props.items():
row = tk.Frame(prop_frame)
row.pack(fill="x", pady=2)
lbl = tk.Label(row, text=f"{key}:", width=15, anchor="w")
lbl.pack(side="left")
ent = tk.Entry(row)
help_text = "No documentation available"
for setting in self.definition.get("settings", []):
if setting["name"] == key:
help_text = f'{setting["doc"]}\nDefaults to \'{setting["default"]}\''
break
for setting in self.definition.get("inputs", []):
if setting["name"] == key:
help_text = f'{setting["doc"]}\nThe name of some other module\'s output.'
break
for setting in self.definition.get("outputs", []):
if setting["name"] == key:
help_text = f'{setting["doc"]}\nTo be used in some other module as input.\nThe name \'final\' makes it the final output for this template.'
break
original_type = type(value)
self.editor_entries[key] = (ent, original_type)
ent.insert(0, format_for_display(value))
ent.pack(side="left", fill="x", expand=True)
ent.bind("<Enter>", lambda event, text=help_text: self.show_tooltip(event, text))
ent.bind("<Leave>", lambda event: self.hide_tooltip())
# --- Graphics Section ---
graphics_frame = tk.Frame(frame)
graphics_frame.pack(padx=NODE_MARGIN, pady=NODE_MARGIN)
# Commit/Delete buttons placed above the thumbnail
btn_frame = tk.Frame(graphics_frame)
btn_frame.pack(pady=NODE_MARGIN)
commit_btn = tk.Button(btn_frame, text="Apply Changes", command=self.commit_from_editor)
commit_btn.pack(side="left", padx=5)
#delete_btn = tk.Button(btn_frame, text="Delete", command=lambda: self.editor.delete_selected_node())
#delete_btn.pack(side="left", padx=5)
preset_name = self.editor.current_preset_name()
outname = self.properties.get("out", None)
norm_path = None
if outname and preset_name:
norm_path = os.path.join(module_output_path(preset_name), f"norm_{outname}.png")
ph_font = font_regular_10
# Create the norm thumbnail which preserves aspect ratio.
norm_thumb = self.create_thumbnail_image(norm_path, ph_font,
int(THUMBNAIL_SIZE[0] * 1.5),
int(THUMBNAIL_SIZE[1] * 1.5))
thumb_w, thumb_h = norm_thumb.size
# Set the canvas to exactly match the thumbnail's dimensions.
canvas = tk.Canvas(graphics_frame, width=thumb_w, height=thumb_h, bg="white")
canvas.pack()
# Convert the PIL thumbnail into a Tkinter PhotoImage.
norm_photo = ImageTk.PhotoImage(norm_thumb)
# Place the image onto the canvas, centered.
canvas.create_image(thumb_w // 2, thumb_h // 2, image=norm_photo)
# Keep a reference to avoid garbage collection.
self._norm_photo = norm_photo
self.editor_graphics_canvas = canvas
canvas.bind("<Button-1>", self.on_graphics_click)
# Compute brightness info from the raw image (instead of the norm variant)
raw_path = None
if outname and preset_name:
raw_path = os.path.join(module_output_path(preset_name), f"raw_{outname}.png")
try:
raw_image = Image.open(raw_path)
raw_gray = raw_image.convert("L")
min_brightness, max_brightness = raw_gray.getextrema()
brightness_text = f"Brightness {min_brightness} to {max_brightness}"
except Exception as e:
brightness_text = "Unable to determine brightness info"
brightness_label = tk.Label(graphics_frame, text=brightness_text)
brightness_label.pack(pady=NODE_MARGIN)
update_label = tk.Label(graphics_frame,
text="[Click image to open]",
font=("Arial", 10))
update_label.pack(pady=(0, NODE_MARGIN))
return frame
def show_tooltip(self, event, text):
"""Show tooltip near the entry widget."""
self.tooltip.config(text=text)
self.tooltip.place(x=event.widget.winfo_rootx() - self.tooltip.master.winfo_rootx(),
y=event.widget.winfo_rooty() - self.tooltip.master.winfo_rooty() + 25)
self.tooltip.lift() # Ensure tooltip appears on top
def hide_tooltip(self, event=None):
"""Hide tooltip."""
self.tooltip.place_forget()
def commit_from_editor(self):
"""Parse values back into their correct types and store them."""
for key, (entry, original_type) in self.editor_entries.items():
new_val = entry.get().strip()
try:
self.properties[key] = parse_from_display(new_val, original_type)
except ValueError as e:
messagebox.showerror("Error", str(e))
return
self.draw()
# this probably should include a slight update of node editor graphics but nevermind for now
self.editor.cancel_pending_connection()
self.editor.rebuild_connections()
self.editor.set_unsaved(True)
self.set_dirty()
def on_graphics_click(self, event):
self.open_full_image_in_editor("norm")
def open_full_image_in_editor(self, slot):
preset_name = self.editor.current_preset_name()
outname = self.properties.get("out", None)
if not (outname and preset_name):
return
path = os.path.join(module_output_path(preset_name), f"{slot}_{outname}.png")
if not os.path.exists(path):
return
top = tk.Toplevel(self.editor)
top.title(os.path.basename(path))
canvas = tk.Canvas(top, bg="black")
canvas.pack(fill="both", expand=True)
try:
original = Image.open(path).convert("RGBA")
except Exception as e:
messagebox.showerror("Error", f"Failed to open image: {e}")
return
def resize_image(event):
cw, ch = event.width, event.height
ow, oh = original.size
scale = min(cw/ow, ch/oh)
new_size = (int(ow*scale), int(oh*scale))
resized = original.resize(new_size, resample_filter)
photo = ImageTk.PhotoImage(resized)
canvas.photo = photo
canvas.delete("all")
canvas.create_image(cw/2, ch/2, image=photo, anchor="center")
canvas.bind("<Configure>", resize_image)
##############################################################################################################################
##############################################################################################################################
# Editor Class
##############################################################################################################################
##############################################################################################################################
class NodeEditorApp(tk.Tk):
def __init__(self):
global g_editor
super().__init__()
g_editor = self
self.current_preset = "Untitled"
self.unsaved = False
self.map_width = 256
self.map_height = 256
self.update_title()
self.geometry("1200x800")
self.nodes = []
self.connections = []
self.drag_data = {}
self._node_id_counter = 1
self.is_panning = False
self.pan_start_x = 0
self.pan_start_y = 0
self.pan_start_camera_x = 0
self.pan_start_camera_y = 0
self.shift_pressed = False
self.mouse_x = 0
self.mouse_y = 0
self.pending_connection = None
self.generation_queue = []
self.generation_running = False
self.generation_type = ""
self.mainview_bg_color = "#bbbbbb"
self.mainview_grid_size = 400
self.mainview_grid_color = "#999999"
self.mainview_origin_color = "#888888"
self.tick_interval = 3000
self.create_menu()
self.create_toolbar()
self.create_ui()
self.init_crap_id = self.canvas.bind("<Configure>", lambda e: self.draw_overlay(True))
self.bind("<Control-s>", lambda event: self.save_template())
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.canvas.bind("<ButtonPress-3>", self.on_right_button_press)
self.canvas.bind("<ButtonRelease-3>", self.on_right_button_release)
self.canvas.bind("<B3-Motion>", self.on_right_button_drag)
self.canvas.bind("<Motion>", self.on_mouse_move)
self.canvas.bind("<MouseWheel>", self.on_mousewheel)
self.canvas.bind("<ButtonPress-1>", self.on_left_mouse_button)
self.bind("<KeyPress-Shift_L>", self.on_shift_press)
self.bind("<KeyRelease-Shift_L>", self.on_shift_release)
self.bind("<KeyPress-Shift_R>", self.on_shift_press)
self.bind("<KeyRelease-Shift_R>", self.on_shift_release)
self.bind("<KeyRelease-Escape>", self.on_escape)
for l in init_log:
self.log(l, noprint=True)
self.log("Welcome back, Commander.", level="important")
self.after(self.tick_interval, self.tick) # one-line setup
def tick(self):
if self.generation_running == False:
if len(self.generation_queue) > 0:
job = self.generation_queue.pop(0)
if job["type"] == "full":
self.run_generation()
elif job["type"] == "incremental":
self.run_generation(job["dirty_list"])
else:
self.log("Unknown generation type", level="error")
self.after(self.tick_interval, self.tick) # reschedule
def update_title(self):
if self.current_preset:
title = f"WorldStack Editor - {self.current_preset}"
else:
title = "WorldStack Editor"
if self.unsaved:
title += " *"
self.title(title)
def set_unsaved(self, flag=True):
self.unsaved = flag
self.update_title()
def set_dirty(self, node:Node=None):
# adds jobs in a consolidated way. yes this means there will only be one job queued now, so it's a queue for no reason
job = {}
if node == None:
self.generation_queue.clear()
job["type"] = "full"
self.generation_queue.append(job)
else:
if any(job.get("type") == "full" for job in self.generation_queue):
return
job["type"] = "incremental"
job["dirty_list"] = [node.properties[outp["name"]] for outp in node.definition.get("outputs", [])]
while len(self.generation_queue):
j = self.generation_queue.pop()
for n in j["dirty_list"]:
if n not in job["dirty_list"]:
job["dirty_list"].append(n)
self.generation_queue.append(job)
# --- Menus ---
def create_menu(self):
menubar = tk.Menu(self)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=self.new_template)
filemenu.add_command(label="Open", command=self.open_template)
filemenu.add_command(label="Save", command=self.save_template)
filemenu.add_command(label="Save As", command=self.save_template_as)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.on_close)
menubar.add_cascade(label="File", menu=filemenu)
settings_menu = tk.Menu(menubar, tearoff=0)
settings_menu.add_command(label="Map Size", command=self.settings_map_size)
menubar.add_cascade(label="Settings", menu=settings_menu)
self.config(menu=menubar)
def settings_map_size(self):
top = tk.Toplevel(self)
top.title("Map Size")
tk.Label(top, text="Select Map Width:").grid(row=0, column=0, padx=5, pady=5)
width_var = tk.IntVar(value=self.map_width)
width_combo = ttk.Combobox(top, textvariable=width_var, values=VALID_MAP_SIZES, state="readonly")
width_combo.grid(row=0, column=1, padx=5, pady=5)
tk.Label(top, text="Select Map Height:").grid(row=1, column=0, padx=5, pady=5)
height_var = tk.IntVar(value=self.map_height)
height_combo = ttk.Combobox(top, textvariable=height_var, values=VALID_MAP_SIZES, state="readonly")
height_combo.grid(row=1, column=1, padx=5, pady=5)
def apply():
self.map_width = width_var.get()
self.map_height = height_var.get()
self.set_unsaved(True)
self.set_dirty()
top.destroy()
tk.Button(top, text="OK", command=apply).grid(row=2, column=0, columnspan=2, pady=10)
def create_toolbar(self):
toolbar = tk.Frame(self, bd=1, relief=tk.RAISED)
go_button = tk.Button(toolbar, text="Regenerate", command=self.run_generation)
go_button.pack(side=tk.LEFT, padx=2, pady=2)
add_node_button = tk.Button(toolbar, text="New Node", command=self.add_node_dialog)
add_node_button.pack(side=tk.LEFT, padx=2, pady=2)
add_node_button = tk.Button(toolbar, text="Delete Node(s)", command=self.delete_selected_node)
add_node_button.pack(side=tk.LEFT, padx=2, pady=2)
add_node_button = tk.Button(toolbar, text="Help", command=self.show_help)
add_node_button.pack(side=tk.LEFT, padx=2, pady=2)
toolbar.pack(side=tk.TOP, fill=tk.X)
def create_ui(self):
# top-level split: main area (left) and sidebar (right)
main_pane = tk.PanedWindow(self, orient=tk.HORIZONTAL)
main_pane.pack(fill=tk.BOTH, expand=True)
# left stack: canvas (top) and console (bottom)
self.content_pane = tk.PanedWindow(main_pane, orient=tk.VERTICAL)
main_pane.add(self.content_pane, stretch="always")
# canvas
self.canvas = tk.Canvas(self.content_pane, bg=self.mainview_bg_color, width=800, height=800)
self.content_pane.add(self.canvas, stretch="always")
# console frame at the bottom
self.console_frame = tk.LabelFrame(self.content_pane, text="Console")
self.console_text = tk.Text(self.console_frame, wrap="word", height=10)
self.console_text.configure(state="disabled")
self.console_text.pack(side="left", fill=tk.BOTH, expand=True)
self.console_scroll = tk.Scrollbar(self.console_frame, orient="vertical",
command=self.console_text.yview)