-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.McpRoutes.cpp
More file actions
1718 lines (1597 loc) · 99.6 KB
/
MainWindow.McpRoutes.cpp
File metadata and controls
1718 lines (1597 loc) · 99.6 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 "MainWindow.xaml.h"
#include "Engine/Mcp/McpHttpServer.h"
#include "Effects/CustomPixelShaderEffect.h"
#include "Effects/CustomComputeShaderEffect.h"
#include "Effects/ShaderLabEffects.h"
#include "Effects/SourceNodeFactory.h"
#include "Rendering/IccProfileParser.h"
#include "Version.h"
// Helper: narrow string from wide string.
static std::string ToUtf8(const std::wstring& ws)
{
if (ws.empty()) return {};
int len = WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), static_cast<int>(ws.size()), nullptr, 0, nullptr, nullptr);
std::string s(len, 0);
WideCharToMultiByte(CP_UTF8, 0, ws.c_str(), static_cast<int>(ws.size()), s.data(), len, nullptr, nullptr);
return s;
}
// Base64 (standard alphabet, '=' padding, no line wrapping).
static std::string Base64Encode(const uint8_t* data, size_t len)
{
static constexpr char kAlphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
if (len == 0) return out;
out.reserve(((len + 2) / 3) * 4);
size_t i = 0;
while (i + 2 < len)
{
uint32_t v = (uint32_t(data[i]) << 16) | (uint32_t(data[i + 1]) << 8) | uint32_t(data[i + 2]);
out.push_back(kAlphabet[(v >> 18) & 0x3F]);
out.push_back(kAlphabet[(v >> 12) & 0x3F]);
out.push_back(kAlphabet[(v >> 6) & 0x3F]);
out.push_back(kAlphabet[v & 0x3F]);
i += 3;
}
if (i < len)
{
uint32_t v = uint32_t(data[i]) << 16;
bool two = (i + 1 < len);
if (two) v |= uint32_t(data[i + 1]) << 8;
out.push_back(kAlphabet[(v >> 18) & 0x3F]);
out.push_back(kAlphabet[(v >> 12) & 0x3F]);
out.push_back(two ? kAlphabet[(v >> 6) & 0x3F] : '=');
out.push_back('=');
}
return out;
}
namespace winrt::ShaderLab::implementation
{
// Dispatch a lambda to the UI thread and block until completion.
// Returns the result from the lambda. Must NOT be called from the UI thread.
//
// Key correctness properties:
// * The state (result/exception/event) lives in a shared_ptr captured by
// the lambda, so if we time out and the caller returns, the lambda can
// still safely write to it without dangling references.
// * We always check the wait result before reading the result so a timeout
// won't deref an empty optional. On timeout we throw so the calling
// route returns a 500 instead of producing garbage.
// * Non-void return only -- DispatchSync<void> isn't supported.
template<typename F>
auto MainWindow::DispatchSync(F&& fn) -> decltype(fn())
{
using R = decltype(fn());
struct State
{
std::optional<R> result;
std::exception_ptr ex;
HANDLE event{ nullptr };
~State() { if (event) CloseHandle(event); }
};
auto state = std::make_shared<State>();
state->event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!state->event)
throw std::runtime_error("DispatchSync: CreateEventW failed");
// Move the lambda into a shared_ptr so it stays alive even if the
// DispatcherQueue holds the callback longer than this scope.
auto fnPtr = std::make_shared<std::decay_t<F>>(std::forward<F>(fn));
DispatcherQueue().TryEnqueue([state, fnPtr]()
{
try { state->result = (*fnPtr)(); }
catch (...) { state->ex = std::current_exception(); }
SetEvent(state->event);
});
// 30s timeout -- generous for stats/readback paths but still a
// backstop against a wedged UI thread.
DWORD wait = WaitForSingleObject(state->event, 30000);
if (wait != WAIT_OBJECT_0)
throw std::runtime_error("DispatchSync: UI thread did not respond within 30s");
if (state->ex) std::rethrow_exception(state->ex);
if (!state->result.has_value())
throw std::runtime_error("DispatchSync: lambda completed without producing a result");
return std::move(*state->result);
}
::ShaderLab::McpHttpServer::Response MainWindow::GuiEngineCommandSink::Dispatch(
std::function<::ShaderLab::McpHttpServer::Response(
::ShaderLab::Mcp::EngineContext&)> closure)
{
// Marshal the engine work to the render thread (single writer to
// m_graph). Re-entrant calls from inside the consumer thread run
// inline (RenderThreadDispatcher detects this).
::ShaderLab::McpHttpServer::Response resp;
try
{
resp = window->m_renderDispatcher.DispatchSync(
[this, &closure]() -> ::ShaderLab::McpHttpServer::Response {
::ShaderLab::Mcp::EngineContext ctx{};
ctx.graph = &window->m_graph;
ctx.evaluator = &window->m_graphEvaluator;
ctx.displayMonitor = &window->m_displayMonitor;
ctx.sourceFactory = &window->m_sourceFactory;
// Closure runs on render thread now -- give it the render
// D2D context so source-prep / evaluator ops it performs
// share state with the per-frame render path.
ctx.dc = window->m_renderEngine.RenderD2DContext();
ctx.d3dDevice = window->m_renderEngine.D3DDevice();
ctx.d3dContext = window->m_renderEngine.D3DContext();
ctx.renderFrame = [this]() { window->RenderFrameToOffscreen(0.0); };
ctx.getPreviewNodeId = [this]() -> uint32_t { return window->m_previewNodeId; };
ctx.getLoadedIccProfile = [this]() -> std::optional<::ShaderLab::Rendering::DisplayProfile> {
return window->m_loadedIccProfile;
};
ctx.setLoadedIccProfile = [this](const ::ShaderLab::Rendering::DisplayProfile& p) {
window->m_loadedIccProfile = p;
};
return closure(ctx);
});
}
catch (const std::exception& e)
{
::ShaderLab::McpHttpServer::Response err;
err.statusCode = 500;
err.body = std::string(R"({"error":")") + e.what() + R"("})";
err.contentType = "application/json";
return err;
}
return resp;
}
// Event hooks fire from inside Dispatch closures, which run on the
// render thread. Anything that touches XAML or UI-thread-only controllers
// must be marshalled back to the UI thread via DispatcherQueue().TryEnqueue.
//
// P7 race protection: NodeGraphController::AutoLayout / RebuildLayout
// iterate `m_graph.Nodes()` and each node's `properties` std::map. The
// render worker mutates those maps every tick (analysisOutput updates,
// clock advancement, source factory writes). To avoid use-after-free /
// iterator invalidation in std::map traversal, we run those layout
// calls THROUGH the render dispatcher with DispatchSync. The dispatcher
// drains queued closures BEFORE the worker's per-tick body, so when our
// closure runs the worker is implicitly paused -- m_graph is stable for
// the duration of the layout, and m_visuals isn't being concurrently
// read by the UI thread (which is blocked in DispatchSync).
static void RunLayoutOnRenderThread(::ShaderLab::Rendering::RenderThreadDispatcher& dispatcher,
std::function<void()> work)
{
dispatcher.DispatchSync([work = std::move(work)]() {
work();
});
}
void MainWindow::GuiEngineCommandSink::OnNodeAdded(uint32_t nodeId)
{
window->m_graph.MarkAllDirty();
window->m_forceRender = true;
// Detect Output nodes added via /graph/apply or other engine-side
// routes and auto-open a window for each. Engine-pure hosts don't
// care about windows; this sink runs only in the GUI host.
bool isOutput = false;
if (auto* n = window->m_graph.FindNode(nodeId))
isOutput = (n->type == ::ShaderLab::Graph::NodeType::Output);
auto* w = window;
w->DispatcherQueue().TryEnqueue([w, nodeId, isOutput]{
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.AutoLayout(); });
w->PopulatePreviewNodeSelector();
if (isOutput)
{
try { w->OpenOutputWindow(nodeId); } catch (...) {}
}
});
}
void MainWindow::GuiEngineCommandSink::OnNodeRemoved(uint32_t nodeId)
{
window->m_graphEvaluator.InvalidateNode(nodeId);
window->m_graph.MarkAllDirty();
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w, nodeId]{
w->CloseOutputWindow(nodeId);
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.AutoLayout(); });
w->PopulatePreviewNodeSelector();
});
}
void MainWindow::GuiEngineCommandSink::OnNodeChanged(uint32_t nodeId)
{
window->m_forceRender = true;
// If the changed node has any visibleWhen-conditional parameters,
// a property change might flip a pin's visibility. Rebuild the
// node-graph layout so new input pins materialize on the canvas.
//
// OnNodeChanged is already running inside a render-dispatcher
// closure (the /graph/set-property route DispatchSync's into the
// worker before invoking this hook), so it is safe to touch
// m_graph and m_nodeGraphController here directly -- the worker
// is paused for the duration. We just need to tell the controller
// to repaint via m_needsRedraw (set by RebuildLayout itself).
if (auto* n = window->m_graph.FindNode(nodeId))
{
if (n->customEffect.has_value())
{
for (const auto& p : n->customEffect->parameters)
{
if (!p.visibleWhen.empty())
{
window->m_nodeGraphController.RebuildLayout();
break;
}
}
}
}
}
void MainWindow::GuiEngineCommandSink::OnGraphCleared()
{
window->m_graphEvaluator.ReleaseCache();
window->m_previewNodeId = 0;
window->m_graph.MarkAllDirty();
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w]{
w->m_outputWindows.clear();
// Also drop sinks so the render worker doesn't keep churning on
// closed windows. Without this the m_outputSinks vector grows
// unbounded across graph clear/load cycles.
{
std::scoped_lock lock(w->m_outputSinksMutex);
w->m_outputSinks.clear();
}
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.AutoLayout(); });
w->PopulatePreviewNodeSelector();
});
}
void MainWindow::GuiEngineCommandSink::OnGraphLoaded()
{
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w]{
w->ResetAfterGraphLoad(/*reopenOutputWindows=*/true);
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.AutoLayout(); });
});
}
void MainWindow::GuiEngineCommandSink::OnGraphStructureChanged()
{
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w]{
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.AutoLayout(); });
});
}
void MainWindow::GuiEngineCommandSink::OnCustomEffectRecompiled(uint32_t /*nodeId*/)
{
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w]{
RunLayoutOnRenderThread(w->m_renderDispatcher,
[w]{ w->m_nodeGraphController.RebuildLayout(); });
w->PopulateAddNodeFlyout();
});
}
void MainWindow::GuiEngineCommandSink::OnDisplayProfileChanged()
{
window->m_graph.MarkAllDirty();
window->m_forceRender = true;
auto* w = window;
w->DispatcherQueue().TryEnqueue([w]{ w->UpdateStatusBar(); });
}
void MainWindow::SetupMcpRoutes()
{
if (!m_mcpServer)
m_mcpServer = std::make_unique<::ShaderLab::McpHttpServer>();
if (!m_engineSink)
m_engineSink = std::make_unique<GuiEngineCommandSink>(this);
// Activity callback: fires on the listener thread once per HTTP request.
// We update atomic state + a small mutexed string snapshot; the UI render
// tick polls these and refreshes the indicator dot + tooltip. Keeping
// this side cheap and non-blocking ensures we don't introduce lock-step
// between MCP responses and the UI thread.
m_mcpServer->SetActivityCallback(
[this](const std::string& method,
const std::wstring& path,
uint16_t statusCode,
const std::string& peerAddress)
{
using clk = std::chrono::system_clock;
auto nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
clk::now().time_since_epoch()).count();
m_mcpLastActivityMs.store(nowMs, std::memory_order_relaxed);
m_mcpRequestCount.fetch_add(1, std::memory_order_relaxed);
{
std::lock_guard lock(m_mcpLastReqMutex);
m_mcpLastReqMethod = method;
m_mcpLastReqPath = ToUtf8(path);
m_mcpLastReqPeer = peerAddress;
m_mcpLastReqStatus = statusCode;
if (!peerAddress.empty())
m_mcpKnownPeers.insert(peerAddress);
}
m_mcpUiUpdateSeq.fetch_add(1, std::memory_order_release);
});
// Register engine-pure routes (Phase 7 migration). Currently
// empty; routes are migrated in batches with each commit.
// The GUI app then registers UI-coupled routes below
// (graph_snapshot, preview/graph view tools, etc).
::ShaderLab::Mcp::RegisterEngineRoutes(*m_mcpServer, *m_engineSink);
// =====================================================================
// GET / — Health check / probe (some MCP clients GET / before POST).
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/", [](const std::wstring& path, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
// Only match exact "/" — longer GET paths fall through to other routes.
if (path != L"/")
return { 404, R"({"error":"Not found"})" };
return { 200, R"({"name":"shaderlab","transport":"streamable-http","endpoint":"POST /"})" };
});
// =====================================================================
// GET /context — System prompt / onboarding for calling agents
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/context", [](const std::wstring&, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
std::string doc = R"JSON({
"name": "ShaderLab",
"description": "D2D shader effect development tool with node graph, HDR/WCG pipeline.",
"pipeline": {
"format": "scRGB FP16 linear light",
"whitePoint": "1.0 = 80 nits SDR white",
"valuesAbove1": "HDR, super-white",
"colorSpace": "Linear sRGB primaries, Rec.709"
},
"shaderConventions": {
"texcoords": "D2D provides TEXCOORD0 in pixel/scene space, not normalized 0-1",
"sampling": "Use Load int3 uv0.xy 0 for direct texel access; all inputs share TEXCOORD0",
"filteredSampling": "Use SampleLevel with GetDimensions normalization for bilinear",
"constantBuffer": "register b0, variables packed by D3DReflect offsets",
"textures": "register t0..t7, one per input",
"computeOutput": "RWTexture2D<float4> Output : register u0"
},
"analysisEffects": {
"pattern": "Compute shaders can act as analysis effects that read an entire image and produce typed output fields",
"outputTypes": "float, float2, float3, float4, floatarray, float2array, float3array, float4array",
"outputConvention": "Write results to Output[int2(pixelOffset, 0)]. Each field occupies pixelCount() pixels sequentially",
"readback": "The host reads the output row and unpacks typed fields based on analysisFields descriptors",
"fieldDescriptors": "Define analysisFields array in custom effect definition with name, type, and length (for arrays)",
"propertyBindings": "Analysis output fields can be bound to downstream node properties via propertyBindings",
"builtInExample": "D2D Histogram effect: processes input, exposes 256-float histogram via GetValue",
"customExample": "Gamut analysis: Output[0,0].x = maxLuminance (float), Output[1,0] = gamutBounds (float4), etc."
},
"nodeTypes": ["Source", "BuiltInEffect", "PixelShader", "ComputeShader", "Output"],
"outputNote": "PNG captures are tone-mapped SDR. Use /render/pixel/X/Y for true scRGB float values. Values above 1.0 are HDR.",
"endpoints": {
"GET /context": "This document",
"GET /graph": "Full graph state with nodes, edges, properties, custom effects",
"GET /graph/node/{id}": "Single node detail including custom effect definition",
"GET /registry/effects": "All built-in D2D effects",
"GET /custom-effects": "All custom effects in graph with HLSL source",
"GET /render/capture": "Output as base64 PNG, SDR tone-mapped",
"GET /render/pixel/{x}/{y}": "scRGB float4 plus luminance at coordinates",
"POST /graph/add-node": "Add a node, body: effectName string",
"POST /graph/remove-node": "Remove node, body: nodeId number",
"POST /graph/connect": "Connect pins, body: srcId srcPin dstId dstPin",
"POST /graph/disconnect": "Disconnect, body: srcId srcPin dstId dstPin",
"POST /graph/set-property": "Set property, body: nodeId key value",
"POST /graph/load": "Load graph JSON, body: full graph JSON string",
"GET /graph/save": "Get graph as JSON string",
"POST /graph/clear": "Clear entire graph",
"POST /effect/compile": "Compile HLSL, body: nodeId hlsl",
"POST /render/preview-node": "Set preview node, body: nodeId number"
}
})JSON";
return { 200, doc };
});
// =====================================================================
// GET /graph, GET /graph/save, GET /graph/node/{id}
// -- moved to Engine/Mcp/EngineMcpRoutes.cpp (Phase 7).
// =====================================================================
// =====================================================================
// GET /registry -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// (Phase 7 migration). Static D2D effect catalog, no Dispatch needed.
// =====================================================================
// =====================================================================
// GET /custom-effects -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// (Phase 7).
// =====================================================================
// =====================================================================
// POST /graph/add-node -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/remove-node -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/connect -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// (Phase 7 migration). Same notes as /graph/disconnect.
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/disconnect -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// (Phase 7 migration). UI side effects (nodeLogs, AutoLayout) drop
// out: the GUI render tick picks up dirty state and refreshes the
// canvas next frame.
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/set-property -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// (Phase 7 migration). Mutates m_graph through IEngineCommandSink.
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/load -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// =====================================================================
// POST /graph/clear -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// POST /render/preview-node
// =====================================================================
m_mcpServer->AddRoute(L"POST", L"/render/preview-node", [this](const std::wstring&, const std::string& body)
-> ::ShaderLab::McpHttpServer::Response
{
try
{
auto jobj = winrt::Windows::Data::Json::JsonObject::Parse(winrt::to_hstring(body));
uint32_t nodeId = static_cast<uint32_t>(jobj.GetNamedNumber(L"nodeId"));
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
m_previewNodeId = nodeId;
m_needsFitPreview = true;
m_forceRender = true;
m_graph.MarkAllDirty();
return { 200, R"({"ok":true})" };
});
}
catch (...) { return { 400, R"({"error":"Invalid request"})" }; }
});
// =====================================================================
// POST /effect/compile
// =====================================================================
// -- moved to Engine/Mcp/EngineMcpRoutes.cpp (Phase 7).
// Mirrors EffectDesignerWindow Update-in-Graph; fires
// OnCustomEffectRecompiled hook.
// =====================================================================
// =====================================================================
// GET /render/pixel/{x}/{y}
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/render/pixel/", [this](const std::wstring& path, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
// Parse /render/pixel/{x}/{y}
auto rest = path.substr(14); // after "/render/pixel/"
auto slash = rest.find(L'/');
if (slash == std::wstring::npos)
return { 400, R"({"error":"Format: /render/pixel/{x}/{y}"})" };
float x = std::stof(rest.substr(0, slash));
float y = std::stof(rest.substr(slash + 1));
auto* dc = m_renderEngine.D2DDeviceContext();
if (!dc) return { 500, R"({"error":"No device context"})" };
auto* image = ResolveDisplayImage(m_previewNodeId);
if (!image) return { 404, R"({"error":"No output image"})" };
// Read pixel value using a 1x1 bitmap copy.
D2D1_POINT_2U srcPoint = { static_cast<UINT32>(x), static_cast<UINT32>(y) };
D2D1_BITMAP_PROPERTIES1 bmpProps = {};
bmpProps.pixelFormat = { DXGI_FORMAT_R32G32B32A32_FLOAT, D2D1_ALPHA_MODE_PREMULTIPLIED };
bmpProps.bitmapOptions = D2D1_BITMAP_OPTIONS_CPU_READ | D2D1_BITMAP_OPTIONS_CANNOT_DRAW;
winrt::com_ptr<ID2D1Bitmap1> readBitmap;
HRESULT hr = dc->CreateBitmap(D2D1::SizeU(1, 1), nullptr, 0, bmpProps, readBitmap.put());
if (FAILED(hr)) return { 500, R"({"error":"Failed to create read bitmap"})" };
D2D1_RECT_U srcRect = { srcPoint.x, srcPoint.y, srcPoint.x + 1, srcPoint.y + 1 };
// Need to render the image to a target first, then copy.
// For simplicity, report from the cached pixel inspector logic.
// TODO: implement proper pixel readback
return { 200, std::format("{{\"x\":{:.0f},\"y\":{:.0f},\"note\":\"Pixel readback via MCP coming soon\"}}", x, y) };
});
// =====================================================================
// =====================================================================
// GET /render/capture -- Save output PNG to temp file, return path
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/render/capture", [this](const std::wstring&, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
return m_renderDispatcher.DispatchSync(
[this]() -> ::ShaderLab::McpHttpServer::Response {
// Run on render thread (single writer to graph + owns the
// engine D2D context). Force a full re-evaluation so the
// capture reflects current state.
m_graph.MarkAllDirty();
RenderFrameToOffscreen(0.0);
auto pngData = CapturePreviewAsPng();
if (pngData.empty())
return { 404, R"({"error":"No output image"})" };
// Write to temp file.
wchar_t tempPath[MAX_PATH]{};
GetTempPathW(MAX_PATH, tempPath);
std::wstring filePath = std::wstring(tempPath) + L"shaderlab_capture.png";
HANDLE hFile = CreateFileW(filePath.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE)
return { 500, R"({"error":"Failed to create temp file"})" };
DWORD written = 0;
WriteFile(hFile, pngData.data(), static_cast<DWORD>(pngData.size()), &written, nullptr);
CloseHandle(hFile);
auto pathUtf8 = ToUtf8(filePath);
// Escape backslashes for JSON.
std::string escaped;
for (char c : pathUtf8) { if (c == '\\') escaped += "\\\\"; else escaped += c; }
return { 200, std::format("{{\"path\":\"{}\",\"size\":{}}}", escaped, pngData.size()) };
});
});
// =====================================================================
// GET /perf — Return per-frame performance timings
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/perf", [this](const std::wstring&, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
auto& t = m_lastFrameTiming;
if (t.framesSampled == 0)
t = m_frameTiming; // fallback to live if no snapshot yet
double fps = (t.totalUs > 0) ? 1000000.0 / t.totalUs : 0;
return { 200, std::format(
"{{\"fps\":{:.1f},\"totalMs\":{:.2f},"
"\"sourcesPrepMs\":{:.2f},\"evaluateMs\":{:.2f},"
"\"deferredComputeMs\":{:.2f},\"drawMs\":{:.2f},"
"\"endDrawFlushMs\":{:.2f},"
"\"uiTickMs\":{:.2f},\"outputWindowsMs\":{:.2f},\"traceMs\":{:.2f},"
"\"computeDispatches\":{},"
"\"framesSampled\":{},\"endDrawFailed\":{}}}",
fps, t.totalUs / 1000.0,
t.sourcesPrepUs / 1000.0, t.evaluateUs / 1000.0,
t.deferredComputeUs / 1000.0, t.drawUs / 1000.0,
t.endDrawFlushUs / 1000.0,
t.uiTickUs / 1000.0, t.outputWindowsUs / 1000.0, t.traceUs / 1000.0,
t.computeDispatches,
t.framesSampled, t.endDrawFailed) };
});
// =====================================================================
// GET /node/{id}/logs — Return per-node log entries
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/node/", [this](const std::wstring& path, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
// Parse nodeId and optional /logs suffix from path.
// Expected: /node/{id}/logs or /node/{id}/logs?since={seq}
auto stripped = path.substr(6); // remove "/node/"
uint32_t nodeId = 0;
try { nodeId = static_cast<uint32_t>(std::stoi(stripped)); } catch (...) {
return { 400, R"({"error":"Invalid node ID"})" };
}
auto it = m_nodeLogs.find(nodeId);
if (it == m_nodeLogs.end())
return { 200, R"({"logs":[]})" };
auto& log = it->second;
// Check for ?since= parameter.
uint64_t sinceSeq = 0;
auto qPos = path.find(L"since=");
if (qPos != std::wstring::npos)
{
try { sinceSeq = std::stoull(path.substr(qPos + 6)); } catch (...) {}
}
std::string json = "{\"logs\":[";
bool first = true;
for (const auto& entry : log.Entries())
{
if (entry.sequence <= sinceSeq) continue;
if (!first) json += ",";
first = false;
auto tt = std::chrono::system_clock::to_time_t(entry.timestamp);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
entry.timestamp.time_since_epoch()).count() % 1000;
struct tm tm_buf{};
localtime_s(&tm_buf, &tt);
char timeBuf[32]{};
sprintf_s(timeBuf, "%02d:%02d:%02d.%03d",
tm_buf.tm_hour, tm_buf.tm_min, tm_buf.tm_sec, static_cast<int>(ms));
const char* levelStr = "Info";
if (entry.level == ::ShaderLab::Controls::LogLevel::Warning) levelStr = "Warning";
else if (entry.level == ::ShaderLab::Controls::LogLevel::Error) levelStr = "Error";
// JSON-escape the message.
std::string msg = ToUtf8(entry.message);
std::string escaped;
for (char c : msg) {
if (c == '"') escaped += "\\\"";
else if (c == '\\') escaped += "\\\\";
else if (c == '\n') escaped += "\\n";
else if (c == '\r') escaped += "\\r";
else if (c == '\t') escaped += "\\t";
else if (static_cast<unsigned char>(c) < 0x20)
escaped += std::format("\\u{:04x}", static_cast<unsigned char>(c));
else escaped += c;
}
json += std::format("{{\"seq\":{},\"time\":\"{}\",\"level\":\"{}\",\"message\":\"{}\"}}",
entry.sequence, timeBuf, levelStr, escaped);
}
json += "]}";
return { 200, json };
});
});
// =====================================================================
// POST /graph/bind-property -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// POST /graph/unbind-property -- moved to Engine/Mcp/EngineMcpRoutes.cpp
// =====================================================================
// =====================================================================
// GET /analysis/{id} -- moved to Engine/Mcp/EngineMcpRoutes.cpp (Phase 7).
// =====================================================================
// =====================================================================
// POST /render/pixel-trace — Run pixel trace at normalized coordinates
// =====================================================================
m_mcpServer->AddRoute(L"POST", L"/render/pixel-trace", [this](const std::wstring&, const std::string& body)
-> ::ShaderLab::McpHttpServer::Response
{
try
{
auto jobj = winrt::Windows::Data::Json::JsonObject::Parse(winrt::to_hstring(body));
uint32_t nodeId = static_cast<uint32_t>(jobj.GetNamedNumber(L"nodeId"));
float normX = static_cast<float>(jobj.GetNamedNumber(L"x"));
float normY = static_cast<float>(jobj.GetNamedNumber(L"y"));
return m_renderDispatcher.DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
// P13: pixel-trace runs on the render thread. m_graph is
// single-writer there; the render-side D2D context shares
// the engine's multi-threaded D2D device with the worker's
// BeginDraw session. UI's PopulatePixelTraceTree also
// routes its ReTrace through the render dispatcher, so
// there's no concurrent access to m_pixelTrace state.
auto* dc = m_renderEngine.RenderD2DContext();
if (!dc) return { 500, R"({"error":"No device context"})" };
// Compute preview image bounds inline on render context
// (can't call MainWindow::GetPreviewImageBounds, which
// reads from the UI D2D context).
auto* previewNode = m_graph.FindNode(m_previewNodeId);
auto* previewImage = previewNode ? previewNode->cachedOutput : nullptr;
if (!previewImage) return { 404, R"({"error":"No preview image"})" };
float oldDpiX, oldDpiY;
dc->GetDpi(&oldDpiX, &oldDpiY);
dc->SetDpi(96.0f, 96.0f);
D2D1_RECT_F bounds{};
HRESULT bhr = dc->GetImageLocalBounds(previewImage, &bounds);
dc->SetDpi(oldDpiX, oldDpiY);
if (FAILED(bhr)) return { 500, R"({"error":"GetImageLocalBounds failed"})" };
uint32_t imageW = static_cast<uint32_t>(bounds.right - bounds.left);
uint32_t imageH = static_cast<uint32_t>(bounds.bottom - bounds.top);
if (imageW == 0 || imageH == 0)
return { 404, R"({"error":"No preview image"})" };
if (!m_pixelTrace.BuildTrace(dc, m_graph, nodeId, normX, normY, imageW, imageH))
return { 500, R"({"error":"Pixel trace failed"})" };
const auto& root = m_pixelTrace.Root();
uint32_t pixelX = static_cast<uint32_t>(normX * imageW);
uint32_t pixelY = static_cast<uint32_t>(normY * imageH);
// Recursive lambda to serialize the trace tree.
std::function<std::string(const ::ShaderLab::Controls::PixelTraceNode&)> serializeNode;
serializeNode = [&](const ::ShaderLab::Controls::PixelTraceNode& tn) -> std::string
{
std::string j = "{";
j += std::format("\"nodeId\":{},\"name\":\"{}\",\"pin\":\"{}\"",
tn.nodeId, ToUtf8(tn.nodeName), ToUtf8(tn.pinName));
// Pixel values.
const auto& px = tn.pixel;
j += std::format(",\"pixel\":{{\"scRGB\":[{:.6f},{:.6f},{:.6f},{:.6f}]",
px.scR, px.scG, px.scB, px.scA);
j += std::format(",\"sRGB\":[{},{},{},{}]",
px.sR, px.sG, px.sB, px.sA);
j += std::format(",\"luminance\":{:.2f}}}", px.luminanceNits);
// Analysis fields (for compute/analysis nodes).
if (tn.hasAnalysisOutput && !tn.analysisFields.empty())
{
j += ",\"analysisFields\":[";
bool first = true;
for (const auto& fv : tn.analysisFields)
{
if (!first) j += ",";
j += "{\"name\":\"" + ToUtf8(fv.name) + "\"";
std::string typeTag;
switch (fv.type)
{
case ::ShaderLab::Graph::AnalysisFieldType::Float: typeTag = "float"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2: typeTag = "float2"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3: typeTag = "float3"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4: typeTag = "float4"; break;
case ::ShaderLab::Graph::AnalysisFieldType::FloatArray: typeTag = "floatarray"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float2Array: typeTag = "float2array"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float3Array: typeTag = "float3array"; break;
case ::ShaderLab::Graph::AnalysisFieldType::Float4Array: typeTag = "float4array"; break;
}
j += ",\"type\":\"" + typeTag + "\"";
if (!::ShaderLab::Graph::AnalysisFieldIsArray(fv.type))
{
uint32_t cc = ::ShaderLab::Graph::AnalysisFieldComponentCount(fv.type);
j += ",\"value\":[";
for (uint32_t c = 0; c < cc; ++c)
{
if (c > 0) j += ",";
j += std::format("{:.6f}", fv.components[c]);
}
j += "]";
}
else
{
uint32_t stride = ::ShaderLab::Graph::AnalysisFieldComponentCount(fv.type);
uint32_t count = stride > 0 ? static_cast<uint32_t>(fv.arrayData.size()) / stride : 0;
j += ",\"count\":" + std::to_string(count);
j += ",\"value\":[";
for (size_t i = 0; i < fv.arrayData.size(); ++i)
{
if (i > 0) j += ",";
j += std::format("{:.6f}", fv.arrayData[i]);
}
j += "]";
}
j += "}";
first = false;
}
j += "]";
}
else
{
j += ",\"analysisFields\":[]";
}
// Recurse into inputs.
j += ",\"inputs\":[";
for (size_t i = 0; i < tn.inputs.size(); ++i)
{
if (i > 0) j += ",";
j += serializeNode(tn.inputs[i]);
}
j += "]";
j += "}";
return j;
};
std::string json = "{";
json += std::format("\"position\":{{\"x\":{:.6f},\"y\":{:.6f},\"pixelX\":{},\"pixelY\":{}}}",
normX, normY, pixelX, pixelY);
json += ",\"nodes\":[" + serializeNode(root) + "]";
json += "}";
return { 200, json };
});
}
catch (...) { return { 400, R"({"error":"Invalid request"})" }; }
});
// =====================================================================
// Graph editor view (snapshot + pan/zoom)
// =====================================================================
// POST /graph/snapshot — body: { "inline": bool? }
// Captures the live node-graph view at the swap-chain panel size.
// Always writes PNG to a unique %TEMP% file. When inline=true, also
// returns base64-encoded bytes in the response.
m_mcpServer->AddRoute(L"POST", L"/graph/snapshot", [this](const std::wstring&, const std::string& body)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
bool wantInline = false;
if (!body.empty())
{
winrt::Windows::Data::Json::JsonObject jo{ nullptr };
if (winrt::Windows::Data::Json::JsonObject::TryParse(winrt::to_hstring(body), jo))
{
if (jo.HasKey(L"inline"))
{
auto v = jo.GetNamedValue(L"inline");
if (v.ValueType() == winrt::Windows::Data::Json::JsonValueType::Boolean)
wantInline = v.GetBoolean();
}
}
}
auto pngData = CaptureGraphAsPng();
if (pngData.empty())
return { 500, R"({"error":"Snapshot failed"})" };
// Unique temp filename to avoid concurrent-capture overwrites.
static std::atomic<uint32_t> s_seq{ 0 };
uint32_t seq = s_seq.fetch_add(1, std::memory_order_relaxed);
wchar_t tempPath[MAX_PATH]{};
GetTempPathW(MAX_PATH, tempPath);
std::wstring filePath = std::format(L"{}shaderlab_graph_snapshot_{}_{}.png",
tempPath, GetCurrentProcessId(), seq);
HANDLE hFile = CreateFileW(filePath.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE)
return { 500, R"({"error":"Failed to create temp file"})" };
DWORD written = 0;
WriteFile(hFile, pngData.data(), static_cast<DWORD>(pngData.size()), &written, nullptr);
CloseHandle(hFile);
auto pathUtf8 = ToUtf8(filePath);
std::string escapedPath;
for (char c : pathUtf8) { if (c == '\\') escapedPath += "\\\\"; else escapedPath += c; }
if (wantInline)
{
auto b64 = Base64Encode(pngData.data(), pngData.size());
return { 200, std::format(
"{{\"path\":\"{}\",\"size\":{},\"width\":{},\"height\":{},"
"\"mimeType\":\"image/png\",\"base64\":\"{}\"}}",
escapedPath, pngData.size(),
m_graphPanelWidth, m_graphPanelHeight, b64) };
}
return { 200, std::format(
"{{\"path\":\"{}\",\"size\":{},\"width\":{},\"height\":{},\"mimeType\":\"image/png\"}}",
escapedPath, pngData.size(),
m_graphPanelWidth, m_graphPanelHeight) };
});
});
// GET /graph/view — current pan/zoom + viewport + content bounds
m_mcpServer->AddRoute(L"GET", L"/graph/view", [this](const std::wstring&, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
m_nodeGraphController.RebuildLayout();
auto pan = m_nodeGraphController.PanOffset();
float zoom = m_nodeGraphController.Zoom();
auto b = m_nodeGraphController.ContentBounds();
float cw = (std::max)(0.0f, b.right - b.left);
float ch = (std::max)(0.0f, b.bottom - b.top);
return { 200, std::format(
"{{\"zoom\":{:.6f},\"panX\":{:.6f},\"panY\":{:.6f}"
",\"viewportW\":{},\"viewportH\":{}"
",\"contentBounds\":{{\"x\":{:.6f},\"y\":{:.6f},\"w\":{:.6f},\"h\":{:.6f}}}"
",\"zoomLimits\":{{\"min\":0.1,\"max\":5.0}}"
"}}",
zoom, pan.x, pan.y,
m_graphPanelWidth, m_graphPanelHeight,
b.left, b.top, cw, ch) };
});
});
// POST /graph/view — body: { zoom?, panX?, panY? }
m_mcpServer->AddRoute(L"POST", L"/graph/view", [this](const std::wstring&, const std::string& body)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
winrt::Windows::Data::Json::JsonObject jo{ nullptr };
if (!winrt::Windows::Data::Json::JsonObject::TryParse(winrt::to_hstring(body), jo))
return { 400, R"({"error":"Invalid JSON body"})" };
auto pan = m_nodeGraphController.PanOffset();
float zoom = m_nodeGraphController.Zoom();
bool changed = false;
if (jo.HasKey(L"zoom"))
{
auto v = jo.GetNamedValue(L"zoom");
if (v.ValueType() != winrt::Windows::Data::Json::JsonValueType::Number)
return { 400, R"({"error":"'zoom' must be a number"})" };
zoom = static_cast<float>(v.GetNumber());
m_nodeGraphController.SetZoom(zoom);
changed = true;
}
if (jo.HasKey(L"panX"))
{
auto v = jo.GetNamedValue(L"panX");
if (v.ValueType() != winrt::Windows::Data::Json::JsonValueType::Number)
return { 400, R"({"error":"'panX' must be a number"})" };
pan.x = static_cast<float>(v.GetNumber());
changed = true;
}
if (jo.HasKey(L"panY"))
{
auto v = jo.GetNamedValue(L"panY");
if (v.ValueType() != winrt::Windows::Data::Json::JsonValueType::Number)
return { 400, R"({"error":"'panY' must be a number"})" };
pan.y = static_cast<float>(v.GetNumber());
changed = true;
}
if (jo.HasKey(L"panX") || jo.HasKey(L"panY"))
m_nodeGraphController.SetPanOffset(pan.x, pan.y);
// Re-read post-clamp.
auto p2 = m_nodeGraphController.PanOffset();
float z2 = m_nodeGraphController.Zoom();
return { 200, std::format(
"{{\"ok\":true,\"changed\":{},\"zoom\":{:.6f},\"panX\":{:.6f},\"panY\":{:.6f}}}",
changed ? "true" : "false", z2, p2.x, p2.y) };
});
});
// POST /graph/view/fit — body: { padding?:number (DIPs, default 40) }
m_mcpServer->AddRoute(L"POST", L"/graph/view/fit", [this](const std::wstring&, const std::string& body)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {
float padding = 40.0f;
if (!body.empty())
{
winrt::Windows::Data::Json::JsonObject jo{ nullptr };
if (winrt::Windows::Data::Json::JsonObject::TryParse(winrt::to_hstring(body), jo)
&& jo.HasKey(L"padding"))
{
auto v = jo.GetNamedValue(L"padding");
if (v.ValueType() == winrt::Windows::Data::Json::JsonValueType::Number)
padding = static_cast<float>(v.GetNumber());
}
}
FitGraphView(padding);
auto p = m_nodeGraphController.PanOffset();
float z = m_nodeGraphController.Zoom();
auto b = m_nodeGraphController.ContentBounds();
bool empty = !(b.right > b.left && b.bottom > b.top);
return { 200, std::format(
"{{\"ok\":true,\"empty\":{},\"zoom\":{:.6f},\"panX\":{:.6f},\"panY\":{:.6f}}}",
empty ? "true" : "false", z, p.x, p.y) };
});
});
// =====================================================================
// GET /gpu/list — Enumerate GPU adapters + identify the active one
// =====================================================================
m_mcpServer->AddRoute(L"GET", L"/gpu/list", [this](const std::wstring&, const std::string&)
-> ::ShaderLab::McpHttpServer::Response
{
return DispatchSync([&]() -> ::ShaderLab::McpHttpServer::Response {