-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDAZStudioMCPPlugin.cpp
More file actions
5739 lines (5288 loc) · 281 KB
/
Copy pathDAZStudioMCPPlugin.cpp
File metadata and controls
5739 lines (5288 loc) · 281 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 "DAZStudioMCPPlugin.h"
#include "dzplugin.h"
#include "dzundostack.h"
#include "dzexportmgr.h"
#include "dzfloatproperty.h"
#include "dzenumproperty.h"
#include "dznumericproperty.h"
#include "dzselectionmap.h"
#include "dzfacetmesh.h"
#include "dzvertexmesh.h"
#include "dzinstancenode.h"
#include "dzscript.h"
#include "dzbox3.h"
#include "dzmodifier.h"
#include "dzvec3.h"
#include "dzfileiosettings.h"
#include "dzexporter.h"
#include "Log.h"
#include "JsonUtil.h"
#include "ExportOptions.h"
#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
#include <cstdlib>
#include <functional>
#include <unordered_map>
#include <sstream>
#include <string>
#include <mutex>
#include <condition_variable>
#include <QtCore/QCoreApplication>
#include <QtCore/QEvent>
#include <QtCore/QTimer>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <nlohmann/json.hpp>
static MCPState g_state = {nullptr, 8765};
static std::string JsonEscape(const QString& value);
class RunScriptEvent : public QEvent {
public:
static const QEvent::Type EventType = static_cast<QEvent::Type>(QEvent::User + 100);
QString script;
QString argsJson;
QString* resultOut;
std::mutex* mtx;
std::condition_variable* cv;
bool* done;
RunScriptEvent(const QString& s, const QString& a, QString* r, std::mutex* m, std::condition_variable* c, bool* d)
: QEvent(EventType), script(s), argsJson(a), resultOut(r), mtx(m), cv(c), done(d) {}
};
class ExportSceneEvent : public QEvent {
public:
static const QEvent::Type EventType = static_cast<QEvent::Type>(QEvent::User + 101);
QString path;
QString settingsJson;
QString* resultOut;
std::mutex* mtx;
std::condition_variable* cv;
bool* done;
ExportSceneEvent(const QString& p, const QString& s, QString* r, std::mutex* m, std::condition_variable* c, bool* d)
: QEvent(EventType), path(p), settingsJson(s), resultOut(r), mtx(m), cv(c), done(d) {}
};
class ScriptExecutor : public QObject {
public:
ScriptExecutor(QObject* parent = nullptr) : QObject(parent) {}
protected:
void customEvent(QEvent* e) override {
if (e->type() == RunScriptEvent::EventType) {
RunScriptEvent* rse = static_cast<RunScriptEvent*>(e);
std::string escapedArgs = JsonEscape(rse->argsJson.isEmpty() ? "{}" : rse->argsJson);
QString fullScript = QString(
"var __args = JSON.parse('%1');\n"
"(function(){\n%2\n}).call(null, __args);\n"
).arg(escapedArgs.c_str()).arg(rse->script);
DzScript dzScript;
dzScript.addLine(fullScript);
if (dzScript.execute()) {
*rse->resultOut = "{\"success\":true}";
} else {
*rse->resultOut = "{\"success\":false}";
}
{
std::lock_guard<std::mutex> lock(*rse->mtx);
*rse->done = true;
}
rse->cv->notify_one();
} else if (e->type() == ExportSceneEvent::EventType) {
ExportSceneEvent* ese = static_cast<ExportSceneEvent*>(e);
bool success = false;
if (dzApp && dzApp->getExportMgr()) {
DzExportMgr* exportMgr = dzApp->getExportMgr();
int exporterIndex = exportMgr->findExporterIndex(ese->path);
if (exporterIndex >= 0) {
DzExporter* exporter = exportMgr->getExporter(exporterIndex);
if (exporter) {
ExportOptions opts = ExportOptions::fromJson(ese->settingsJson);
DzFileIOSettings ioSettings;
opts.applyToSettings(&ioSettings);
DzError err = exporter->writeFile(ese->path, &ioSettings);
if (err == DZ_NO_ERROR) {
*ese->resultOut = "{\"success\":true}";
success = true;
}
}
}
}
if (!success) {
*ese->resultOut = "{\"success\":false}";
}
{
std::lock_guard<std::mutex> lock(*ese->mtx);
*ese->done = true;
}
ese->cv->notify_one();
}
}
};
static ScriptExecutor* g_scriptExecutor = nullptr;
static std::string JsonEscape(const QString& value) {
std::string input = value.toUtf8().constData();
std::ostringstream out;
for (char ch : input) {
switch (ch) {
case '\\': out << "\\\\"; break;
case '"': out << "\\\""; break;
case '\n': out << "\\n"; break;
case '\r': out << "\\r"; break;
case '\t': out << "\\t"; break;
default: out << ch; break;
}
}
return out.str();
}
static std::string JsonEscape(const char* value) {
return JsonEscape(QString(value ? value : ""));
}
static QString ExtractJsonValue(const std::string& json, const std::string& key) {
std::string needle = "\"" + key + "\"";
size_t keyPos = json.find(needle);
if (keyPos == std::string::npos) return "";
size_t colon = json.find(':', keyPos + needle.size());
if (colon == std::string::npos) return "";
size_t valStart = colon + 1;
while (valStart < json.size() && (json[valStart] == ' ' || json[valStart] == '\t' || json[valStart] == '\r' || json[valStart] == '\n')) {
valStart++;
}
if (valStart >= json.size()) return "";
char firstChar = json[valStart];
if (firstChar == '"') {
std::string raw;
bool escaped = false;
size_t pos = valStart + 1;
for (; pos < json.size(); ++pos) {
char ch = json[pos];
if (escaped) {
switch (ch) {
case '"': raw += '"'; break;
case '\\': raw += '\\'; break;
case '/': raw += '/'; break;
case 'b': raw += '\b'; break;
case 'f': raw += '\f'; break;
case 'n': raw += '\n'; break;
case 'r': raw += '\r'; break;
case 't': raw += '\t'; break;
case 'u': {
if (pos + 4 < json.size()) {
std::string hex = json.substr(pos + 1, 4);
unsigned int codepoint;
std::istringstream(hex) >> std::hex >> codepoint;
if (codepoint <= 0x7F) {
raw += static_cast<char>(codepoint);
} else if (codepoint <= 0x7FF) {
raw += static_cast<char>(0xC0 | (codepoint >> 6));
raw += static_cast<char>(0x80 | (codepoint & 0x3F));
} else {
raw += static_cast<char>(0xE0 | (codepoint >> 12));
raw += static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F));
raw += static_cast<char>(0x80 | (codepoint & 0x3F));
}
pos += 4;
}
break;
}
default: raw += ch; break;
}
escaped = false;
continue;
}
if (ch == '\\') {
escaped = true;
continue;
}
if (ch == '"') break;
raw += ch;
}
return QString::fromUtf8(raw.c_str());
} else if (firstChar == '{' || firstChar == '[') {
char closeChar = (firstChar == '{') ? '}' : ']';
int depth = 1;
size_t idx = valStart + 1;
bool inString = false;
bool escaped = false;
for (; idx < json.size(); ++idx) {
char ch = json[idx];
if (escaped) {
escaped = false;
continue;
}
if (ch == '\\' && inString) {
escaped = true;
continue;
}
if (ch == '"') {
inString = !inString;
continue;
}
if (!inString) {
if (ch == firstChar) {
depth++;
} else if (ch == closeChar) {
depth--;
if (depth == 0) {
idx++;
break;
}
}
}
}
if (depth != 0 || idx > json.size()) return "";
return QString::fromUtf8(json.substr(valStart, idx - valStart).c_str());
} else {
size_t idx = valStart;
for (; idx < json.size(); ++idx) {
char ch = json[idx];
if (ch == ',' || ch == '}' || ch == ']' || ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') {
break;
}
}
return QString::fromUtf8(json.substr(valStart, idx - valStart).c_str());
}
}
static QString ExtractJsonString(const std::string& json, const std::string& key) {
return ExtractJsonValue(json, key);
}
static QString ExtractArgString(const std::string& json, const std::string& key) {
return ExtractJsonValue(json, key);
}
static std::string OkResponse(const QString& id, const std::string& data) {
std::ostringstream oss;
oss << "{\"id\":\"" << JsonEscape(id) << "\",\"status\":\"ok\",\"data\":" << data << "}\n";
return oss.str();
}
static std::string ErrorResponse(const QString& id, const QString& error) {
std::ostringstream oss;
oss << "{\"id\":\"" << JsonEscape(id) << "\",\"status\":\"error\",\"error\":\"" << JsonEscape(error) << "\"}\n";
return oss.str();
}
static QString NodeType(DzNode* node) {
if (qobject_cast<DzFigure*>(node)) return "Figure";
if (qobject_cast<DzLight*>(node)) return "Light";
if (qobject_cast<DzCamera*>(node)) return "Camera";
return "Node";
}
static std::string SceneInfoData() {
if (!dzScene) return "{\"available\":false}";
QString filename = dzScene->getFilename();
if (filename.isEmpty()) filename = "Untitled Scene";
std::ostringstream oss;
oss << "{";
oss << "\"scene\":\"" << JsonEscape(filename) << "\",";
oss << "\"nodes\":" << dzScene->getNumNodes() << ",";
oss << "\"lights\":" << dzScene->getNumLights() << ",";
oss << "\"cameras\":" << dzScene->getNumCameras();
DzNode* selected = dzScene->getPrimarySelection();
if (selected) {
oss << ",\"selected\":\"" << JsonEscape(selected->getName()) << "\"";
}
oss << "}";
return oss.str();
}
static std::string NodeListData(bool selectedOnly) {
std::ostringstream oss;
oss << "{\"nodes\":[";
if (dzScene) {
bool first = true;
DzNodeListIterator iter = selectedOnly ? dzScene->selectedNodeListIterator() : dzScene->nodeListIterator();
while (iter.hasNext()) {
DzNode* node = iter.next();
if (!node) continue;
if (!first) oss << ",";
first = false;
oss << "{";
oss << "\"id\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"name\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"type\":\"" << JsonEscape(NodeType(node)) << "\",";
oss << "\"selected\":" << (node->isSelected() ? "true" : "false");
oss << "}";
}
}
oss << "]}";
return oss.str();
}
static std::string CamerasData() {
std::ostringstream oss;
oss << "{\"cameras\":[";
if (dzScene) {
bool first = true;
for (int i = 0; i < dzScene->getNumCameras(); i++) {
DzCamera* camera = dzScene->getCamera(i);
if (!camera) continue;
if (!first) oss << ",";
first = false;
oss << "{\"id\":\"" << JsonEscape(camera->getName()) << "\",";
oss << "\"name\":\"" << JsonEscape(camera->getName()) << "\"}";
}
}
oss << "]}";
return oss.str();
}
static bool SelectNodeInDaz(const QString& nodeId) {
if (!dzScene || nodeId.isEmpty()) return false;
DzNode* node = dzScene->findNode(nodeId);
if (!node) return false;
dzScene->setPrimarySelection(node);
return true;
}
static bool OpenContentFile(const QString& path, bool merge) {
if (!dzApp || path.isEmpty()) return false;
DzContentMgr* contentMgr = dzApp->getContentMgr();
if (!contentMgr) return false;
return contentMgr->openFile(path, merge);
}
static bool ImportContentFile(const QString& path) {
if (!dzApp || path.isEmpty()) return false;
DzContentMgr* contentMgr = dzApp->getContentMgr();
if (!contentMgr) return false;
return contentMgr->importFile(path);
}
static std::string CaptureActiveViewport(const QString& path) {
if (!dzApp) return "";
DzMainWindow* mainWindow = dzApp->getInterface();
if (!mainWindow) return "";
DzViewportMgr* viewportMgr = mainWindow->getViewportMgr();
if (!viewportMgr) return "";
DzViewport* viewport = viewportMgr->getActiveViewport();
if (!viewport) return "";
Dz3DViewport* viewport3d = viewport->get3DViewport();
if (!viewport3d) return "";
QImage image = viewport3d->captureImage();
if (image.isNull()) return "";
if (path == "stream") {
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
return ba.toBase64().constData();
} else if (!path.isEmpty()) {
if (image.save(path)) return path.toStdString();
}
return "";
}
static bool BeginUndoBatch() {
if (!dzUndoStack) return false;
dzUndoStack->beginHold();
return true;
}
static bool AcceptUndoBatch(const QString& caption) {
if (!dzUndoStack) return false;
dzUndoStack->accept(caption);
return true;
}
static bool CancelUndoBatch() {
if (!dzUndoStack) return false;
dzUndoStack->cancel();
return true;
}
static bool AddNode(const QString& type, const QString& name) {
if (!dzScene) return false;
DzNode* newNode = nullptr;
if (type == "point_light") newNode = new DzPointLight();
else if (type == "spot_light") newNode = new DzSpotLight();
else if (type == "distant_light") newNode = new DzDistantLight();
else if (type == "camera") newNode = new DzBasicCamera();
else if (type == "null") newNode = new DzNode();
if (!newNode) return false;
if (!name.isEmpty()) newNode->setName(name);
dzScene->addNode(newNode);
return true;
}
static bool SetProperty(const QString& nodeId, const QString& propName, const QString& valueStr) {
if (!dzScene) return false;
DzNode* node = dzScene->findNode(nodeId);
if (!node) node = dzScene->getPrimarySelection();
if (!node) return false;
DzProperty* prop = node->findProperty(propName);
if (!prop) return false;
if (DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop)) {
fProp->setValue(valueStr.toFloat());
return true;
}
if (DzBoolProperty* bProp = qobject_cast<DzBoolProperty*>(prop)) {
bProp->setBoolValue(valueStr.toLower() == "true" || valueStr == "1");
return true;
}
if (DzColorProperty* cProp = qobject_cast<DzColorProperty*>(prop)) {
QStringList parts = valueStr.split(",");
if (parts.size() >= 3) {
cProp->setColorValue(QColor(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()));
return true;
}
}
if (DzStringProperty* sProp = qobject_cast<DzStringProperty*>(prop)) {
sProp->setValue(valueStr);
return true;
}
return false;
}
static bool SetMaterialProperty(const QString& nodeId, const QString& propName, const QString& valueStr) {
if (!dzScene) return false;
DzNode* node = dzScene->findNode(nodeId);
if (!node) node = dzScene->getPrimarySelection();
if (!node) return false;
DzObject* obj = node->getObject();
if (!obj) return false;
DzShape* shape = obj->getCurrentShape();
if (!shape) return false;
bool setAny = false;
for (int i = 0; i < shape->getNumMaterials(); ++i) {
DzMaterial* mat = shape->getMaterial(i);
if (mat) {
DzProperty* prop = mat->findProperty(propName);
if (prop) {
if (DzColorProperty* cProp = qobject_cast<DzColorProperty*>(prop)) {
QStringList parts = valueStr.split(",");
if (parts.size() >= 3) {
cProp->setColorValue(QColor(parts[0].toInt(), parts[1].toInt(), parts[2].toInt()));
setAny = true;
}
} else if (DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop)) {
fProp->setValue(valueStr.toFloat());
setAny = true;
} else if (DzBoolProperty* bProp = qobject_cast<DzBoolProperty*>(prop)) {
bProp->setBoolValue(valueStr.toLower() == "true" || valueStr == "1");
setAny = true;
} else if (DzStringProperty* sProp = qobject_cast<DzStringProperty*>(prop)) {
sProp->setValue(valueStr);
setAny = true;
}
}
}
}
return setAny;
}
static DzNode* ResolveNodeOrSelection(const QString& nodeId) {
if (!dzScene) return nullptr;
if (!nodeId.isEmpty() && nodeId.toLower() != "selected") {
DzNode* node = dzScene->findNode(nodeId);
if (node) return node;
}
return dzScene->getPrimarySelection();
}
static float ClampOpacity(float value) {
if (value < 0.0f) return 0.0f;
if (value > 1.0f) return 1.0f;
return value;
}
static bool IsInternalSurfaceName(const QString& text) {
QString lower = text.toLower();
const char* keywords[] = {
"skull", "bone", "rib", "spine", "pelvis", "clavicle", "scapula",
"skeleton", "sternum", "vertebra", "femur", "humerus", "anatomy"
};
for (const char* keyword : keywords) {
if (lower.contains(keyword)) return true;
}
return false;
}
static int SetOpacityOnMaterials(DzNode* node, const QString& surfacePattern, float value, QStringList* affectedSurfaces = nullptr) {
if (!node) return 0;
DzObject* obj = node->getObject();
if (!obj) return 0;
DzShape* shape = obj->getCurrentShape();
if (!shape) return 0;
QString pattern = surfacePattern.toLower();
bool matchAll = pattern.isEmpty();
int count = 0;
for (int i = 0; i < shape->getNumMaterials(); ++i) {
DzMaterial* mat = shape->getMaterial(i);
if (!mat) continue;
QString name = mat->getName();
QString label = mat->getLabel();
QString nameLower = name.toLower();
QString labelLower = label.toLower();
bool matches = matchAll ||
nameLower == pattern ||
labelLower == pattern ||
nameLower.contains(pattern) ||
labelLower.contains(pattern);
if (!matches) continue;
DzProperty* prop = mat->findProperty("Opacity");
if (DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop)) {
fProp->setValue(value);
count++;
if (affectedSurfaces) {
affectedSurfaces->append(!label.isEmpty() ? label : name);
}
}
}
return count;
}
static std::string JsonStringArray(const QStringList& values) {
std::ostringstream oss;
oss << "[";
for (int i = 0; i < values.size(); ++i) {
if (i > 0) oss << ",";
oss << "\"" << JsonEscape(values[i]) << "\"";
}
oss << "]";
return oss.str();
}
static QStringList GetInternalSurfaceNames(DzNode* node) {
QStringList surfaces;
if (!node) return surfaces;
DzObject* obj = node->getObject();
if (!obj) return surfaces;
DzShape* shape = obj->getCurrentShape();
if (!shape) return surfaces;
for (int i = 0; i < shape->getNumMaterials(); ++i) {
DzMaterial* mat = shape->getMaterial(i);
if (!mat) continue;
QString name = mat->getName();
QString label = mat->getLabel();
if (IsInternalSurfaceName(name) || IsInternalSurfaceName(label)) {
surfaces.append(!label.isEmpty() ? label : name);
}
}
return surfaces;
}
static DzNode* FindLoadedNode(DzNode* beforeSelection, int beforeNodeCount) {
DzNode* selected = dzScene ? dzScene->getPrimarySelection() : nullptr;
if (selected && selected != beforeSelection) return selected;
if (!dzScene) return selected;
for (int i = dzScene->getNumNodes() - 1; i >= beforeNodeCount; --i) {
DzNode* node = dzScene->getNode(i);
if (node) return node;
}
return selected;
}
static std::string PlaceAssetInsideFigure(const QString& figureId, const QString& assetPath) {
if (!dzScene) return "{\"placed\":false,\"error\":\"No scene\"}";
DzNode* figure = ResolveNodeOrSelection(figureId);
if (!figure) return "{\"placed\":false,\"error\":\"Figure not found\"}";
DzNode* beforeSelection = dzScene->getPrimarySelection();
int beforeNodeCount = dzScene->getNumNodes();
if (!OpenContentFile(assetPath, true)) {
return "{\"placed\":false,\"error\":\"Asset load failed\"}";
}
DzNode* asset = FindLoadedNode(beforeSelection, beforeNodeCount);
if (!asset) return "{\"placed\":false,\"error\":\"Loaded asset node not found\"}";
DzBox3 box = figure->getWSBoundingBox();
DzVec3 minVec = box.getMin();
DzVec3 maxVec = box.getMax();
DzVec3 center(
(minVec.m_x + maxVec.m_x) * 0.5f,
minVec.m_y + ((maxVec.m_y - minVec.m_y) * 0.55f),
(minVec.m_z + maxVec.m_z) * 0.5f
);
asset->setWSPos(center);
figure->addNodeChild(asset, true);
std::ostringstream oss;
oss << "{\"placed\":true,\"figure_id\":\"" << JsonEscape(figure->getName()) << "\",";
oss << "\"node_id\":\"" << JsonEscape(asset->getName()) << "\",";
oss << "\"position\":[" << center.m_x << "," << center.m_y << "," << center.m_z << "]}";
return oss.str();
}
static std::string GetMaterialProperties(const QString& nodeId) {
if (!dzScene) return "{\"materials\":[]}";
DzNode* node = dzScene->findNode(nodeId);
if (!node) node = dzScene->getPrimarySelection();
if (!node) return "{\"materials\":[]}";
DzObject* obj = node->getObject();
if (!obj) return "{\"materials\":[]}";
std::ostringstream oss;
oss << "{\"materials\":[";
bool firstMat = true;
for (int i = 0; i < obj->getNumShapes(); ++i) {
DzShape* shape = obj->getShape(i);
if (!shape) continue;
for (int j = 0; j < shape->getNumMaterials(); ++j) {
DzMaterial* mat = shape->getMaterial(j);
if (!mat) continue;
if (!firstMat) oss << ",";
firstMat = false;
oss << "{";
oss << "\"name\":\"" << JsonEscape(mat->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(mat->getLabel()) << "\",";
oss << "\"properties\":[";
bool firstProp = true;
for (int k = 0; k < mat->getNumProperties(); ++k) {
DzProperty* prop = mat->getProperty(k);
if (!prop) continue;
DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop);
if (!fProp) continue;
if (!firstProp) oss << ",";
firstProp = false;
oss << "{";
oss << "\"name\":\"" << JsonEscape(prop->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(prop->getLabel()) << "\",";
oss << "\"value\":" << fProp->getValue() << ",";
oss << "\"min\":" << fProp->getMin() << ",";
oss << "\"max\":" << fProp->getMax();
oss << "}";
}
oss << "]";
oss << "}";
}
}
oss << "]}";
return oss.str();
}
static std::string GetNodeProperties(const QString& nodeId) {
if (!dzScene) return "{\"properties\":[]}";
DzNode* node = dzScene->findNode(nodeId);
if (!node) node = dzScene->getPrimarySelection();
if (!node) return "{\"properties\":[]}";
std::ostringstream oss;
oss << "{\"properties\":[";
bool first = true;
// We want to collect numeric properties, especially morphs and transform properties
for (int i = 0; i < node->getNumProperties(); ++i) {
DzProperty* prop = node->getProperty(i);
if (!prop) continue;
DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop);
if (!fProp) continue;
if (!first) oss << ",";
first = false;
oss << "{";
oss << "\"name\":\"" << JsonEscape(prop->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(prop->getLabel()) << "\",";
oss << "\"value\":" << fProp->getValue() << ",";
oss << "\"min\":" << fProp->getMin() << ",";
oss << "\"max\":" << fProp->getMax() << ",";
oss << "\"path\":\"" << JsonEscape(prop->getPath()) << "\",";
oss << "\"is_morph\":" << (prop->getPath().contains("Morphs") ? "true" : "false");
oss << "}";
}
oss << "]}";
return oss.str();
}
static bool DeleteNode(const QString& nodeId) {
if (!dzScene) return false;
DzNode* node = dzScene->findNode(nodeId);
if (!node) return false;
dzScene->removeNode(node);
return true;
}
static std::string GetGeoshellsData() {
if (!dzScene) return "{\"shells\":[]}";
std::ostringstream oss;
oss << "{\"shells\":[";
bool first = true;
DzNodeListIterator it = dzScene->nodeListIterator();
while (it.hasNext()) {
DzNode* node = it.next();
if (node && node->inherits("DzGeometryShellNode")) {
if (!first) oss << ",";
first = false;
oss << "{\"id\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"name\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(node->getLabel()) << "\"}";
}
}
oss << "]}";
return oss.str();
}
static std::string GetSceneAssetsData() {
if (!dzScene) return "{\"assets\":[]}";
std::ostringstream oss;
oss << "{\"assets\":[";
bool first = true;
DzNodeListIterator it = dzScene->nodeListIterator();
while (it.hasNext()) {
DzNode* node = it.next();
if (!node) continue;
QString label = node->getLabel();
if (label.isEmpty()) label = node->getName();
if (label.isEmpty()) continue;
if (!first) oss << ",";
first = false;
oss << "\"" << JsonEscape(label) << "\"";
}
oss << "]}";
return oss.str();
}
static bool SetMorphValue(const QString& nodeId, const QString& morphName, const QString& valueStr) {
if (!dzScene) return false;
DzNode* node = dzScene->findNode(nodeId);
if (!node) node = dzScene->getPrimarySelection();
if (!node) return false;
DzProperty* prop = node->findProperty(morphName, false);
if (!prop) {
for (int i = 0; i < node->getNumProperties(); ++i) {
DzProperty* candidate = node->getProperty(i);
if (!candidate) continue;
if (candidate->getName().compare(morphName, Qt::CaseInsensitive) == 0 ||
candidate->getLabel().compare(morphName, Qt::CaseInsensitive) == 0) {
prop = candidate;
break;
}
}
}
if (!prop) return false;
if (DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop)) {
fProp->setValue(valueStr.toFloat());
return true;
}
return SetProperty(nodeId, morphName, valueStr);
}
static bool ApplyRenderSettings(const QString& widthStr, const QString& heightStr) {
if (!dzApp) return false;
int width = widthStr.toInt();
int height = heightStr.toInt();
if (width <= 0) width = 1920;
if (height <= 0) height = 1080;
QString script = QString(
"var rm = App.getRenderMgr();\n"
"if (rm) {\n"
" rm.setRenderImgSize(%1, %2);\n"
" true;\n"
"} else { false; }\n"
).arg(width).arg(height);
DzScript dzScript;
dzScript.addLine(script);
return dzScript.execute();
}
static std::string GetFigureMorphsData(const QString& nodeId) {
if (!dzScene) return "{\"morphs\":[]}";
DzNode* node = dzScene->findNode(nodeId);
if (!node) return "{\"morphs\":[]}";
std::ostringstream oss;
oss << "{\"morphs\":[";
bool first = true;
for (int i = 0; i < node->getNumProperties(); ++i) {
DzProperty* prop = node->getProperty(i);
if (!prop) continue;
QString path = prop->getPath();
if (!path.contains("Morphs")) continue;
DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop);
if (!fProp) continue;
if (!first) oss << ",";
first = false;
oss << "{";
oss << "\"id\":\"" << JsonEscape(prop->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(prop->getLabel()) << "\",";
oss << "\"value\":" << fProp->getValue() << ",";
oss << "\"min\":" << fProp->getMin() << ",";
oss << "\"max\":" << fProp->getMax() << ",";
oss << "\"type\":\"morph\"";
oss << "}";
}
oss << "]}";
return oss.str();
}
static std::string GetFittedItemsData(const QString& nodeId) {
if (!dzScene) return "{\"items\":[]}";
DzNode* figure = dzScene->findNode(nodeId);
if (!figure) return "{\"items\":[]}";
std::ostringstream oss;
oss << "{\"items\":[";
bool first = true;
// Iterate all nodes and check if they are children of the figure or wearables
DzNodeListIterator it = dzScene->nodeListIterator();
while (it.hasNext()) {
DzNode* node = it.next();
if (!node || node == figure) continue;
// Check if this node's label suggests it's fitted clothing
QString label = node->getLabel();
if (label.isEmpty()) continue;
// A fitted item is typically a child of the figure or has a fitting relationship
bool isFitted = false;
if (node->getNodeParent() == figure) {
isFitted = true;
}
// Also check if it's a wearable/fitted item via label heuristics
if (!isFitted) {
QString lower = label.toLower();
if (lower.contains("wearable") || lower.contains("outfit") ||
lower.contains("clothing") || lower.contains("fit")) {
isFitted = true;
}
}
if (!isFitted) continue;
if (!first) oss << ",";
first = false;
oss << "{\"node_id\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(label) << "\"}";
}
oss << "]}";
return oss.str();
}
static std::string GetActiveExpressionsData(const QString& nodeId) {
if (!dzScene) return "{\"expressions\":[]}";
DzNode* node = dzScene->findNode(nodeId);
if (!node) return "{\"expressions\":[]}";
std::ostringstream oss;
oss << "{\"expressions\":[";
bool first = true;
for (int i = 0; i < node->getNumProperties(); ++i) {
DzProperty* prop = node->getProperty(i);
if (!prop) continue;
QString path = prop->getPath();
if (!path.contains("Expression")) continue;
DzFloatProperty* fProp = qobject_cast<DzFloatProperty*>(prop);
if (!fProp) continue;
if (!first) oss << ",";
first = false;
oss << "{";
oss << "\"id\":\"" << JsonEscape(prop->getName()) << "\",";
oss << "\"label\":\"" << JsonEscape(prop->getLabel()) << "\",";
oss << "\"value\":" << fProp->getValue();
oss << "}";
}
oss << "]}";
return oss.str();
}
static std::string GetTimelineStateData() {
if (!dzScene) return "{\"available\":false}";
std::ostringstream oss;
int curFrame = dzScene->getFrame();
DzTimeRange playRange = dzScene->getPlayRange();
DzTime timeStep = dzScene->getTimeStep();
float fps = 30.0f;
if (timeStep > 0) {
fps = 1.0f / (static_cast<float>(timeStep) / 1000.0f);
}
oss << "{";
oss << "\"current_frame\":" << curFrame << ",";
oss << "\"start_frame\":" << (playRange.getStart() / timeStep) << ",";
oss << "\"end_frame\":" << (playRange.getEnd() / timeStep) << ",";
oss << "\"fps\":" << fps << ",";
oss << "\"is_playing\":false";
oss << "}";
return oss.str();
}
static std::string GetBoundingBoxesData() {
if (!dzScene) return "{\"bounds\":[]}";
std::ostringstream oss;
oss << "{\"bounds\":[";
bool first = true;
DzNodeListIterator it = dzScene->nodeListIterator();
while (it.hasNext()) {
DzNode* node = it.next();
if (!node) continue;
DzBox3 box = node->getWSBoundingBox();
DzVec3 minVec = box.getMin();
DzVec3 maxVec = box.getMax();
DzVec3 centerVec = box.getCenter();
if (!first) oss << ",";
first = false;
oss << "{";
oss << "\"node_id\":\"" << JsonEscape(node->getName()) << "\",";
oss << "\"min\":[" << minVec.m_x << "," << minVec.m_y << "," << minVec.m_z << "],";
oss << "\"max\":[" << maxVec.m_x << "," << maxVec.m_y << "," << maxVec.m_z << "],";
oss << "\"center\":[" << centerVec.m_x << "," << centerVec.m_y << "," << centerVec.m_z << "]";
oss << "}";
}
oss << "]}";
return oss.str();
}
using CommandHandler = std::function<std::string(const QString& id, const std::string& line)>;
static std::string CommandsData();
static std::unordered_map<std::string, CommandHandler> BuildCommandHandlers() {
std::unordered_map<std::string, CommandHandler> handlers;
// ─── dForce / Physics Commands (via DazScript) ────────────────────────────