-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEffectDesignerWindow.xaml.cpp
More file actions
1321 lines (1180 loc) · 58.5 KB
/
EffectDesignerWindow.xaml.cpp
File metadata and controls
1321 lines (1180 loc) · 58.5 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
#include "pch.h"
#include "EffectDesignerWindow.xaml.h"
#if __has_include("EffectDesignerWindow.g.cpp")
#include "EffectDesignerWindow.g.cpp"
#endif
using namespace winrt;
using namespace Microsoft::UI::Xaml;
namespace winrt::ShaderLab::implementation
{
EffectDesignerWindow::EffectDesignerWindow()
{
InitializeComponent();
Title(L"Effect Designer");
ShaderTypeSelector().SelectedIndex(0);
OutputTypeSelector().SelectedIndex(0);
GenerateScaffoldButton().Click({ this, &EffectDesignerWindow::OnGenerateScaffold });
CompileButton().Click({ this, &EffectDesignerWindow::OnCompile });
FormatButton().Click([this](auto&&, auto&&)
{
auto text = std::wstring(HlslEditorBox().Text());
HlslEditorBox().Text(winrt::hstring(FormatHlsl(text)));
});
AddToGraphButton().Click({ this, &EffectDesignerWindow::OnAddToGraph });
UpdateInGraphButton().Click({ this, &EffectDesignerWindow::OnUpdateInGraph });
ShaderTypeSelector().SelectionChanged({ this, &EffectDesignerWindow::OnShaderTypeChanged });
AddInputButton().Click({ this, &EffectDesignerWindow::OnAddInput });
AddParamButton().Click({ this, &EffectDesignerWindow::OnAddParam });
// Analysis fields: show/hide based on Output type selection.
OutputTypeSelector().SelectionChanged([this](auto&&, auto&&)
{
bool showFields = (OutputTypeSelector().SelectedIndex() == 3); // Typed Analysis
AnalysisFieldsSection().Visibility(showFields
? Visibility::Visible : Visibility::Collapsed);
});
AddAnalysisFieldButton().Click([this](auto&&, auto&&)
{
AppendAnalysisFieldRow();
});
HlslEditorBox().PreviewKeyDown([this](auto&&, Input::KeyRoutedEventArgs const& args)
{
if (args.Key() == winrt::Windows::System::VirtualKey::Tab)
{
// Insert 4 spaces at the cursor position instead of moving focus.
auto editor = HlslEditorBox();
auto selStart = editor.SelectionStart();
auto text = std::wstring(editor.Text());
text.insert(selStart, L" ");
editor.Text(winrt::hstring(text));
editor.SelectionStart(selStart + 4);
editor.SelectionLength(0);
args.Handled(true);
}
});
HlslEditorBox().KeyDown([this](auto&&, Input::KeyRoutedEventArgs const& args)
{
if (args.Key() == winrt::Windows::System::VirtualKey::Enter)
{
if ((GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0)
{
OnCompile(nullptr, nullptr);
args.Handled(true);
}
}
});
// Add a default input.
OnAddInput(nullptr, nullptr);
}
void EffectDesignerWindow::OnShaderTypeChanged(
winrt::Windows::Foundation::IInspectable const&,
Controls::SelectionChangedEventArgs const&)
{
bool isCompute = ShaderTypeSelector().SelectedIndex() == 1;
bool isD3D11 = ShaderTypeSelector().SelectedIndex() == 2;
ComputeSettingsPanel().Visibility(
(isCompute || isD3D11) ? Visibility::Visible : Visibility::Collapsed);
}
void EffectDesignerWindow::OnAddInput(
winrt::Windows::Foundation::IInspectable const&,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
{
auto panel = InputsPanel();
uint32_t idx = panel.Children().Size();
auto row = Controls::StackPanel();
row.Orientation(Controls::Orientation::Horizontal);
row.Spacing(4);
auto indexText = Controls::TextBlock();
indexText.Text(std::to_wstring(idx) + L":");
indexText.VerticalAlignment(VerticalAlignment::Center);
indexText.Width(24);
row.Children().Append(indexText);
auto nameBox = Controls::TextBox();
nameBox.PlaceholderText(L"Input name");
nameBox.Text(idx == 0 ? L"Input" : std::format(L"Input {}", idx));
nameBox.MinWidth(150);
row.Children().Append(nameBox);
auto removeBtn = Controls::Button();
removeBtn.Content(box_value(L"X"));
removeBtn.Click([row, panel](auto&&, auto&&) {
uint32_t i = 0;
if (panel.Children().IndexOf(row, i))
panel.Children().RemoveAt(i);
});
row.Children().Append(removeBtn);
panel.Children().Append(row);
}
winrt::Microsoft::UI::Xaml::Controls::StackPanel
EffectDesignerWindow::AppendAnalysisFieldRow()
{
auto panel = AnalysisFieldsPanel();
auto row = Controls::StackPanel();
row.Orientation(Controls::Orientation::Horizontal);
row.Spacing(4);
auto nameBox = Controls::TextBox();
nameBox.PlaceholderText(L"Field Name");
nameBox.MinWidth(120);
row.Children().Append(nameBox);
auto typeCombo = Controls::ComboBox();
typeCombo.Items().Append(box_value(L"Float"));
typeCombo.Items().Append(box_value(L"Float2"));
typeCombo.Items().Append(box_value(L"Float3"));
typeCombo.Items().Append(box_value(L"Float4"));
typeCombo.Items().Append(box_value(L"Float Array"));
typeCombo.Items().Append(box_value(L"Float2 Array"));
typeCombo.Items().Append(box_value(L"Float3 Array"));
typeCombo.Items().Append(box_value(L"Float4 Array"));
typeCombo.SelectedIndex(0);
typeCombo.MinWidth(110);
row.Children().Append(typeCombo);
auto lenBox = Controls::NumberBox();
lenBox.Header(box_value(L"Length"));
lenBox.Value(0);
lenBox.Minimum(0);
lenBox.Maximum(4096);
lenBox.Width(80);
lenBox.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
lenBox.Visibility(Visibility::Collapsed);
row.Children().Append(lenBox);
// Show length only for array types.
typeCombo.SelectionChanged([lenBox](auto&& sender, auto&&) {
auto c = sender.template as<Controls::ComboBox>();
lenBox.Visibility(c.SelectedIndex() >= 4
? Visibility::Visible : Visibility::Collapsed);
});
auto removeBtn = Controls::Button();
removeBtn.Content(box_value(L"\xE711"));
removeBtn.FontFamily(winrt::Microsoft::UI::Xaml::Media::FontFamily(L"Segoe Fluent Icons"));
removeBtn.Click([row, panel](auto&&, auto&&) {
uint32_t i = 0;
if (panel.Children().IndexOf(row, i))
panel.Children().RemoveAt(i);
});
row.Children().Append(removeBtn);
panel.Children().Append(row);
return row;
}
void EffectDesignerWindow::OnAddParam(
winrt::Windows::Foundation::IInspectable const&,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)
{
auto panel = ParamsPanel();
// Each parameter is a compact grid:
// Row 0: Name | Type | Remove
// Row 1: Default/Min/Max values (or Labels for enum)
auto card = Controls::Grid();
card.Padding(winrt::Microsoft::UI::Xaml::ThicknessHelper::FromLengths(8, 6, 8, 6));
card.Background(winrt::Microsoft::UI::Xaml::Media::SolidColorBrush(
winrt::Windows::UI::Color{ 255, 40, 40, 40 }));
card.CornerRadius(winrt::Microsoft::UI::Xaml::CornerRadiusHelper::FromRadii(4, 4, 4, 4));
card.RowSpacing(4);
card.ColumnSpacing(8);
auto rowDef0 = Controls::RowDefinition();
rowDef0.Height(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Auto));
auto rowDef1 = Controls::RowDefinition();
rowDef1.Height(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Auto));
card.RowDefinitions().Append(rowDef0);
card.RowDefinitions().Append(rowDef1);
auto colDef0 = Controls::ColumnDefinition();
colDef0.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Auto));
auto colDef1 = Controls::ColumnDefinition();
colDef1.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Auto));
auto colDef2 = Controls::ColumnDefinition();
colDef2.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Star));
auto colDef3 = Controls::ColumnDefinition();
colDef3.Width(winrt::Microsoft::UI::Xaml::GridLengthHelper::FromValueAndType(1, winrt::Microsoft::UI::Xaml::GridUnitType::Auto));
card.ColumnDefinitions().Append(colDef0);
card.ColumnDefinitions().Append(colDef1);
card.ColumnDefinitions().Append(colDef2);
card.ColumnDefinitions().Append(colDef3);
// Row 0: Name + Type + Remove
auto nameBox = Controls::TextBox();
nameBox.PlaceholderText(L"Name");
nameBox.MinWidth(120);
Controls::Grid::SetRow(nameBox, 0);
Controls::Grid::SetColumn(nameBox, 0);
card.Children().Append(nameBox);
auto typeCombo = Controls::ComboBox();
typeCombo.Items().Append(box_value(L"float"));
typeCombo.Items().Append(box_value(L"float2"));
typeCombo.Items().Append(box_value(L"float3"));
typeCombo.Items().Append(box_value(L"float4"));
typeCombo.Items().Append(box_value(L"int"));
typeCombo.Items().Append(box_value(L"uint"));
typeCombo.Items().Append(box_value(L"bool"));
typeCombo.Items().Append(box_value(L"enum"));
typeCombo.SelectedIndex(0);
typeCombo.MinWidth(90);
Controls::Grid::SetRow(typeCombo, 0);
Controls::Grid::SetColumn(typeCombo, 1);
card.Children().Append(typeCombo);
auto removeBtn = Controls::Button();
removeBtn.Content(box_value(L"X"));
removeBtn.VerticalAlignment(winrt::Microsoft::UI::Xaml::VerticalAlignment::Top);
Controls::Grid::SetRow(removeBtn, 0);
Controls::Grid::SetColumn(removeBtn, 3);
removeBtn.Click([card, panel](auto&&, auto&&) {
uint32_t i = 0;
if (panel.Children().IndexOf(card, i))
panel.Children().RemoveAt(i);
});
card.Children().Append(removeBtn);
// Row 1: Value fields container (spans columns 0-2)
auto valRow = Controls::StackPanel();
valRow.Orientation(Controls::Orientation::Horizontal);
valRow.Spacing(8);
Controls::Grid::SetRow(valRow, 1);
Controls::Grid::SetColumn(valRow, 0);
Controls::Grid::SetColumnSpan(valRow, 3);
card.Children().Append(valRow);
// Helper to rebuild value fields based on type.
auto rebuildDefaults = [valRow](int typeIdx)
{
valRow.Children().Clear();
if (typeIdx == 6) // bool
{
auto toggle = Controls::ToggleSwitch();
toggle.Header(box_value(L"Default"));
toggle.IsOn(false);
valRow.Children().Append(toggle);
return;
}
if (typeIdx == 7) // enum
{
auto labelsBox = Controls::TextBox();
labelsBox.PlaceholderText(L"Label1, Label2, ...");
labelsBox.Header(box_value(L"Labels (comma-separated)"));
labelsBox.MinWidth(200);
valRow.Children().Append(labelsBox);
auto minBox = Controls::NumberBox();
minBox.Header(box_value(L"Min"));
minBox.Value(0.0);
minBox.Width(70);
minBox.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
valRow.Children().Append(minBox);
auto maxBox = Controls::NumberBox();
maxBox.Header(box_value(L"Max"));
maxBox.Value(1.0);
maxBox.Width(70);
maxBox.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
valRow.Children().Append(maxBox);
return;
}
int count = 1;
if (typeIdx == 1) count = 2; // float2
else if (typeIdx == 2) count = 3; // float3
else if (typeIdx == 3) count = 4; // float4
for (int i = 0; i < count; ++i)
{
auto nb = Controls::NumberBox();
nb.Value(0.0);
nb.Width(70);
nb.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
if (count == 1)
nb.Header(box_value(L"Default"));
else
{
static const wchar_t* compLabels[] = { L"X", L"Y", L"Z", L"W" };
nb.Header(box_value(winrt::hstring(compLabels[i])));
}
valRow.Children().Append(nb);
}
auto minBox = Controls::NumberBox();
minBox.Header(box_value(L"Min"));
minBox.Value(0.0);
minBox.Width(70);
minBox.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
valRow.Children().Append(minBox);
auto maxBox = Controls::NumberBox();
maxBox.Header(box_value(L"Max"));
maxBox.Value(1.0);
maxBox.Width(70);
maxBox.SpinButtonPlacementMode(Controls::NumberBoxSpinButtonPlacementMode::Compact);
valRow.Children().Append(maxBox);
};
rebuildDefaults(0);
typeCombo.SelectionChanged([rebuildDefaults](auto&& sender, auto&&)
{
auto combo = sender.template as<Controls::ComboBox>();
rebuildDefaults(combo.SelectedIndex());
});
panel.Children().Append(card);
}
::ShaderLab::Graph::CustomEffectDefinition EffectDesignerWindow::BuildDefinition()
{
::ShaderLab::Graph::CustomEffectDefinition def;
def.shaderType = [&]() {
int idx = ShaderTypeSelector().SelectedIndex();
if (idx == 1) return ::ShaderLab::Graph::CustomShaderType::ComputeShader;
if (idx == 2) return ::ShaderLab::Graph::CustomShaderType::D3D11ComputeShader;
return ::ShaderLab::Graph::CustomShaderType::PixelShader;
}();
// Inputs.
auto inputPanel = InputsPanel();
for (uint32_t i = 0; i < inputPanel.Children().Size(); ++i)
{
auto row = inputPanel.Children().GetAt(i).as<Controls::StackPanel>();
if (row.Children().Size() >= 2)
{
auto nameBox = row.Children().GetAt(1).as<Controls::TextBox>();
def.inputNames.push_back(std::wstring(nameBox.Text()));
}
}
// Parameters.
auto paramPanel = ParamsPanel();
for (uint32_t i = 0; i < paramPanel.Children().Size(); ++i)
{
auto card = paramPanel.Children().GetAt(i).try_as<Controls::Grid>();
if (!card) continue;
// Find children by type: nameBox (TextBox), typeCombo (ComboBox), valRow (StackPanel in row 1)
Controls::TextBox nameBox{ nullptr };
Controls::ComboBox typeCombo{ nullptr };
Controls::StackPanel valRow{ nullptr };
for (uint32_t c = 0; c < card.Children().Size(); ++c)
{
auto child = card.Children().GetAt(c);
int row = Controls::Grid::GetRow(child.as<winrt::Microsoft::UI::Xaml::FrameworkElement>());
if (row == 0)
{
if (auto tb = child.try_as<Controls::TextBox>()) nameBox = tb;
else if (auto cb = child.try_as<Controls::ComboBox>()) typeCombo = cb;
}
else if (row == 1)
{
if (auto sp = child.try_as<Controls::StackPanel>()) valRow = sp;
}
}
if (!nameBox || !typeCombo || !valRow) continue;
::ShaderLab::Graph::ParameterDefinition param;
param.name = std::wstring(nameBox.Text());
param.typeName = std::wstring(unbox_value<hstring>(typeCombo.SelectedItem()));
// valRow children: [default value(s)...] [Min NumberBox] [Max NumberBox]
// Min and Max are the last two NumberBoxes (except for bool which has no min/max).
uint32_t numChildren = valRow.Children().Size();
// Find min/max (last two NumberBoxes for non-bool types).
if (param.typeName != L"bool" && numChildren >= 2)
{
auto minNb = valRow.Children().GetAt(numChildren - 2).try_as<Controls::NumberBox>();
auto maxNb = valRow.Children().GetAt(numChildren - 1).try_as<Controls::NumberBox>();
if (minNb) param.minValue = static_cast<float>(minNb.Value());
if (maxNb) param.maxValue = static_cast<float>(maxNb.Value());
}
// Read default values.
if (param.typeName == L"float" && numChildren >= 3)
{
param.defaultValue = static_cast<float>(
valRow.Children().GetAt(0).as<Controls::NumberBox>().Value());
}
else if (param.typeName == L"float2" && numChildren >= 4)
{
namespace Num = winrt::Windows::Foundation::Numerics;
param.defaultValue = Num::float2{
static_cast<float>(valRow.Children().GetAt(0).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(1).as<Controls::NumberBox>().Value()) };
}
else if (param.typeName == L"float3" && numChildren >= 5)
{
namespace Num = winrt::Windows::Foundation::Numerics;
param.defaultValue = Num::float3{
static_cast<float>(valRow.Children().GetAt(0).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(1).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(2).as<Controls::NumberBox>().Value()) };
}
else if (param.typeName == L"float4" && numChildren >= 6)
{
namespace Num = winrt::Windows::Foundation::Numerics;
param.defaultValue = Num::float4{
static_cast<float>(valRow.Children().GetAt(0).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(1).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(2).as<Controls::NumberBox>().Value()),
static_cast<float>(valRow.Children().GetAt(3).as<Controls::NumberBox>().Value()) };
}
else if (param.typeName == L"int" && numChildren >= 3)
{
param.defaultValue = static_cast<int32_t>(
valRow.Children().GetAt(0).as<Controls::NumberBox>().Value());
}
else if (param.typeName == L"uint" && numChildren >= 3)
{
param.defaultValue = static_cast<uint32_t>(
valRow.Children().GetAt(0).as<Controls::NumberBox>().Value());
}
else if (param.typeName == L"bool" && numChildren >= 1)
{
// valRow has a ToggleSwitch for bool.
auto toggle = valRow.Children().GetAt(0).try_as<Controls::ToggleSwitch>();
param.defaultValue = toggle ? toggle.IsOn() : false;
}
else if (param.typeName == L"enum")
{
// Enum: stored as float in HLSL cbuffer. Labels in the TextBox.
param.typeName = L"float"; // HLSL type is float
auto labelsBox = valRow.Children().GetAt(0).try_as<Controls::TextBox>();
if (labelsBox)
{
auto text = std::wstring(labelsBox.Text());
// Parse comma-separated labels.
std::wstring label;
for (wchar_t ch : text)
{
if (ch == L',')
{
// Trim whitespace.
while (!label.empty() && label.front() == L' ') label.erase(label.begin());
while (!label.empty() && label.back() == L' ') label.pop_back();
if (!label.empty()) param.enumLabels.push_back(label);
label.clear();
}
else label += ch;
}
while (!label.empty() && label.front() == L' ') label.erase(label.begin());
while (!label.empty() && label.back() == L' ') label.pop_back();
if (!label.empty()) param.enumLabels.push_back(label);
}
param.defaultValue = 0.0f;
param.maxValue = static_cast<float>(param.enumLabels.size() - 1);
}
else
{
param.defaultValue = 0.0f;
}
def.parameters.push_back(std::move(param));
}
// Compute settings.
if (def.shaderType == ::ShaderLab::Graph::CustomShaderType::ComputeShader)
{
def.threadGroupX = static_cast<uint32_t>(ThreadGroupX().Value());
def.threadGroupY = static_cast<uint32_t>(ThreadGroupY().Value());
def.threadGroupZ = static_cast<uint32_t>(ThreadGroupZ().Value());
int outIdx = OutputTypeSelector().SelectedIndex();
if (outIdx == 1) def.analysisOutputType = ::ShaderLab::Graph::AnalysisOutputType::Histogram;
else if (outIdx == 2) def.analysisOutputType = ::ShaderLab::Graph::AnalysisOutputType::FloatBuffer;
else if (outIdx == 3)
{
def.analysisOutputType = ::ShaderLab::Graph::AnalysisOutputType::Typed;
// Collect analysis output fields from UI.
auto fieldsPanel = AnalysisFieldsPanel();
for (uint32_t fi = 0; fi < fieldsPanel.Children().Size(); ++fi)
{
auto fRow = fieldsPanel.Children().GetAt(fi).try_as<Controls::StackPanel>();
if (!fRow || fRow.Children().Size() < 3) continue;
auto fName = fRow.Children().GetAt(0).try_as<Controls::TextBox>();
auto fType = fRow.Children().GetAt(1).try_as<Controls::ComboBox>();
auto fLen = fRow.Children().GetAt(2).try_as<Controls::NumberBox>();
if (!fName || !fType) continue;
::ShaderLab::Graph::AnalysisFieldDescriptor fd;
fd.name = std::wstring(fName.Text());
fd.type = static_cast<::ShaderLab::Graph::AnalysisFieldType>(fType.SelectedIndex());
if (fLen && fType.SelectedIndex() >= 4)
fd.arrayLength = static_cast<uint32_t>(fLen.Value());
def.analysisFields.push_back(std::move(fd));
}
}
}
def.hlslSource = std::wstring(HlslEditorBox().Text());
return def;
}
std::wstring EffectDesignerWindow::GenerateHlsl(const ::ShaderLab::Graph::CustomEffectDefinition& def)
{
std::wstring hlsl;
// Constant buffer.
if (!def.parameters.empty())
{
hlsl += L"cbuffer Constants : register(b0)\n{\n";
for (const auto& p : def.parameters)
{
hlsl += L" " + p.typeName + L" " + p.name + L";\n";
}
hlsl += L"};\n\n";
}
if (def.shaderType == ::ShaderLab::Graph::CustomShaderType::PixelShader)
{
// Texture inputs.
for (uint32_t i = 0; i < def.inputNames.size(); ++i)
{
hlsl += std::format(L"Texture2D {} : register(t{});\n", def.inputNames[i], i);
}
if (!def.inputNames.empty())
{
hlsl += L"\n// D2D provides TEXCOORD in pixel/scene space.\n";
hlsl += L"// All inputs share TEXCOORD0 (same coordinate space).\n";
hlsl += L"// Use Load(int3(uv0.xy, 0)) for direct texel access.\n\n";
}
// Entry point — all inputs use TEXCOORD0 since MapOutputRectToInputRects
// returns the same rect for all inputs (1:1 mapping).
hlsl += L"float4 main(\n";
hlsl += L" float4 pos : SV_POSITION,\n";
hlsl += L" float4 uv0 : TEXCOORD0) : SV_TARGET\n";
hlsl += L"{\n";
if (def.inputNames.size() >= 1)
{
for (uint32_t i = 0; i < def.inputNames.size(); ++i)
{
hlsl += std::format(L" float4 color{0} = {1}.Load(int3(uv0.xy, 0));\n",
i, def.inputNames[i]);
}
hlsl += L"\n";
if (def.inputNames.size() == 1)
{
hlsl += L" // Your code here\n\n";
hlsl += L" return color0;\n";
}
else
{
hlsl += L" // Your code here -- blend, combine, or process the inputs\n\n";
hlsl += L" return color0;\n";
}
}
else
{
hlsl += L" // Your code here (no inputs)\n";
hlsl += L" return float4(0, 0, 0, 1);\n";
}
hlsl += L"}\n";
}
else if (def.shaderType == ::ShaderLab::Graph::CustomShaderType::D3D11ComputeShader)
{
// D3D11 compute shader — dispatched outside D2D tiling.
// Single dispatch(1,1,1) with stride pattern over the full image.
hlsl += L"// D3D11 Compute Shader — runs outside D2D's tiling system.\n";
hlsl += L"// Single dispatch(1,1,1) — one thread group strides over the full image.\n";
hlsl += L"// Width and Height are auto-injected at cbuffer offset 0.\n\n";
// Texture input
if (!def.inputNames.empty())
hlsl += std::format(L"Texture2D<float4> {} : register(t0);\n", def.inputNames[0]);
else
hlsl += L"Texture2D<float4> Source : register(t0);\n";
// Output structured buffer
hlsl += L"RWStructuredBuffer<float4> Result : register(u0);\n\n";
// Cbuffer with Width/Height first
hlsl += L"cbuffer Constants : register(b0)\n{\n";
hlsl += L" uint Width; // Auto-injected: source image width\n";
hlsl += L" uint Height; // Auto-injected: source image height\n";
for (const auto& p : def.parameters)
hlsl += L" " + p.typeName + L" " + p.name + L";\n";
hlsl += L"};\n\n";
// Analysis field layout comments
uint32_t pixOff = 0;
for (const auto& fd : def.analysisFields)
{
std::wstring typeTag;
switch (fd.type)
{
case ::ShaderLab::Graph::AnalysisFieldType::Float: typeTag = L"float"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2: typeTag = L"float2"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3: typeTag = L"float3"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4: typeTag = L"float4"; break;
case ::ShaderLab::Graph::AnalysisFieldType::FloatArray: typeTag = L"float[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2Array: typeTag = L"float2[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3Array: typeTag = L"float3[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4Array: typeTag = L"float4[]"; break;
}
hlsl += std::format(L"// Result[{}]: {} {} ({})\n",
pixOff, typeTag, fd.name,
::ShaderLab::Graph::AnalysisFieldIsArray(fd.type)
? std::format(L"{} elements", fd.pixelCount())
: L"1 element");
pixOff += fd.pixelCount();
}
if (pixOff > 0) hlsl += L"\n";
// Groupshared + main
std::wstring srcName = def.inputNames.empty() ? L"Source" : def.inputNames[0];
hlsl += L"// Groupshared accumulators for parallel reduction.\n";
hlsl += L"groupshared float4 gs_sum[32 * 32];\n\n";
hlsl += L"[numthreads(32, 32, 1)]\n";
hlsl += L"void main(uint3 GTid : SV_GroupThreadID)\n";
hlsl += L"{\n";
hlsl += L" uint tid = GTid.y * 32 + GTid.x;\n";
hlsl += L" float4 acc = float4(0, 0, 0, 0);\n\n";
hlsl += L" // Stride over entire image — each thread covers many pixels.\n";
hlsl += L" for (uint y = GTid.y; y < Height; y += 32)\n";
hlsl += L" {\n";
hlsl += L" for (uint x = GTid.x; x < Width; x += 32)\n";
hlsl += L" {\n";
hlsl += std::format(L" float4 pixel = {}.Load(int3(x, y, 0));\n", srcName);
hlsl += L" // TODO: accumulate your statistics here\n";
hlsl += L" acc += pixel;\n";
hlsl += L" }\n";
hlsl += L" }\n\n";
hlsl += L" // Parallel reduction in groupshared memory.\n";
hlsl += L" gs_sum[tid] = acc;\n";
hlsl += L" GroupMemoryBarrierWithGroupSync();\n\n";
hlsl += L" for (uint s = (32 * 32) / 2; s > 0; s >>= 1)\n";
hlsl += L" {\n";
hlsl += L" if (tid < s)\n";
hlsl += L" gs_sum[tid] += gs_sum[tid + s];\n";
hlsl += L" GroupMemoryBarrierWithGroupSync();\n";
hlsl += L" }\n\n";
hlsl += L" // Thread 0 writes final results.\n";
hlsl += L" if (tid == 0)\n";
hlsl += L" {\n";
hlsl += L" float totalPixels = float(Width * Height);\n";
hlsl += L" float4 mean = gs_sum[0] / max(totalPixels, 1.0);\n";
if (!def.analysisFields.empty())
{
pixOff = 0;
for (const auto& fd : def.analysisFields)
{
hlsl += std::format(L" Result[{}] = mean; // {} — replace with your value\n",
pixOff, fd.name);
pixOff += fd.pixelCount();
}
}
else
{
hlsl += L" Result[0] = mean;\n";
}
hlsl += L" }\n";
hlsl += L"}\n";
}
else
{
for (uint32_t i = 0; i < def.inputNames.size(); ++i)
{
hlsl += std::format(L"Texture2D {} : register(t{});\n", def.inputNames[i], i);
}
hlsl += L"RWTexture2D<float4> Output : register(u0);\n";
if (!def.inputNames.empty())
hlsl += L"SamplerState Sampler0 : register(s0);\n";
hlsl += L"\n";
if (def.analysisOutputType == ::ShaderLab::Graph::AnalysisOutputType::Typed)
{
// Analysis compute shader: reads entire input, writes summary stats
// to the output row. Each field occupies a known pixel offset.
hlsl += L"// Analysis compute shader pattern:\n";
hlsl += L"// The output texture is used as a data buffer.\n";
hlsl += L"// Write results to Output[int2(pixelOffset, 0)].\n";
hlsl += L"// The host reads typed fields back after evaluation.\n\n";
hlsl += L"cbuffer Constants : register(b0)\n{\n";
hlsl += L" int2 _TileOffset; // Auto-injected: tile origin in full image\n";
for (const auto& p : def.parameters)
hlsl += L" " + p.typeName + L" " + p.name + L";\n";
hlsl += L"};\n\n";
// Generate field pixel offset comments.
uint32_t pixOff = 0;
for (const auto& fd : def.analysisFields)
{
std::wstring typeTag;
switch (fd.type)
{
case ::ShaderLab::Graph::AnalysisFieldType::Float: typeTag = L"float"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2: typeTag = L"float2"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3: typeTag = L"float3"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4: typeTag = L"float4"; break;
case ::ShaderLab::Graph::AnalysisFieldType::FloatArray: typeTag = L"float[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2Array: typeTag = L"float2[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3Array: typeTag = L"float3[]"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4Array: typeTag = L"float4[]"; break;
}
hlsl += std::format(L"// pixel {}: {} {} ({})\n",
pixOff, typeTag, fd.name,
::ShaderLab::Graph::AnalysisFieldIsArray(fd.type)
? std::format(L"{} pixels", fd.pixelCount())
: L"1 pixel");
pixOff += fd.pixelCount();
}
hlsl += L"\n";
hlsl += std::format(L"[numthreads({}, {}, {})]\n",
def.threadGroupX, def.threadGroupY, def.threadGroupZ);
hlsl += L"void main(uint3 DTid : SV_DispatchThreadID)\n";
hlsl += L"{\n";
if (!def.inputNames.empty())
{
hlsl += L" // Get full source dimensions and compute global position.\n";
hlsl += L" uint srcW, srcH;\n";
hlsl += std::format(L" {}.GetDimensions(srcW, srcH);\n", def.inputNames[0]);
hlsl += L" uint2 globalPos = DTid.xy + uint2(_TileOffset);\n";
hlsl += L" if (globalPos.x >= srcW || globalPos.y >= srcH) return;\n\n";
hlsl += L" // Sample input using normalized UVs (Load() not available in D2D compute).\n";
hlsl += L" float2 uv = (float2(globalPos) + 0.5) / float2(srcW, srcH);\n";
hlsl += std::format(L" float4 pixel = {}.SampleLevel(Sampler0, uv, 0);\n\n", def.inputNames[0]);
}
hlsl += L" // TODO: Accumulate statistics across pixels.\n";
hlsl += L" // For whole-image statistics, use groupshared memory and atomic ops,\n";
hlsl += L" // or output per-pixel data and reduce on the CPU.\n\n";
hlsl += L" // Write results to known pixel locations.\n";
pixOff = 0;
for (const auto& fd : def.analysisFields)
{
hlsl += std::format(L" // Output[int2({}, 0)] = ...; // {}\n", pixOff, fd.name);
pixOff += fd.pixelCount();
}
if (def.analysisFields.empty())
hlsl += L" // Output[int2(0, 0)] = float4(result, 0, 0, 0);\n";
hlsl += L"}\n";
}
else
{
// Image-processing compute shader (passthrough scaffold).
hlsl += L"// Image-processing compute shader:\n";
hlsl += L"// D2D evaluates compute effects in tiles. _TileOffset is auto-injected\n";
hlsl += L"// per tile so the shader sees correct global coordinates.\n";
hlsl += L"// Use Source.GetDimensions() for the full image size.\n";
hlsl += L"// Use SampleLevel() with normalized UVs (Load() not available in D2D compute).\n\n";
hlsl += L"cbuffer Constants : register(b0)\n{\n";
hlsl += L" int2 _TileOffset; // Auto-injected: tile origin in full image\n";
for (const auto& p : def.parameters)
hlsl += L" " + p.typeName + L" " + p.name + L";\n";
hlsl += L"};\n\n";
hlsl += std::format(L"[numthreads({}, {}, {})]\n",
def.threadGroupX, def.threadGroupY, def.threadGroupZ);
hlsl += L"void main(uint3 DTid : SV_DispatchThreadID)\n";
hlsl += L"{\n";
if (!def.inputNames.empty())
{
hlsl += L" // Get full source dimensions and compute global position.\n";
hlsl += L" uint srcW, srcH;\n";
hlsl += std::format(L" {}.GetDimensions(srcW, srcH);\n", def.inputNames[0]);
hlsl += L" uint2 globalPos = DTid.xy + uint2(_TileOffset);\n";
hlsl += L" if (globalPos.x >= srcW || globalPos.y >= srcH) return;\n\n";
hlsl += L" // Sample input using normalized UVs.\n";
hlsl += L" float2 uv = (float2(globalPos) + 0.5) / float2(srcW, srcH);\n";
hlsl += std::format(L" float4 color = {}.SampleLevel(Sampler0, uv, 0);\n", def.inputNames[0]);
hlsl += L"\n // Your code here\n\n";
hlsl += L" Output[DTid.xy] = color;\n";
}
else
{
hlsl += L" // Your code here\n";
hlsl += L" Output[DTid.xy] = float4(0, 0, 0, 1);\n";
}
hlsl += L"}\n";
}
}
return hlsl;
}
bool EffectDesignerWindow::CompileHlsl(::ShaderLab::Graph::CustomEffectDefinition& def)
{
auto hlsl = std::wstring(HlslEditorBox().Text());
def.hlslSource = hlsl;
// WinUI TextBox uses \r as line separator. D3DCompile needs \n.
std::string hlslUtf8 = winrt::to_string(hlsl);
for (auto& ch : hlslUtf8)
{
if (ch == '\r') ch = '\n';
}
std::wstring target = (def.shaderType == ::ShaderLab::Graph::CustomShaderType::PixelShader)
? L"ps_5_0" : L"cs_5_0";
std::wstring entryPoint = L"main";
auto result = ::ShaderLab::Effects::ShaderCompiler::CompileFromString(
hlslUtf8, "EffectDesigner", winrt::to_string(entryPoint), winrt::to_string(target));
if (!result.succeeded)
{
CompileStatusText().Text(L"X " + winrt::hstring(result.ErrorMessage()));
def.compiledBytecode.clear();
return false;
}
auto* blob = result.bytecode.get();
def.compiledBytecode.resize(blob->GetBufferSize());
memcpy(def.compiledBytecode.data(), blob->GetBufferPointer(), blob->GetBufferSize());
// Generate a unique GUID for this shader instance if not already set.
if (def.shaderGuid == GUID{})
CoCreateGuid(&def.shaderGuid);
CompileStatusText().Text(L"V Compiled successfully (" +
winrt::to_hstring(def.compiledBytecode.size()) + L" bytes)");
return true;
}
std::wstring EffectDesignerWindow::FormatHlsl(const std::wstring& source)
{
// Split into lines (handle \r, \n, \r\n).
std::vector<std::wstring> lines;
std::wstring current;
for (size_t i = 0; i < source.size(); ++i)
{
wchar_t ch = source[i];
if (ch == L'\r')
{
lines.push_back(current);
current.clear();
if (i + 1 < source.size() && source[i + 1] == L'\n') ++i;
}
else if (ch == L'\n')
{
lines.push_back(current);
current.clear();
}
else
{
current += ch;
}
}
if (!current.empty()) lines.push_back(current);
// If input is a single long line (common for embedded HLSL),
// split on semicolons and braces first.
if (lines.size() <= 2)
{
std::vector<std::wstring> expanded;
for (const auto& line : lines)
{
std::wstring buf;
bool inString = false;
bool inLineComment = false;
for (size_t i = 0; i < line.size(); ++i)
{
wchar_t ch = line[i];
wchar_t next = (i + 1 < line.size()) ? line[i + 1] : 0;
if (inLineComment) { buf += ch; continue; }
if (ch == L'"') inString = !inString;
if (inString) { buf += ch; continue; }
if (ch == L'/' && next == L'/') { inLineComment = true; buf += ch; continue; }
if (ch == L'{')
{
// Trim trailing whitespace from buf.
while (!buf.empty() && buf.back() == L' ') buf.pop_back();
if (!buf.empty()) expanded.push_back(buf);
expanded.push_back(L"{");
buf.clear();
// Skip whitespace after brace.
while (i + 1 < line.size() && line[i + 1] == L' ') ++i;
continue;
}
if (ch == L'}')
{
while (!buf.empty() && buf.back() == L' ') buf.pop_back();
if (!buf.empty()) expanded.push_back(buf);
expanded.push_back(L"}");
buf.clear();
// Skip whitespace + optional semicolon after }.
while (i + 1 < line.size() && line[i + 1] == L' ') ++i;
if (i + 1 < line.size() && line[i + 1] == L';') { ++i; expanded.back() += L";"; }
continue;
}
if (ch == L';')
{
buf += ch;
// End this statement as a line.
while (!buf.empty() && buf.front() == L' ') buf.erase(buf.begin());
expanded.push_back(buf);
buf.clear();
// Skip whitespace after semicolon.
while (i + 1 < line.size() && line[i + 1] == L' ') ++i;
continue;
}
buf += ch;
}
while (!buf.empty() && buf.front() == L' ') buf.erase(buf.begin());
if (!buf.empty()) expanded.push_back(buf);
}
lines = std::move(expanded);
}
// Now apply indentation based on brace depth.
std::wstring result;
int indent = 0;
for (auto& line : lines)
{
// Trim leading/trailing whitespace.
size_t start = line.find_first_not_of(L" \t");
size_t end = line.find_last_not_of(L" \t");
if (start == std::wstring::npos) { result += L"\n"; continue; }
line = line.substr(start, end - start + 1);
// Decrease indent for closing braces.
if (!line.empty() && line[0] == L'}')
indent = (std::max)(indent - 1, 0);
// Apply indentation.
for (int i = 0; i < indent; ++i)
result += L" ";
result += line;
result += L"\n";
// Increase indent after opening braces.
// Count net braces on this line (excluding strings/comments).
for (wchar_t ch : line)
{
if (ch == L'{') ++indent;
else if (ch == L'}') indent = (std::max)(indent - 1, 0);
}
// Re-adjust: we already decremented for leading }, so add back.
if (!line.empty() && line[0] == L'}')
indent = indent; // already handled above
}
// Remove trailing newline.
while (!result.empty() && result.back() == L'\n') result.pop_back();
return result;
}
void EffectDesignerWindow::OnGenerateScaffold(
winrt::Windows::Foundation::IInspectable const&,
winrt::Microsoft::UI::Xaml::RoutedEventArgs const&)