-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1818 lines (1532 loc) · 84.4 KB
/
main.py
File metadata and controls
1818 lines (1532 loc) · 84.4 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
import kivy
kivy.require('2.1.0') # Or your Kivy version
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle, Line, Ellipse, InstructionGroup
from kivy.utils import get_color_from_hex
from kivy.uix.actionbar import ActionBar, ActionView, ActionPrevious, ActionGroup, ActionButton
from kivy.metrics import dp
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.behaviors import DragBehavior
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty, ListProperty, NumericProperty, DictProperty, ColorProperty
from kivy.uix.stencilview import StencilView
from kivy.animation import Animation
from enum import Enum
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.slider import Slider
from kivy.uix.checkbox import CheckBox
from functools import partial
from kivy.clock import Clock # For animation loop
import random # For potential future use with randomness
import uuid # For generating unique IDs
from kivy.uix.popup import Popup
from kivy.uix.button import Button
# Import from our project
from src.core.ir import EffectIR, EmitterProperties, EmitterParameter, AnimatedParameter, TimelineKeyframe # Add EmitterProperties, EmitterParameter
# Optional: Set a default window size for easier viewing
Window.size = (1280, 720) # width, height
class ParamType(Enum):
FLOAT = float
INT = int
STRING = str
BOOLEAN = bool
COLOR = tuple # Will be represented as (r,g,b,a) using Kivy's ColorProperty for UI
VECTOR2 = tuple # (x,y)
VECTOR3 = tuple # (x,y,z)
FILEPATH = str # Special string type for file paths
# Add more as needed, e.g., TEXTURE, CURVE, GRADIENT
class Parameter:
def __init__(self, name: str, param_type: ParamType, value,
display_name: str = None, default_value=None,
ui_hint: str = None, unit: str = None, **kwargs):
self.name = name # Programmatic name
self.param_type = param_type
self.display_name = display_name if display_name else name.replace('_', ' ').title()
self.value = value
self.default_value = default_value if default_value is not None else value
self.ui_hint = ui_hint # e.g., 'slider', 'color_picker', 'checkbox'
self.unit = unit
self.options = kwargs # For min, max, step, enum_values, etc.
def __repr__(self):
return f"Parameter(name='{self.name}', type={self.param_type.name}, value={self.value}, display='{self.display_name}')"
class Socket(Widget):
node = ObjectProperty(None)
is_output = BooleanProperty(False)
connected_sockets = ListProperty([])
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.size_hint = (None, None)
self.size = (dp(14), dp(14))
# Create socket circle
with self.canvas.before:
Color(rgba=get_color_from_hex('#CCCCCC')) # Light gray for sockets
self.socket_circle = Ellipse(pos=self.pos, size=self.size)
self.bind(pos=self._update_graphics)
self.active_connection = None
self.temp_line = None
self.temp_color = None
self.connection_line = None
self.connection_color = None
def get_socket_pos(self):
"""Get the socket position in window coordinates"""
scatter = self.get_scatter()
if scatter:
# Transform the position through scatter
return scatter.to_window(*self.center)
return self.center
def get_scatter(self):
parent = self.parent
while parent:
if isinstance(parent, ScatterLayout):
return parent
parent = parent.parent
return None
def _update_graphics(self, *args):
self.socket_circle.pos = self.pos
# Update connection lines if any
for connected_socket in self.connected_sockets:
self.update_connection_line(connected_socket)
def update_connection_line(self, other_socket):
if self.connection_line:
start_pos = self.get_socket_pos()
end_pos = other_socket.get_socket_pos()
# Calculate control points for bezier curve
dx = end_pos[0] - start_pos[0]
control1_x = start_pos[0] + dx * 0.5
control1_y = start_pos[1]
control2_x = start_pos[0] + dx * 0.5
control2_y = end_pos[1]
# Update the line
self.connection_line.bezier = [
start_pos[0], start_pos[1],
control1_x, control1_y,
control2_x, control2_y,
end_pos[0], end_pos[1]
]
def on_touch_down(self, touch):
if self.collide_point(*touch.pos) and touch.button == 'left':
touch.grab(self)
# Remove any existing temporary line
self.remove_temp_line()
# Get the socket position in window coordinates
start_pos = self.get_socket_pos()
# Create new temporary line
with self.canvas.after:
self.temp_color = Color(rgba=get_color_from_hex('#AAAAAA'))
self.temp_line = Line(points=[start_pos[0], start_pos[1], touch.x, touch.y], width=dp(2))
return True
return super().on_touch_down(touch)
def on_touch_move(self, touch):
if touch.grab_current is self and self.temp_line:
# Get the socket position in window coordinates
start_pos = self.get_socket_pos()
# Update temporary line to follow cursor exactly
self.temp_line.points = [start_pos[0], start_pos[1], touch.x, touch.y]
return True
return super().on_touch_move(touch)
def remove_temp_line(self):
if self.temp_line:
self.canvas.after.remove(self.temp_line)
self.temp_line = None
if self.temp_color:
self.canvas.after.remove(self.temp_color)
self.temp_color = None
def remove_connection_line(self):
if self.connection_line:
self.canvas.after.remove(self.connection_line)
self.connection_line = None
if self.connection_color:
self.canvas.after.remove(self.connection_color)
self.connection_color = None
def on_touch_up(self, touch):
if touch.grab_current is self:
# Remove temporary line
self.remove_temp_line()
# Find potential connection targets
scatter = self.get_scatter()
if scatter:
for widget in scatter.walk():
if isinstance(widget, Socket) and widget != self:
if widget.collide_point(*widget.to_local(*touch.pos)):
if self.is_output != widget.is_output:
self.connect_to(widget)
break
touch.ungrab(self)
return True
return super().on_touch_up(touch)
def connect_to(self, other_socket):
if other_socket not in self.connected_sockets:
# Clear existing connections
self.remove_connection_line()
for socket in self.connected_sockets:
socket.remove_connection_line()
self.connected_sockets.clear()
other_socket.remove_connection_line()
for socket in other_socket.connected_sockets:
socket.remove_connection_line()
other_socket.connected_sockets.clear()
# Create new connection
self.connected_sockets.append(other_socket)
other_socket.connected_sockets.append(self)
# Get positions in window coordinates
start_pos = self.get_socket_pos()
end_pos = other_socket.get_socket_pos()
# Draw permanent connection line
with self.canvas.after:
self.connection_color = Color(rgba=get_color_from_hex('#E0E0E0'))
self.connection_line = Line(bezier=[
start_pos[0], start_pos[1],
start_pos[0], start_pos[1],
end_pos[0], end_pos[1],
end_pos[0], end_pos[1]
], width=dp(2))
self.update_connection_line(other_socket)
class StencilBoxLayout(BoxLayout, StencilView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Add the gray background to StencilBoxLayout
with self.canvas.before:
Color(rgba=get_color_from_hex('#2A2A2A'))
self.bg_rect = Rectangle(size=self.size, pos=self.pos)
self.bind(pos=self._update_rect, size=self._update_rect)
def _update_rect(self, instance, value):
self.bg_rect.pos = instance.pos
self.bg_rect.size = instance.size
class PlaceholderPanel(BoxLayout):
def __init__(self, text, panel_color_hex='#333333', **kwargs):
super().__init__(**kwargs)
with self.canvas.before:
Color(rgba=get_color_from_hex(panel_color_hex))
self.rect = Rectangle(size=self.size, pos=self.pos)
self.bind(pos=self._update_rect, size=self._update_rect)
self.add_widget(Label(text=text))
def _update_rect(self, instance, value):
self.rect.pos = instance.pos
self.rect.size = instance.size
class Particle:
def __init__(self, pos, color, size, life=1.0, velocity=(0,0)):
self.pos = list(pos)
self.color = tuple(color)
self.size = tuple(size)
self.life = float(life)
self.velocity = list(velocity) # Store velocity
def __repr__(self):
return f"Particle(pos={self.pos}, color={self.color}, life={self.life:.2f}, vel={self.velocity})"
class PreviewWindow(Widget):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.particles = []
self.particle_draw_group = InstructionGroup()
self.current_emitter_node = None
self.emission_rate = 0
self.particle_lifespan = 1.0
self.particle_base_color = (1,1,1,1)
self.particle_initial_velocity = (0,0)
self.particle_emitter_offset = (0,0) # Store emitter position offset
self.emission_debt = 0.0
with self.canvas:
Color(rgba=get_color_from_hex('#252525'))
self.bg_rect = Rectangle(pos=self.pos, size=self.size)
self.canvas.add(self.particle_draw_group)
self.bind(pos=self._update_rect, size=self._update_rect)
self._simulation_event = None
def _update_rect(self, instance, value):
self.bg_rect.pos = self.pos
self.bg_rect.size = self.size
def start_simulation(self, node):
self.stop_simulation()
if not (node and isinstance(node, SourceNode)):
self.draw_particles() # Draw empty if no valid node
return
app = App.get_running_app()
if not (app and hasattr(app, 'effect_ir') and app.effect_ir):
print("Warning: EffectIR not found in app. Preview will not use IR data.")
self.draw_particles()
return
emitter_data = app.effect_ir.get_emitter(node.node_id)
if not emitter_data:
print(f"Warning: EmitterProperties for node '{node.node_id}' not found in EffectIR. Preview might not reflect true state.")
# Fallback or clear: For now, let's clear and not simulate if IR data is missing for the selected node
self.current_emitter_node = None # Ensure no old data is used
self.draw_particles()
return
self.current_emitter_node = node # Still keep a reference to the node for identity, maybe other non-IR uses
# Fetch parameters from EffectIR, considering current_time for animation
current_time = app.current_time
node_id = node.node_id
self.emission_rate = app.effect_ir.get_animated_param_value(node_id, "emission_rate", current_time)
self.particle_lifespan = app.effect_ir.get_animated_param_value(node_id, "lifespan", current_time)
color_val = app.effect_ir.get_animated_param_value(node_id, "particle_color", current_time)
self.particle_base_color = color_val if isinstance(color_val, tuple) and len(color_val) == 4 else (1,1,1,1)
# Debug: Print the color being used
print(f"Preview: Using particle color {self.particle_base_color} from EffectIR at T={current_time:.2f}")
velocity_val = app.effect_ir.get_animated_param_value(node_id, "initial_velocity", current_time)
self.particle_initial_velocity = velocity_val if isinstance(velocity_val, tuple) and len(velocity_val) == 2 else (0,0)
emitter_pos_val = app.effect_ir.get_animated_param_value(node_id, "emitter_position", current_time)
self.particle_emitter_offset = emitter_pos_val if isinstance(emitter_pos_val, tuple) and len(emitter_pos_val) == 2 else (0,0)
print(f"Preview using IR data for '{node.node_id}' at T={current_time:.2f}: Rate={self.emission_rate}, Life={self.particle_lifespan}, Color={self.particle_base_color}")
self.emission_debt = 0.0
if self.emission_rate > 0 or self.particles:
self._simulation_event = Clock.schedule_interval(self.update_simulation, 1.0 / 60.0)
else:
self.draw_particles()
def stop_simulation(self):
if self._simulation_event:
Clock.unschedule(self._simulation_event)
self._simulation_event = None
self.particles.clear()
self.particle_draw_group.clear()
self.current_emitter_node = None
self.emission_debt = 0.0
def update_simulation(self, dt):
if not self.current_emitter_node:
self.stop_simulation()
return
particles_to_emit_float = self.emission_rate * dt + self.emission_debt
num_to_emit = int(particles_to_emit_float)
self.emission_debt = particles_to_emit_float - num_to_emit
particle_size = (dp(10), dp(10))
# Calculate base emission position using the offset
base_pos_x = self.center_x + self.particle_emitter_offset[0]
base_pos_y = self.center_y + self.particle_emitter_offset[1]
for _ in range(num_to_emit):
p = Particle(
pos=(base_pos_x, base_pos_y), # Use base position
color=self.particle_base_color,
size=particle_size,
life=self.particle_lifespan,
velocity=self.particle_initial_velocity
)
self.particles.append(p)
for i in range(len(self.particles) - 1, -1, -1):
p = self.particles[i]
p.life -= dt
p.pos[0] += p.velocity[0] * dt
p.pos[1] += p.velocity[1] * dt
if p.life <= 0:
self.particles.pop(i)
self.draw_particles()
def update_preview(self, node):
if node and isinstance(node, SourceNode):
self.start_simulation(node)
else:
self.stop_simulation()
self.draw_particles()
def draw_particles(self):
self.particle_draw_group.clear()
for p in self.particles:
self.particle_draw_group.add(Color(rgba=p.color))
ellipse_pos = (p.pos[0] - p.size[0] / 2, p.pos[1] - p.size[1] / 2)
self.particle_draw_group.add(Ellipse(pos=ellipse_pos, size=p.size))
class NodeWidget(BoxLayout):
title = StringProperty('Node')
parameters = ListProperty([])
is_selected = BooleanProperty(False)
node_id = StringProperty('')
def __init__(self, title='Node', params_config=None, node_id=None, **kwargs):
super().__init__(**kwargs)
self.title = title
if node_id:
self.node_id = node_id
else:
self.node_id = uuid.uuid4().hex
self.orientation = 'vertical'
self.size_hint = (None, None)
self.size = (dp(180), dp(120))
self._touch_offset_x = 0
self._touch_offset_y = 0
self.parameters = []
if params_config:
for p_name, p_data in params_config.items():
self.add_parameter(
name=p_name,
param_type=p_data.get('type'),
value=p_data.get('value'),
display_name=p_data.get('display_name'),
default_value=p_data.get('default_value'),
ui_hint=p_data.get('ui_hint'),
unit=p_data.get('unit'),
**p_data.get('options', {})
)
with self.canvas.before:
self.border_color_instruction = Color(rgba=get_color_from_hex('#757575'))
self.border_line = Line(rectangle=(self.x, self.y, self.width, self.height), width=1.2)
Color(rgba=get_color_from_hex('#424242'))
self.bg_rect = Rectangle(size=self.size, pos=self.pos)
self.bind(pos=self._update_graphics, size=self._update_graphics, is_selected=self.on_selection_change)
# Create title bar
title_bar = BoxLayout(size_hint_y=None, height=dp(30), padding=(dp(5), dp(2)))
with title_bar.canvas.before:
Color(rgba=get_color_from_hex('#2C2C2C'))
self.title_bg_rect = Rectangle(size=title_bar.size, pos=title_bar.pos)
title_bar.bind(pos=lambda i,p: setattr(self.title_bg_rect, 'pos', p),
size=lambda i,s: setattr(self.title_bg_rect, 'size', s))
title_label = Label(text=self.title, bold=True, shorten=True, ellipsis_options={'markup': True})
title_bar.add_widget(title_label)
self.add_widget(title_bar)
content_area = BoxLayout(padding=dp(5))
input_layout = BoxLayout(orientation='vertical', size_hint_x=None, width=dp(20))
self.input_socket = Socket(is_output=False, node=self)
input_layout.add_widget(Widget())
input_layout.add_widget(self.input_socket)
input_layout.add_widget(Widget())
content_area.add_widget(input_layout)
self.node_content_label = Label(text='Node Content')
content_area.add_widget(self.node_content_label)
output_layout = BoxLayout(orientation='vertical', size_hint_x=None, width=dp(20))
self.output_socket = Socket(is_output=True, node=self)
output_layout.add_widget(Widget())
output_layout.add_widget(self.output_socket)
output_layout.add_widget(Widget())
content_area.add_widget(output_layout)
self.add_widget(content_area)
self.update_node_content_display()
def add_parameter(self, name: str, param_type: ParamType, value,
display_name: str = None, default_value=None,
ui_hint: str = None, unit: str = None, **kwargs):
param = Parameter(name, param_type, value,
display_name=display_name, default_value=default_value,
ui_hint=ui_hint, unit=unit, **kwargs)
self.parameters.append(param)
self.update_node_content_display()
def get_parameter_value(self, name: str):
for param in self.parameters:
if param.name == name:
return param.value
return None
def set_parameter_value(self, name: str, value):
for param in self.parameters:
if param.name == name:
old_value = param.value
param.value = value
print(f"Parameter '{name}' changed from {old_value} to {value}")
self.update_node_content_display()
app = App.get_running_app()
if app:
# Update EffectIR if this node is a source node and has a representation in IR
if isinstance(self, SourceNode) and app.effect_ir:
emitter_data = app.effect_ir.get_emitter(self.node_id)
if emitter_data:
# Ensure the parameter exists in the IR's EmitterProperties parameters dict
if name in emitter_data.parameters:
emitter_data.set_param_value(name, value)
print(f"EffectIR: Updated emitter '{self.node_id}' param '{name}' to: {value}")
else:
# This case should ideally not happen if IR is synced on creation
print(f"Warning: Param '{name}' not found in IR for emitter '{self.node_id}'. Creating it.")
emitter_data.parameters[name] = EmitterParameter(name=name, value=value)
# Or, more strictly, only update if it exists, depends on design
else:
print(f"Warning: EmitterProperties for node '{self.node_id}' not found in EffectIR.")
# Existing notification for UI/Preview updates
app.notify_parameter_changed(self, param.name)
return True
return False
def update_node_content_display(self):
if hasattr(self, 'node_content_label'):
if self.parameters:
param_texts = [f"{p.display_name}: {p.value}{' ' + p.unit if p.unit else ''}" for p in self.parameters[:2]]
self.node_content_label.text = "\n".join(param_texts)
else:
self.node_content_label.text = "(No Params)"
def on_selection_change(self, instance, value):
if value:
self.border_color_instruction.rgba = get_color_from_hex('#FFFFFF')
else:
self.border_color_instruction.rgba = get_color_from_hex('#757575')
self._update_graphics(self, self.pos)
def _update_graphics(self, instance, value):
self.bg_rect.pos = instance.pos
self.bg_rect.size = instance.size
self.border_line.rectangle = (instance.x, instance.y, instance.width, instance.height)
if hasattr(self, 'input_socket'):
for connected_socket in self.input_socket.connected_sockets:
self.input_socket.update_connection_line(connected_socket)
if hasattr(self, 'output_socket'):
for connected_socket in self.output_socket.connected_sockets:
self.output_socket.update_connection_line(connected_socket)
def get_scatter_pos(self, pos):
scatter = self.get_scatter()
if scatter:
return scatter.to_local(*pos)
return pos
def get_scatter(self):
parent = self.parent
while parent:
if isinstance(parent, ScatterLayout):
return parent
parent = parent.parent
return None
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
if (hasattr(self, 'input_socket') and self.input_socket.collide_point(*self.input_socket.to_local(*touch.pos))) or \
(hasattr(self, 'output_socket') and self.output_socket.collide_point(*self.output_socket.to_local(*touch.pos))):
return super().on_touch_down(touch)
app = App.get_running_app()
if app:
app.select_node(self)
touch.grab(self)
self._touch_offset_x = self.x - touch.x
self._touch_offset_y = self.y - touch.y
return True
return super().on_touch_down(touch)
def on_touch_move(self, touch):
if touch.grab_current is self:
new_x = touch.x + self._touch_offset_x
new_y = touch.y + self._touch_offset_y
self.pos = (new_x, new_y)
if hasattr(self, 'input_socket'):
for connected_socket in self.input_socket.connected_sockets:
self.input_socket.update_connection_line(connected_socket)
connected_socket.update_connection_line(self.input_socket)
if hasattr(self, 'output_socket'):
for connected_socket in self.output_socket.connected_sockets:
self.output_socket.update_connection_line(connected_socket)
connected_socket.update_connection_line(self.output_socket)
return True
return super().on_touch_move(touch)
def on_touch_up(self, touch):
if touch.grab_current is self:
touch.ungrab(self)
return True
return super().on_touch_up(touch)
# --- Concrete Node Type Classes ---
class SourceNode(NodeWidget):
def __init__(self, **kwargs):
if 'node_id' not in kwargs:
kwargs['node_id'] = uuid.uuid4().hex
base_params_config = {
"emission_rate": {
"type": ParamType.FLOAT, "value": 10.0, "default_value": 10.0,
"display_name": "Emission Rate", "ui_hint": "slider", "unit": "p/s",
"options": {"min": 0.0, "max": 100.0, "step": 0.1}
},
"lifespan": {
"type": ParamType.FLOAT, "value": 2.0, "default_value": 2.0,
"display_name": "Lifespan", "ui_hint": "slider", "unit": "s",
"options": {"min": 0.1, "max": 10.0, "step": 0.05}
},
"particle_color": {
"type": ParamType.COLOR, "value": (1.0, 1.0, 0.0, 1.0),
"default_value": (1.0, 1.0, 0.0, 1.0), "display_name": "Particle Color",
"ui_hint": "color_picker"
},
"initial_velocity": {
"type": ParamType.VECTOR2,
"value": (0.0, 100.0),
"default_value": (0.0, 100.0),
"display_name": "Initial Velocity",
"unit": "px/s"
},
"emitter_position": {
"type": ParamType.VECTOR2,
"value": (0.0, 0.0), # Offset from PreviewWindow center
"default_value": (0.0, 0.0),
"display_name": "Emitter Position Offset",
"unit": "px"
}
}
super().__init__(title='Source', params_config=base_params_config, **kwargs)
app = App.get_running_app()
if app and hasattr(app, 'effect_ir') and app.effect_ir:
ir_emitter_params = {}
for p_name, p_data in base_params_config.items():
ir_emitter_params[p_name] = EmitterParameter(
name=p_name,
value=p_data.get('value')
)
emitter_props = EmitterProperties(
emitter_id=self.node_id,
emitter_type="SourceParticleEmitter",
name=self.title,
parameters=ir_emitter_params
)
app.effect_ir.add_emitter(emitter_props)
print(f"SourceNode '{self.node_id}' added EmitterProperties to EffectIR: {emitter_props}")
# Add mock animation data for this new emitter's emission_rate for testing
if self.node_id == app.effect_ir.emitters[0].emitter_id: # Only for the first source node for predictability
rate_anim_path = f"{self.node_id}/emission_rate"
rate_anim = AnimatedParameter(
keyframes=[
TimelineKeyframe(time=0.0, value=5.0),
TimelineKeyframe(time=app.effect_ir.loop_duration / 2, value=50.0),
TimelineKeyframe(time=app.effect_ir.loop_duration, value=5.0)
]
)
app.effect_ir.add_or_update_timeline(rate_anim_path, rate_anim)
print(f"Added mock emission_rate animation for '{self.node_id}'")
else:
print(f"Warning: Could not register SourceNode '{self.node_id}' with EffectIR (App or EffectIR not found).")
class DisplayNode(NodeWidget):
def __init__(self, **kwargs):
# Define any parameters specific to a DisplayNode (maybe blend mode, etc. later)
params_config = {
"display_name_param": {
"type": ParamType.STRING,
"value": "Default Display",
"display_name": "Display Name"
}
}
super().__init__(title='Display', params_config=params_config, **kwargs)
# --- Color Picker Popup --- #
class ColorPickerPopup(Popup):
@staticmethod
def rgb_to_hsv(r, g, b):
"""Convert RGB to HSV. RGB values should be 0-1."""
max_val = max(r, g, b)
min_val = min(r, g, b)
diff = max_val - min_val
# Value
v = max_val
# Saturation
if max_val == 0:
s = 0
else:
s = diff / max_val
# Hue
if diff == 0:
h = 0
elif max_val == r:
h = (60 * ((g - b) / diff) + 360) % 360
elif max_val == g:
h = (60 * ((b - r) / diff) + 120) % 360
elif max_val == b:
h = (60 * ((r - g) / diff) + 240) % 360
return h / 360.0, s, v # Return h as 0-1 to match Kivy's expected format
@staticmethod
def hsv_to_rgb(h, s, v):
"""Convert HSV to RGB. H should be 0-1, S and V should be 0-1."""
h = h * 360 # Convert back to 0-360 for calculation
c = v * s
x = c * (1 - abs((h / 60) % 2 - 1))
m = v - c
if 0 <= h < 60:
r, g, b = c, x, 0
elif 60 <= h < 120:
r, g, b = x, c, 0
elif 120 <= h < 180:
r, g, b = 0, c, x
elif 180 <= h < 240:
r, g, b = 0, x, c
elif 240 <= h < 300:
r, g, b = x, 0, c
elif 300 <= h < 360:
r, g, b = c, 0, x
else:
r, g, b = 0, 0, 0
return r + m, g + m, b + m
def __init__(self, initial_color=(1,1,1,1), callback=None, **kwargs):
super().__init__(**kwargs)
self.title = "Select Color"
self.size_hint = (None, None)
self.size = (dp(450), dp(400))
self.auto_dismiss = False # User must click OK or Cancel
self.initial_color = list(initial_color) # RGBA
self.current_color_rgba = list(initial_color) # RGBA
# Use our own RGB to HSV conversion
h, s, v = self.rgb_to_hsv(*initial_color[:3])
self.current_color_hsv = [h, s, v, initial_color[3]] # HSVA
self.callback = callback
# Main layout for the popup content
popup_content_layout = BoxLayout(orientation='vertical', padding=dp(10), spacing=dp(10))
# Top section: Swatches and Hex/RGB input
top_section = BoxLayout(size_hint_y=0.3, spacing=dp(10))
# Swatches (Current and Initial)
swatches_layout = BoxLayout(orientation='vertical', size_hint_x=0.3, spacing=dp(5))
self.current_swatch = Widget()
with self.current_swatch.canvas:
self.current_swatch_color_instr = Color(rgba=self.current_color_rgba)
self.current_swatch_rect = Rectangle(size=self.current_swatch.size, pos=self.current_swatch.pos)
self.current_swatch.bind(pos=self._update_swatch_rect, size=self._update_swatch_rect)
initial_swatch_label = Label(text="Initial", size_hint_y=0.2)
self.initial_swatch = Widget()
with self.initial_swatch.canvas:
Color(rgba=self.initial_color)
self.initial_swatch_rect = Rectangle(size=self.initial_swatch.size, pos=self.initial_swatch.pos)
self.initial_swatch.bind(pos=self._update_initial_swatch_rect, size=self._update_initial_swatch_rect)
swatches_layout.add_widget(Label(text="Current", size_hint_y=0.2))
swatches_layout.add_widget(self.current_swatch)
swatches_layout.add_widget(initial_swatch_label)
swatches_layout.add_widget(self.initial_swatch)
top_section.add_widget(swatches_layout)
# RGB and Hex inputs
rgb_hex_layout = GridLayout(cols=2, size_hint_x=0.7, spacing=dp(5), padding=(0, dp(10)))
rgb_hex_layout.add_widget(Label(text="R (0-1):"))
self.r_input = TextInput(text=f"{self.current_color_rgba[0]:.2f}", multiline=False)
rgb_hex_layout.add_widget(self.r_input)
rgb_hex_layout.add_widget(Label(text="G (0-1):"))
self.g_input = TextInput(text=f"{self.current_color_rgba[1]:.2f}", multiline=False)
rgb_hex_layout.add_widget(self.g_input)
rgb_hex_layout.add_widget(Label(text="B (0-1):"))
self.b_input = TextInput(text=f"{self.current_color_rgba[2]:.2f}", multiline=False)
rgb_hex_layout.add_widget(self.b_input)
rgb_hex_layout.add_widget(Label(text="Hex (RRGGBBAA):"))
hex_color = get_color_from_hex(self._rgba_to_hex(self.current_color_rgba)) # This might be redundant, direct hex string needed
self.hex_input = TextInput(text=self._rgba_to_hex(self.current_color_rgba)[1:], multiline=False) # Remove #
rgb_hex_layout.add_widget(self.hex_input)
top_section.add_widget(rgb_hex_layout)
popup_content_layout.add_widget(top_section)
# HSV and Alpha Sliders
sliders_layout = GridLayout(cols=2, size_hint_y=0.5, spacing=dp(5))
sliders_layout.add_widget(Label(text="Hue (0-360):"))
self.h_slider = Slider(min=0, max=360, value=self.current_color_hsv[0]*360)
sliders_layout.add_widget(self.h_slider)
sliders_layout.add_widget(Label(text="Sat (0-1):"))
self.s_slider = Slider(min=0, max=1, value=self.current_color_hsv[1])
sliders_layout.add_widget(self.s_slider)
sliders_layout.add_widget(Label(text="Val (0-1):"))
self.v_slider = Slider(min=0, max=1, value=self.current_color_hsv[2])
sliders_layout.add_widget(self.v_slider)
sliders_layout.add_widget(Label(text="Alpha (0-1):"))
self.a_slider = Slider(min=0, max=1, value=self.current_color_rgba[3])
sliders_layout.add_widget(self.a_slider)
popup_content_layout.add_widget(sliders_layout)
# Bindings for sliders and inputs to update methods
self.h_slider.bind(value=self._on_hsv_alpha_slider_change)
self.s_slider.bind(value=self._on_hsv_alpha_slider_change)
self.v_slider.bind(value=self._on_hsv_alpha_slider_change)
self.a_slider.bind(value=self._on_hsv_alpha_slider_change)
self.r_input.bind(text=self._on_rgb_input_change)
self.g_input.bind(text=self._on_rgb_input_change)
self.b_input.bind(text=self._on_rgb_input_change)
self.hex_input.bind(text=self._on_hex_input_change)
# OK and Cancel buttons
buttons_layout = BoxLayout(size_hint_y=0.15, spacing=dp(10))
ok_button = Button(text="OK")
ok_button.bind(on_release=self._on_ok)
cancel_button = Button(text="Cancel")
cancel_button.bind(on_release=self.dismiss)
buttons_layout.add_widget(Widget(size_hint_x=0.5)) # Spacer
buttons_layout.add_widget(ok_button)
buttons_layout.add_widget(cancel_button)
buttons_layout.add_widget(Widget(size_hint_x=0.5)) # Spacer
popup_content_layout.add_widget(buttons_layout)
self.content = popup_content_layout
self._update_ui_from_current_color(source='init') # Initial UI sync
def _rgba_to_hex(self, rgba_color):
r, g, b, a_float = rgba_color
return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}{int(a_float*255):02x}"
def _hex_to_rgba(self, hex_color_str):
hex_color_str = hex_color_str.lstrip('#')
if len(hex_color_str) == 6:
hex_color_str += "ff" # Assume full alpha if not provided
if len(hex_color_str) != 8:
return None # Invalid hex
try:
r = int(hex_color_str[0:2], 16) / 255.0
g = int(hex_color_str[2:4], 16) / 255.0
b = int(hex_color_str[4:6], 16) / 255.0
a = int(hex_color_str[6:8], 16) / 255.0
return [r,g,b,a]
except ValueError:
return None
def _update_swatch_rect(self, instance, value):
self.current_swatch_rect.pos = instance.pos
self.current_swatch_rect.size = instance.size
def _update_initial_swatch_rect(self, instance, value):
self.initial_swatch_rect.pos = instance.pos
self.initial_swatch_rect.size = instance.size
def _update_color_internals(self, new_rgba, source_of_change):
"""Updates internal RGBA and HSVA representations and the UI elements."""
self.current_color_rgba = list(new_rgba)
# Update HSV from RGB (excluding alpha, which is handled separately by its slider)
rgb_for_hsv = self.current_color_rgba[:3]
# Use our own RGB to HSV conversion
h, s, v = self.rgb_to_hsv(*rgb_for_hsv)
self.current_color_hsv = [h, s, v, self.current_color_rgba[3]]
self._update_ui_from_current_color(source=source_of_change)
def _update_ui_from_current_color(self, source='unknown'):
"""Updates all UI elements based on self.current_color_rgba and self.current_color_hsv."""
# Update Sliders if they were not the source of change
if source != 'sliders':
self.h_slider.value = self.current_color_hsv[0] * 360
self.s_slider.value = self.current_color_hsv[1]
self.v_slider.value = self.current_color_hsv[2]
self.a_slider.value = self.current_color_rgba[3]
# Update RGB inputs if they were not the source of change
if source != 'rgb_inputs':
self.r_input.text = f"{self.current_color_rgba[0]:.2f}"
self.g_input.text = f"{self.current_color_rgba[1]:.2f}"
self.b_input.text = f"{self.current_color_rgba[2]:.2f}"
# Update Hex input if it was not the source of change
if source != 'hex_input':
self.hex_input.text = self._rgba_to_hex(self.current_color_rgba)[1:9] # RRGGBBAA without #
# Update current color swatch
self.current_swatch_color_instr.rgba = tuple(self.current_color_rgba)
def _on_hsv_alpha_slider_change(self, instance, value):
h = self.h_slider.value / 360.0
s = self.s_slider.value
v = self.v_slider.value
alpha = self.a_slider.value
# Use our own HSV to RGB conversion
r, g, b = self.hsv_to_rgb(h, s, v)
new_rgba = [r, g, b, alpha]
self._update_color_internals(new_rgba, source_of_change='sliders')
def _on_rgb_input_change(self, instance, value):
try:
r = float(self.r_input.text)
g = float(self.g_input.text)
b = float(self.b_input.text)
a = self.current_color_rgba[3] # Keep current alpha from slider/previous state
r = max(0.0, min(1.0, r))
g = max(0.0, min(1.0, g))
b = max(0.0, min(1.0, b))
new_rgba = [r,g,b,a]
self._update_color_internals(new_rgba, source_of_change='rgb_inputs')
except ValueError:
pass # Ignore if text is not a valid float yet
def _on_hex_input_change(self, instance, value):
# Ensure it's 6 or 8 chars for RRGGBB or RRGGBBAA
if len(value) == 6 or len(value) == 8:
rgba = self._hex_to_rgba(value)
if rgba:
self._update_color_internals(rgba, source_of_change='hex_input')
# No update if hex is partially typed and invalid
def _on_ok(self, instance):
if self.callback:
self.callback(tuple(self.current_color_rgba))
self.dismiss()
# --- InspectorPanel modifications needed next ---
# In InspectorPanel.observe_node, for ParamType.COLOR:
# 1. Remove the old color layout (BoxLayout with 4 TextInputs).
# 2. Add a small Widget to show the current color (non-interactive swatch).
# 3. Add a Button (e.g., text="Edit Color" or shows hex code).
# 4. Button on_release: create and open ColorPickerPopup instance.
# - Pass current param color to popup.
# - Pass a callback to popup that does: node.set_parameter_value(param.name, new_color) and updates swatch in inspector.
class InspectorPanel(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.orientation = 'vertical'
self.padding = dp(5)
self.spacing = dp(5)
title_label = Label(text="Inspector", size_hint_y=None, height=dp(30), bold=True)
self.add_widget(title_label)
self.scroll_view = ScrollView(size_hint=(1, 1))
self.params_layout = GridLayout(
cols=2,
spacing=dp(5),
size_hint_y=None
)
self.params_layout.bind(minimum_height=self.params_layout.setter('height'))
self.scroll_view.add_widget(self.params_layout)
self.add_widget(self.scroll_view)
self.observed_node = None
# Clear old swatch instructions if any, to prevent memory leaks with Color objects
if hasattr(self, 'inspector_color_swatches'):
del self.inspector_color_swatches # Or iterate and properly manage canvas instructions
self.inspector_color_swatches = {} # param_name: {swatch_widget, color_instr}
def observe_node(self, node):
self.params_layout.clear_widgets()
self.observed_node = node
if not node:
no_node_label = Label(text="No node selected.", size_hint_y=None, height=dp(30))
self.params_layout.add_widget(no_node_label)
self.params_layout.add_widget(Widget(size_hint_y=None, height=dp(30))) # Spacer
return
if not node.parameters:
no_params_label = Label(text="Node has no parameters.", size_hint_y=None, height=dp(30))
self.params_layout.add_widget(no_params_label)
self.params_layout.add_widget(Widget(size_hint_y=None, height=dp(30))) # Spacer
return
for param in node.parameters:
name_label = Label(
text=f"{param.display_name}:",
size_hint_y=None, height=dp(30),
halign='right', valign='middle'
)
name_label.bind(size=name_label.setter('text_size'))
self.params_layout.add_widget(name_label)
editor_widget = None
param_value_str = str(param.value)
unit_suffix = f" {param.unit}" if param.unit else ""
if param.param_type == ParamType.FLOAT or param.param_type == ParamType.INT:
if param.ui_hint == 'slider' and 'min' in param.options and 'max' in param.options:
slider_layout = BoxLayout(orientation='horizontal', size_hint_y=None, height=dp(30))
current_val_label = Label(text=f"{param.value:.2f}{unit_suffix}", size_hint_x=0.3)
slider = Slider(
min=param.options.get('min', 0),
max=param.options.get('max', 1),