-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLayerEditorWindow.xaml.cs
More file actions
2454 lines (2100 loc) · 80.3 KB
/
LayerEditorWindow.xaml.cs
File metadata and controls
2454 lines (2100 loc) · 80.3 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Win32;
namespace lifeviz;
public partial class LayerEditorWindow : Window
{
private readonly MainWindow _owner;
private readonly LayerEditorViewModel _viewModel;
private LayerEditorProjectSettings? _pendingProjectSettings;
private bool _ownerIsShuttingDown;
private bool _suppressLiveUpdates;
private bool _suppressSimulationLayerBindingApply;
private bool _updatingSelection;
private bool _updatingVideoTransportUi;
private Point _dragStartPoint;
private LayerEditorSource? _draggedSource;
private readonly DispatcherTimer _videoTransportTimer;
private static readonly JsonSerializerOptions LayerConfigJsonOptions = new() { WriteIndented = true };
public LayerEditorWindow(MainWindow owner)
{
InitializeComponent();
_owner = owner;
if (owner.IsLoaded || owner.IsVisible)
{
Owner = owner;
}
_viewModel = new LayerEditorViewModel();
DataContext = _viewModel;
RefreshMasterAudioState();
RefreshFromSources();
UpdateApplyState();
_videoTransportTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(250)
};
_videoTransportTimer.Tick += (_, _) => RefreshSelectedVideoTransportState();
_videoTransportTimer.Start();
Closed += (_, _) => _videoTransportTimer.Stop();
}
public void PrepareForOwnerShutdown()
{
_ownerIsShuttingDown = true;
_suppressLiveUpdates = true;
_pendingProjectSettings = null;
_videoTransportTimer.Stop();
}
public void RefreshFromSourcesIfLive()
{
if (_ownerIsShuttingDown || !_viewModel.LiveMode)
{
return;
}
RefreshFromSources();
}
internal void SetLiveModeForSmoke(bool enabled)
{
LiveModeCheckBox.IsChecked = enabled;
}
internal void ApplySimulationHeightForSmoke(int height, bool applyImmediately)
{
int normalizedHeight = NormalizeSimulationHeight(height);
SimulationHeightComboBox.SelectedItem = normalizedHeight;
SimulationHeight_DropDownClosed(SimulationHeightComboBox, EventArgs.Empty);
if (applyImmediately)
{
ApplyButton_Click(ApplyButton, new RoutedEventArgs(Button.ClickEvent, ApplyButton));
}
}
internal bool RunSimulationLayerReactiveIsolationSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
var first = simulationSource?.SimulationLayers.FirstOrDefault();
if (simulationSource == null || first == null)
{
return false;
}
first.ReactiveMappings.Clear();
first.ReactiveMappings.Add(new LayerEditorSimulationReactiveMapping
{
Id = Guid.NewGuid(),
Input = nameof(SimulationReactiveInput.Level),
Output = nameof(SimulationReactiveOutput.Opacity),
Amount = 1.0
});
first.AudioFrequencyHueShiftDegrees = 90;
SetSelectedSource(simulationSource);
SetSelectedSimulationLayer(first);
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
bool reactiveUiVisible = SelectedSimulationReactiveMappingsGroupBox.IsVisible &&
SelectedSimulationAddReactiveMappingButton.IsVisible &&
SelectedSimulationReactiveMappingsGroupBox.DataContext is LayerEditorSimulationLayer visibleLayer &&
visibleLayer.Id == first.Id;
AddSimulationLayer(LayerEditorSimulationLayerType.Life);
var second = GetSelectedSimulationLayer();
if (second == null || ReferenceEquals(second, first))
{
return false;
}
bool newLayerDidNotInherit = second.ReactiveMappings.Count == 0 &&
second.AudioFrequencyHueShiftDegrees == 0 &&
first.ReactiveMappings.Count == 1;
return reactiveUiVisible && newLayerDidNotInherit;
}
internal bool RunSimGroupSelectionSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
if (simulationSource == null)
{
Logger.Warn("Sim-group selection smoke: no simulation group source found.");
return false;
}
UpdateLayout();
SceneTree.UpdateLayout();
var container = FindTreeViewItem(SceneTree, simulationSource);
if (container == null)
{
Logger.Warn($"Sim-group selection smoke: could not find tree container for {DescribeSource(simulationSource)}.");
return false;
}
TraceSelection($"Smoke selecting scene-tree item {DescribeSource(simulationSource)}");
container.IsSelected = true;
container.Focus();
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
TraceSelection($"Smoke selected source -> {DescribeSource(_viewModel.SelectedSource)}");
return _viewModel.SelectedSource?.Id == simulationSource.Id;
}
internal bool RunSimGroupLiveEditSelectionSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
var selectedLayer = simulationSource?.SimulationLayers.FirstOrDefault(layer => !layer.IsGroup) ?? simulationSource?.SimulationLayers.FirstOrDefault();
if (simulationSource == null || selectedLayer == null)
{
Logger.Warn("Sim-group live-edit selection smoke: missing sim-group source or child layer.");
return false;
}
SetSelectedSource(simulationSource);
SetSelectedSimulationLayer(selectedLayer);
TraceSelection($"Smoke pre-edit source={DescribeSource(_viewModel.SelectedSource)} layer={DescribeSimulationLayer(GetSelectedSimulationLayer())}");
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
double nextThreshold = Math.Clamp(selectedLayer.ThresholdMin + 0.01, 0, selectedLayer.ThresholdMax);
SelectedSimulationThresholdMinSlider.Value = nextThreshold;
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
TraceSelection($"Smoke post-edit source={DescribeSource(_viewModel.SelectedSource)} layer={DescribeSimulationLayer(GetSelectedSimulationLayer())}");
bool runtimeUpdated = _owner.TryGetSimulationLayerThresholdMinForSmoke(selectedLayer.Id, out var runtimeThresholdMin) &&
Math.Abs(runtimeThresholdMin - nextThreshold) < 0.0001;
return _viewModel.SelectedSource?.Id == simulationSource.Id && runtimeUpdated;
}
internal bool RunSimGroupEnabledToggleSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
var selectedLayer = simulationSource?.SimulationLayers.FirstOrDefault(layer => !layer.IsGroup);
if (simulationSource == null || selectedLayer == null)
{
Logger.Warn("Sim-group enabled toggle smoke: missing sim-group source or child layer.");
return false;
}
SetSelectedSource(simulationSource);
SetSelectedSimulationLayer(selectedLayer);
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
var before = _owner.GetSimulationLayerCountsForSmoke();
bool targetState = !selectedLayer.Enabled;
SelectedSimulationEnabledCheckBox.IsChecked = targetState;
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
var after = _owner.GetSimulationLayerCountsForSmoke();
bool expectedChanged = targetState ? after.enabledLayers == before.enabledLayers + 1 : after.enabledLayers == before.enabledLayers - 1;
TraceSelection(
$"Smoke enabled-toggle source={DescribeSource(_viewModel.SelectedSource)} layer={DescribeSimulationLayer(GetSelectedSimulationLayer())} " +
$"before=({before.totalLayers},{before.enabledLayers}) after=({after.totalLayers},{after.enabledLayers}) targetState={targetState}");
return _viewModel.SelectedSource?.Id == simulationSource.Id && after.totalLayers == before.totalLayers && expectedChanged;
}
internal bool RunSimGroupRemoveSourceSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
if (simulationSource == null)
{
Logger.Warn("Sim-group remove-source smoke: missing sim-group source.");
return false;
}
SetSelectedSource(simulationSource);
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
SceneRemoveSourceButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, SceneRemoveSourceButton));
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
bool sourceRemoved = EnumerateSources(_viewModel.Sources).All(source => source.Id != simulationSource.Id);
var after = _owner.GetSimulationLayerCountsForSmoke();
TraceSelection(
$"Smoke remove-source removed={sourceRemoved} runtime=({after.totalLayers},{after.enabledLayers}) selected={DescribeSource(_viewModel.SelectedSource)}");
return sourceRemoved && after.totalLayers == 0 && after.enabledLayers == 0;
}
internal bool RunPixelSortEditorRoundTripSmoke()
{
RefreshFromSources();
var simulationSource = EnsureSimulationSourceForSmoke();
if (simulationSource == null)
{
Logger.Warn("Pixel-sort editor round-trip smoke: missing sim-group source.");
return false;
}
SetSelectedSource(simulationSource);
AddSimulationLayer(LayerEditorSimulationLayerType.PixelSort);
var addedLayer = GetSelectedSimulationLayer();
if (addedLayer == null)
{
Logger.Warn("Pixel-sort editor round-trip smoke: add did not select a new layer.");
return false;
}
Guid addedLayerId = addedLayer.Id;
addedLayer.PixelSortCellWidth = 19;
addedLayer.PixelSortCellHeight = 11;
ApplySimulationLayerSettingsLive(force: true);
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
bool runtimeBeforeRefreshOk = _owner.TryGetSimulationLayerRuntimeInfoForSmoke(
addedLayerId,
out var runtimeTypeBeforeRefresh,
out var runtimeColumnsBeforeRefresh,
out var runtimeRowsBeforeRefresh) &&
string.Equals(runtimeTypeBeforeRefresh, "PixelSort", StringComparison.Ordinal) &&
runtimeColumnsBeforeRefresh == 19 &&
runtimeRowsBeforeRefresh == 11;
RefreshFromSources(simulationSource.Id);
var refreshedSource = EnumerateSources(_viewModel.Sources).FirstOrDefault(source => source.Id == simulationSource.Id);
var refreshedLayer = refreshedSource == null ? null : FindSimulationLayerById(refreshedSource.SimulationLayers, addedLayerId);
bool editorRefreshOk = refreshedLayer?.LayerType == LayerEditorSimulationLayerType.PixelSort &&
refreshedLayer.PixelSortCellWidth == 19 &&
refreshedLayer.PixelSortCellHeight == 11;
bool runtimeAfterRefreshOk = _owner.TryGetSimulationLayerRuntimeInfoForSmoke(
addedLayerId,
out var runtimeTypeAfterRefresh,
out var runtimeColumnsAfterRefresh,
out var runtimeRowsAfterRefresh) &&
string.Equals(runtimeTypeAfterRefresh, "PixelSort", StringComparison.Ordinal) &&
runtimeColumnsAfterRefresh == 19 &&
runtimeRowsAfterRefresh == 11;
Logger.Info(
$"Pixel-sort editor round-trip smoke: runtimeBeforeRefresh={runtimeBeforeRefreshOk}, " +
$"editorRefresh={editorRefreshOk}, runtimeAfterRefresh={runtimeAfterRefreshOk}.");
return runtimeBeforeRefreshOk && editorRefreshOk && runtimeAfterRefreshOk;
}
private LayerEditorSource? EnsureSimulationSourceForSmoke()
{
var simulationSource = EnumerateSources(_viewModel.Sources).FirstOrDefault(source => source.IsSimulationGroup);
if (simulationSource != null)
{
return simulationSource;
}
if (!_viewModel.Sources.Any())
{
_owner.AddLayerGroupFromEditor(null);
RefreshFromSources();
}
_owner.AddSimulationGroupFromEditor(null);
RefreshFromSources();
simulationSource = EnumerateSources(_viewModel.Sources).FirstOrDefault(source => source.IsSimulationGroup);
if (simulationSource != null && simulationSource.SimulationLayers.Count == 0)
{
SetSelectedSource(simulationSource);
AddSimulationLayer(LayerEditorSimulationLayerType.Life);
Dispatcher.Invoke(() => { }, DispatcherPriority.Background);
simulationSource = EnumerateSources(_viewModel.Sources).FirstOrDefault(source => source.IsSimulationGroup);
}
return simulationSource;
}
private void RefreshFromSources(Guid? preferredSelectionId = null)
{
var expandedIds = CollectExpandedIds(_viewModel.Sources);
var selectedSimulationLayerIds = CollectSelectedSimulationLayerIds(_viewModel.Sources);
Guid? selectedId = preferredSelectionId ?? _viewModel.SelectedSource?.Id;
_suppressLiveUpdates = true;
try
{
var sources = _owner.BuildLayerEditorSources();
ApplyExpandedState(sources, expandedIds);
ApplySelectedSimulationLayerState(sources, selectedSimulationLayerIds);
_viewModel.Sources = new ObservableCollection<LayerEditorSource>(sources);
LayerEditorSource? selected = null;
if (selectedId.HasValue)
{
selected = FindSourceById(_viewModel.Sources, selectedId.Value);
if (selected == null)
{
TraceSelection($"RefreshFromSources could not find preferred source id={selectedId.Value}");
}
}
selected ??= _viewModel.Sources.FirstOrDefault();
SetSelectedSource(selected);
TraceSelection($"RefreshFromSources selected={DescribeSource(selected)} preferred={preferredSelectionId}");
RefreshMasterAudioState();
RefreshProjectSettingsState();
RefreshSelectedVideoTransportState();
_pendingProjectSettings = null;
}
finally
{
_suppressLiveUpdates = false;
}
}
private void RefreshMasterAudioState()
{
_viewModel.SourceAudioMasterEnabled = _owner.GetSourceAudioMasterEnabled();
_viewModel.SourceAudioMasterVolume = _owner.GetSourceAudioMasterVolume();
}
private void RefreshProjectSettingsState()
{
var projectSettings = _pendingProjectSettings ?? _owner.GetProjectSettingsForEditor();
_viewModel.SimulationHeight = projectSettings.Height;
_viewModel.SimulationDepth = projectSettings.Depth;
_viewModel.SimulationFramerate = projectSettings.Framerate;
_viewModel.GlobalSimulationLifeOpacity = projectSettings.LifeOpacity;
}
private static HashSet<Guid> CollectExpandedIds(IEnumerable<LayerEditorSource> roots)
{
var ids = new HashSet<Guid>();
foreach (var source in EnumerateSources(roots))
{
if (source.IsExpanded)
{
ids.Add(source.Id);
}
}
return ids;
}
private static void ApplyExpandedState(IEnumerable<LayerEditorSource> roots, ISet<Guid> expandedIds)
{
foreach (var source in EnumerateSources(roots))
{
source.IsExpanded = expandedIds.Contains(source.Id);
}
}
private static Dictionary<Guid, Guid> CollectSelectedSimulationLayerIds(IEnumerable<LayerEditorSource> roots)
{
var ids = new Dictionary<Guid, Guid>();
foreach (var source in EnumerateSources(roots))
{
if (source.IsSimulationGroup && source.SelectedSimulationLayer != null)
{
ids[source.Id] = source.SelectedSimulationLayer.Id;
}
}
return ids;
}
private static void ApplySelectedSimulationLayerState(IEnumerable<LayerEditorSource> roots, IReadOnlyDictionary<Guid, Guid> selectedLayerIds)
{
foreach (var source in EnumerateSources(roots))
{
if (!source.IsSimulationGroup || !selectedLayerIds.TryGetValue(source.Id, out var selectedLayerId))
{
continue;
}
var selectedLayer = FindSimulationLayerById(source.SimulationLayers, selectedLayerId);
if (selectedLayer == null)
{
continue;
}
source.SelectedSimulationLayer = selectedLayer;
selectedLayer.IsSelected = true;
}
}
private static IEnumerable<LayerEditorSource> EnumerateSources(IEnumerable<LayerEditorSource> roots)
{
foreach (var source in roots)
{
yield return source;
foreach (var child in EnumerateSources(source.Children))
{
yield return child;
}
}
}
private static LayerEditorSource? FindSourceById(IEnumerable<LayerEditorSource> roots, Guid id) =>
EnumerateSources(roots).FirstOrDefault(source => source.Id == id);
private void SetSelectedSource(LayerEditorSource? source)
{
if (ReferenceEquals(_viewModel.SelectedSource, source))
{
TraceSelection($"SetSelectedSource noop {DescribeSource(source)}");
return;
}
_updatingSelection = true;
try
{
if (_viewModel.SelectedSource != null)
{
_viewModel.SelectedSource.IsSelected = false;
}
_viewModel.SelectedSource = source;
if (_viewModel.SelectedSource != null)
{
_viewModel.SelectedSource.IsSelected = true;
}
TraceSelection($"SetSelectedSource -> {DescribeSource(_viewModel.SelectedSource)}");
}
finally
{
_updatingSelection = false;
}
}
private static LayerEditorSimulationLayer CloneSimulationLayer(LayerEditorSimulationLayer source)
{
var clone = new LayerEditorSimulationLayer
{
Id = source.Id,
Kind = source.Kind,
LayerType = source.LayerType,
Name = source.Name,
Enabled = source.Enabled,
InputFunction = source.InputFunction,
BlendMode = source.BlendMode,
InjectionMode = source.InjectionMode,
LifeMode = source.LifeMode,
BinningMode = source.BinningMode,
InjectionNoise = source.InjectionNoise,
LifeOpacity = source.LifeOpacity,
RgbHueShiftDegrees = source.RgbHueShiftDegrees,
RgbHueShiftSpeedDegreesPerSecond = source.RgbHueShiftSpeedDegreesPerSecond,
AudioFrequencyHueShiftDegrees = source.AudioFrequencyHueShiftDegrees,
ReactiveMappings = new ObservableCollection<LayerEditorSimulationReactiveMapping>(
source.ReactiveMappings.Select(CloneReactiveMapping)),
ThresholdMin = source.ThresholdMin,
ThresholdMax = source.ThresholdMax,
InvertThreshold = source.InvertThreshold,
PixelSortCellWidth = source.PixelSortCellWidth,
PixelSortCellHeight = source.PixelSortCellHeight
};
foreach (var child in source.Children)
{
var childClone = CloneSimulationLayer(child);
childClone.Parent = clone;
clone.Children.Add(childClone);
}
return clone;
}
private static LayerEditorSimulationReactiveMapping CloneReactiveMapping(LayerEditorSimulationReactiveMapping source)
{
return new LayerEditorSimulationReactiveMapping
{
Id = source.Id,
Input = source.Input,
Output = source.Output,
Amount = source.Amount,
ThresholdMin = source.ThresholdMin,
ThresholdMax = source.ThresholdMax
};
}
private void AttachReactiveMappingHandlers(LayerEditorSimulationLayer layer)
{
foreach (var mapping in layer.ReactiveMappings)
{
mapping.PropertyChanged -= ReactiveMapping_PropertyChanged;
mapping.PropertyChanged += ReactiveMapping_PropertyChanged;
}
foreach (var child in layer.Children)
{
AttachReactiveMappingHandlers(child);
}
}
private void ReactiveMapping_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
GetSelectedSimulationLayer()?.NotifyDetailsChanged();
}
private LayerEditorSource? GetSelectedSimulationSource() =>
_viewModel.SelectedSource?.IsSimulationGroup == true ? _viewModel.SelectedSource : null;
private LayerEditorSimulationLayer? GetSelectedSimulationLayer() =>
GetSelectedSimulationSource()?.SelectedSimulationLayer;
private ObservableCollection<LayerEditorSimulationLayer>? GetSelectedSimulationLayers() =>
GetSelectedSimulationSource()?.SimulationLayers;
private static IEnumerable<LayerEditorSimulationLayer> EnumerateSimulationLayers(IEnumerable<LayerEditorSimulationLayer> roots)
{
foreach (var layer in roots)
{
yield return layer;
foreach (var child in EnumerateSimulationLayers(layer.Children))
{
yield return child;
}
}
}
private static LayerEditorSimulationLayer? FindSimulationLayerById(IEnumerable<LayerEditorSimulationLayer> roots, Guid id) =>
EnumerateSimulationLayers(roots).FirstOrDefault(layer => layer.Id == id);
private void TraceSelection(string message)
{
Logger.Info($"[LayerEditorSelection] {message}");
}
private static string DescribeObject(object? value) => value switch
{
LayerEditorSource source => DescribeSource(source),
LayerEditorSimulationLayer layer => DescribeSimulationLayer(layer),
null => "<null>",
_ => value.GetType().Name
};
private static string DescribeSource(LayerEditorSource? source) =>
source == null ? "<null>" : $"{source.Kind}:{source.DisplayName} ({source.Id})";
private static string DescribeSimulationLayer(LayerEditorSimulationLayer? layer) =>
layer == null ? "<null>" : $"{layer.Kind}:{layer.Name} ({layer.Id})";
private static TreeViewItem? FindTreeViewItem(ItemsControl parent, object item)
{
if (parent.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem direct)
{
return direct;
}
foreach (var child in parent.Items)
{
if (parent.ItemContainerGenerator.ContainerFromItem(child) is not TreeViewItem childContainer)
{
continue;
}
var nested = FindTreeViewItem(childContainer, item);
if (nested != null)
{
return nested;
}
}
return null;
}
private void SetSelectedSimulationLayer(LayerEditorSimulationLayer? layer)
{
var source = GetSelectedSimulationSource();
if (source == null || ReferenceEquals(source.SelectedSimulationLayer, layer))
{
TraceSelection($"SetSelectedSimulationLayer noop source={DescribeSource(source)} layer={DescribeSimulationLayer(layer)}");
return;
}
if (source.SelectedSimulationLayer != null)
{
source.SelectedSimulationLayer.IsSelected = false;
}
_suppressSimulationLayerBindingApply = true;
source.SelectedSimulationLayer = layer;
if (source.SelectedSimulationLayer != null)
{
source.SelectedSimulationLayer.IsSelected = true;
}
TraceSelection($"SetSelectedSimulationLayer source={DescribeSource(source)} layer={DescribeSimulationLayer(layer)}");
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
_suppressSimulationLayerBindingApply = false;
}));
}
private void UpdateApplyState()
{
if (ApplyButton != null)
{
ApplyButton.IsEnabled = !_viewModel.LiveMode;
}
}
private bool ShouldApplyLive() =>
!ReferenceEquals(_viewModel, null) &&
!_ownerIsShuttingDown &&
!_suppressLiveUpdates &&
DataContext is LayerEditorViewModel { LiveMode: true };
private bool EnsureLiveModeForVideoTransport()
{
if (_viewModel.LiveMode)
{
return true;
}
MessageBox.Show(this, "Enable Live Mode to control video playback.", "Live Mode Required",
MessageBoxButton.OK, MessageBoxImage.Information);
return false;
}
private LayerEditorProjectSettings BuildProjectSettingsFromViewModel()
{
if (_ownerIsShuttingDown)
{
return _pendingProjectSettings ?? new LayerEditorProjectSettings();
}
var settings = _pendingProjectSettings ?? _owner.GetProjectSettingsForEditor();
settings.Height = NormalizeSimulationHeight(_viewModel.SimulationHeight);
settings.Depth = Math.Clamp(_viewModel.SimulationDepth, 3, 96);
settings.Framerate = Math.Clamp(_viewModel.SimulationFramerate, 5, 144);
settings.LifeOpacity = Math.Clamp(_viewModel.GlobalSimulationLifeOpacity, 0, 1);
return settings;
}
private void ApplyProjectSettingsLiveIfNeeded()
{
var settings = BuildProjectSettingsFromViewModel();
if (ShouldApplyLive())
{
_owner.ApplyProjectSettingsFromEditor(settings);
_pendingProjectSettings = null;
}
else
{
_pendingProjectSettings = settings;
}
}
private void CommitSimulationDimensions()
{
_viewModel.SimulationHeight = NormalizeSimulationHeight(_viewModel.SimulationHeight);
_viewModel.SimulationDepth = Math.Clamp(_viewModel.SimulationDepth, 3, 96);
_viewModel.SimulationFramerate = Math.Clamp(_viewModel.SimulationFramerate, 5, 144);
ApplyProjectSettingsLiveIfNeeded();
}
private void RefreshSelectedVideoTransportState()
{
if (_ownerIsShuttingDown || _suppressLiveUpdates)
{
return;
}
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
return;
}
var source = _viewModel.SelectedSource;
if (source == null || !source.IsVideo)
{
return;
}
if (!_owner.TryGetSourceVideoPlaybackState(source.Id, out var playbackState))
{
return;
}
_updatingVideoTransportUi = true;
try
{
source.VideoPlaybackPaused = playbackState.IsPaused;
source.VideoPlaybackPosition = playbackState.NormalizedPosition;
source.VideoPlaybackPositionSeconds = playbackState.PositionSeconds;
source.VideoPlaybackDurationSeconds = playbackState.DurationSeconds;
}
finally
{
_updatingVideoTransportUi = false;
}
}
private void LiveModeToggle(object sender, RoutedEventArgs e)
{
UpdateApplyState();
if (_viewModel.LiveMode)
{
RefreshFromSources();
}
}
private void ApplyButton_Click(object sender, RoutedEventArgs e)
{
if (_ownerIsShuttingDown || _viewModel.LiveMode)
{
return;
}
if (_pendingProjectSettings != null)
{
_owner.ApplyProjectSettingsFromEditor(_pendingProjectSettings);
_pendingProjectSettings = null;
}
var selectedId = _viewModel.SelectedSource?.Id;
_owner.ApplyLayerEditorSources(_viewModel.Sources.ToList());
RefreshFromSources(selectedId);
}
private void OpenAppControls_Click(object sender, RoutedEventArgs e)
{
if (_ownerIsShuttingDown)
{
return;
}
Point anchor = AppControlsButton.PointToScreen(new Point(0, AppControlsButton.ActualHeight + 2));
_owner.OpenRootContextMenuAtScreenPoint(anchor.X, anchor.Y);
}
private void SaveLayerConfig_Click(object sender, RoutedEventArgs e)
{
var dialog = new SaveFileDialog
{
Title = "Save Layer Configuration",
Filter = "LifeViz Layer Config (*.lifevizlayers.json)|*.lifevizlayers.json|JSON Files|*.json|All Files|*.*",
DefaultExt = ".lifevizlayers.json",
AddExtension = true,
OverwritePrompt = true
};
if (dialog.ShowDialog(this) != true)
{
return;
}
try
{
var projectSettings = _pendingProjectSettings ?? _owner.GetProjectSettingsForEditor();
var config = LayerConfigFile.FromEditorSources(
_viewModel.Sources,
Array.Empty<LayerEditorSimulationLayer>(),
projectSettings);
string json = JsonSerializer.Serialize(config, LayerConfigJsonOptions);
File.WriteAllText(dialog.FileName, json);
}
catch (Exception ex)
{
MessageBox.Show(this, $"Failed to save layer configuration:\n{ex.Message}", "Save Failed",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void LoadLayerConfig_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Title = "Load Layer Configuration",
Filter = "LifeViz Layer Config (*.lifevizlayers.json)|*.lifevizlayers.json|JSON Files|*.json|All Files|*.*",
CheckFileExists = true,
Multiselect = false
};
if (dialog.ShowDialog(this) != true)
{
return;
}
try
{
string json = File.ReadAllText(dialog.FileName);
var config = JsonSerializer.Deserialize<LayerConfigFile>(json);
if (config == null)
{
MessageBox.Show(this, "That file did not contain a layer configuration.", "Load Failed",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var sources = config.ToEditorSources();
var projectSettings = config.ToEditorProjectSettings();
if (_viewModel.LiveMode)
{
_owner.ApplyProjectSettingsFromEditor(projectSettings);
_owner.ApplyLayerEditorSources(sources);
RefreshFromSources();
}
else
{
_pendingProjectSettings = projectSettings;
_viewModel.Sources = new ObservableCollection<LayerEditorSource>(sources);
SetSelectedSource(_viewModel.Sources.FirstOrDefault());
RefreshProjectSettingsState();
}
}
catch (Exception ex)
{
MessageBox.Show(this, $"Failed to load layer configuration:\n{ex.Message}", "Load Failed",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private LayerEditorSource? ResolveSourceContext(object sender) =>
sender is FrameworkElement { DataContext: LayerEditorSource source } ? source : _viewModel.SelectedSource;
private void BlendMode_Changed(object sender, SelectionChangedEventArgs e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceBlendMode(source.Id, source.BlendMode);
}
}
private void FitMode_Changed(object sender, SelectionChangedEventArgs e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceFitMode(source.Id, source.FitMode);
}
}
private void Opacity_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceOpacity(source.Id, source.Opacity);
}
}
private void Mirror_Changed(object sender, RoutedEventArgs e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceMirror(source.Id, source.Mirror);
}
}
private void VideoAudio_Changed(object sender, RoutedEventArgs e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceVideoAudioEnabled(source.Id, source.VideoAudioEnabled);
}
}
private void VideoAudioVolume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (!ShouldApplyLive())
{
return;
}
var source = ResolveSourceContext(sender);
if (source != null)
{
_owner.UpdateSourceVideoAudioVolume(source.Id, source.VideoAudioVolume);
}
}
private void VideoPlayPause_Click(object sender, RoutedEventArgs e)
{
if (!EnsureLiveModeForVideoTransport())
{
return;
}
var source = ResolveSourceContext(sender);
if (source == null || !source.IsVideo)
{
return;
}
bool pause = !source.VideoPlaybackPaused;
_owner.UpdateSourceVideoPlaybackPaused(source.Id, pause);
RefreshSelectedVideoTransportState();
}
private void VideoSeek_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!EnsureLiveModeForVideoTransport() || _updatingVideoTransportUi)
{
return;
}
var source = ResolveSourceContext(sender);
if (source == null || !source.IsVideo)
{
return;
}
_owner.SeekSourceVideo(source.Id, source.VideoPlaybackPosition);
RefreshSelectedVideoTransportState();
}
private void MasterVideoAudio_Changed(object sender, RoutedEventArgs e)
{
if (_suppressLiveUpdates)
{
return;
}
_owner.UpdateMasterSourceAudioEnabled(_viewModel.SourceAudioMasterEnabled);
}
private void MasterVideoAudioVolume_Changed(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (_suppressLiveUpdates)
{
return;
}
_owner.UpdateMasterSourceAudioVolume(_viewModel.SourceAudioMasterVolume);
}