-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMCPServer.cpp
More file actions
2673 lines (2278 loc) · 103 KB
/
MCPServer.cpp
File metadata and controls
2673 lines (2278 loc) · 103 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 "MCPServer.h"
#include "mainwindow.h"
#include "Manager.h"
#include "MaterialEditorQML.h"
#include "PrimitiveObject.h"
#include "SelectionSet.h"
#include "TransformOperator.h"
#include "MeshImporterExporter.h"
#include "OgreWidget.h"
#include "AnimationWidget.h"
#include "NormalVisualizer.h"
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QTemporaryFile>
#include <QImage>
#include <QBuffer>
#include "SentryReporter.h"
#include <QTimer>
#include <QDateTime>
#include <QMetaObject>
#include <QPixmap>
#include <OgreException.h>
#include <OgreMaterialManager.h>
#include <OgreMaterial.h>
#include <OgreTechnique.h>
#include <OgrePass.h>
#include <OgreMaterialSerializer.h>
#include <OgreTextureManager.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreSubMesh.h>
#include <OgreMesh.h>
#include <cmath>
#include <OgreSkeleton.h>
#include <OgreAnimation.h>
#include <OgreAnimationState.h>
#include <OgreKeyFrame.h>
#include <OgreBone.h>
#include "AnimationMerger.h"
#ifdef Q_OS_WIN
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif
MCPServer::MCPServer(QObject *parent)
: QObject(parent)
{
#ifdef Q_OS_WIN
// Set stdin/stdout to binary mode on Windows
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
}
MCPServer::~MCPServer()
{
stop();
}
void MCPServer::setMainWindow(MainWindow *mainWindow)
{
m_mainWindow = mainWindow;
}
void MCPServer::setOutputFd(int fd)
{
m_stdoutFd = fd;
}
void MCPServer::start()
{
if (m_running) return;
m_stdinFd = fileno(stdin);
// Create notifier for stdin using the raw file descriptor
m_stdinNotifier = new QSocketNotifier(m_stdinFd, QSocketNotifier::Read, this);
connect(m_stdinNotifier, &QSocketNotifier::activated, this, &MCPServer::onReadyRead);
m_running = true;
qDebug() << "MCP Server started";
}
void MCPServer::stop()
{
stopHttp();
if (!m_running) return;
if (m_stdinNotifier) {
m_stdinNotifier->setEnabled(false);
delete m_stdinNotifier;
m_stdinNotifier = nullptr;
}
m_running = false;
qDebug() << "MCP Server stopped";
}
void MCPServer::stopHttp()
{
if (m_httpServer) {
m_httpServer->close();
delete m_httpServer;
m_httpServer = nullptr;
qDebug() << "HTTP REST API stopped";
}
}
bool MCPServer::isHttpRunning() const
{
return m_httpServer && m_httpServer->isListening();
}
int MCPServer::httpPort() const
{
return m_httpPort;
}
void MCPServer::onReadyRead()
{
// Read available data directly from file descriptor (not C FILE*)
char buf[4096];
ssize_t bytesRead = read(m_stdinFd, buf, sizeof(buf));
if (bytesRead <= 0) {
// EOF or error - disable notifier to prevent busy loop
if (m_stdinNotifier)
m_stdinNotifier->setEnabled(false);
// In headless MCP mode (no GUI), quit when the client disconnects
if (!m_mainWindow) {
qDebug() << "MCP: stdin closed, shutting down";
QCoreApplication::quit();
}
return;
}
QByteArray data(buf, bytesRead);
m_buffer.append(data);
// MCP uses Content-Length header like LSP
// Format: Content-Length: <length>\r\n\r\n<json>
while (!m_buffer.isEmpty()) {
// Look for Content-Length header
int headerEnd = m_buffer.indexOf("\r\n\r\n");
if (headerEnd == -1) break;
QString header = QString::fromUtf8(m_buffer.left(headerEnd));
if (!header.startsWith("Content-Length:")) {
// Invalid header, try to recover
m_buffer.remove(0, 1);
continue;
}
bool ok;
int contentLength = header.mid(16).trimmed().toInt(&ok);
if (!ok || contentLength <= 0) {
m_buffer.remove(0, headerEnd + 4);
continue;
}
int messageStart = headerEnd + 4;
int totalLength = messageStart + contentLength;
if (m_buffer.size() < totalLength) {
// Wait for more data
break;
}
QByteArray messageData = m_buffer.mid(messageStart, contentLength);
m_buffer.remove(0, totalLength);
processMessage(messageData);
}
}
void MCPServer::processMessage(const QByteArray &data)
{
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
if (parseError.error != QJsonParseError::NoError) {
sendError(QJsonValue::Null, -32700, "Parse error: " + parseError.errorString());
return;
}
if (!doc.isObject()) {
sendError(QJsonValue::Null, -32600, "Invalid Request: expected object");
return;
}
QJsonObject request = doc.object();
QString method = request["method"].toString();
QJsonValue id = request["id"];
QJsonObject params = request["params"].toObject();
qDebug() << "MCP Request:" << method;
// MCP notifications (no "id" field) must not receive a response.
bool isNotification = !request.contains("id");
// Handle MCP notifications (no response sent)
if (method == "initialized" || method == "notifications/initialized") {
// Post-handshake notification — nothing to do
return;
}
if (method == "notifications/cancelled") {
return;
}
// All other notifications are silently ignored per MCP spec
if (isNotification) {
qDebug() << "MCP: ignoring unknown notification:" << method;
return;
}
QJsonObject result;
// Handle MCP request methods
if (method == "initialize") {
result = handleInitialize(params);
} else if (method == "tools/list") {
result = handleToolsList();
} else if (method == "tools/call") {
result = handleToolsCall(params);
} else if (method == "resources/list") {
result = handleResourcesList();
} else if (method == "resources/read") {
result = handleResourcesRead(params);
} else if (method == "ping") {
result = QJsonObject();
} else {
sendError(id, -32601, "Method not found: " + method);
return;
}
// Send response (only for requests with an id)
QJsonObject response;
response["jsonrpc"] = "2.0";
response["id"] = id;
response["result"] = result;
sendResponse(response);
}
void MCPServer::sendResponse(const QJsonObject &response)
{
QJsonDocument doc(response);
QByteArray data = doc.toJson(QJsonDocument::Compact);
QByteArray header = QString("Content-Length: %1\r\n\r\n").arg(data.size()).toUtf8();
QByteArray output = header + data;
// Write to the saved stdout fd (not current stdout which may be redirected to stderr)
const char *ptr = output.constData();
qint64 remaining = output.size();
while (remaining > 0) {
ssize_t written = write(m_stdoutFd, ptr, remaining);
if (written <= 0) break;
ptr += written;
remaining -= written;
}
}
void MCPServer::sendError(const QJsonValue &id, int code, const QString &message)
{
QJsonObject error;
error["code"] = code;
error["message"] = message;
QJsonObject response;
response["jsonrpc"] = "2.0";
response["id"] = id;
response["error"] = error;
sendResponse(response);
}
void MCPServer::sendNotification(const QString &method, const QJsonObject ¶ms)
{
QJsonObject notification;
notification["jsonrpc"] = "2.0";
notification["method"] = method;
notification["params"] = params;
sendResponse(notification);
}
QJsonObject MCPServer::handleInitialize(const QJsonObject ¶ms)
{
Q_UNUSED(params);
m_initialized = true;
QJsonObject capabilities;
capabilities["tools"] = QJsonObject();
capabilities["resources"] = QJsonObject();
QJsonObject serverInfo;
serverInfo["name"] = SERVER_NAME;
serverInfo["version"] = SERVER_VERSION;
QJsonObject result;
result["protocolVersion"] = MCP_VERSION;
result["capabilities"] = capabilities;
result["serverInfo"] = serverInfo;
return result;
}
QJsonObject MCPServer::handleToolsList()
{
QJsonObject result;
result["tools"] = buildToolsList();
return result;
}
QJsonObject MCPServer::handleToolsCall(const QJsonObject ¶ms)
{
QString toolName = params["name"].toString();
QJsonObject args = params["arguments"].toObject();
return callTool(toolName, args);
}
bool MCPServer::ensureOgreInitialized()
{
if (m_ogreInitialized) return true;
if (m_ogreInitFailed) return false;
try {
if (!Manager::getSingletonPtr()) {
Manager::getSingleton();
}
m_ogreInitialized = true;
return true;
} catch (const Ogre::Exception &e) {
qWarning() << "MCP: Ogre init failed:" << e.getFullDescription().c_str();
}
m_ogreInitFailed = true;
return false;
}
QJsonObject MCPServer::makeErrorResult(const QString &message)
{
QJsonObject textContent;
textContent["type"] = "text";
textContent["text"] = message;
QJsonArray content;
content.append(textContent);
QJsonObject result;
result["isError"] = true;
result["content"] = content;
return result;
}
QJsonObject MCPServer::makeSuccessResult(const QString &message)
{
QJsonObject textContent;
textContent["type"] = "text";
textContent["text"] = message;
QJsonArray content;
content.append(textContent);
QJsonObject result;
result["content"] = content;
return result;
}
QJsonObject MCPServer::callTool(const QString &name, const QJsonObject &args)
{
qDebug() << "MCP Tool Call:" << name << args;
SentryReporter::addBreadcrumb("mcp.tool", QStringLiteral("Tool call: %1").arg(name));
// Start a performance transaction for heavy tools
static const QStringList heavyTools = {
"load_mesh", "export_mesh", "take_screenshot", "create_primitive", "create_material",
"merge_animations"
};
uintptr_t txn = 0;
if (heavyTools.contains(name)) {
txn = SentryReporter::startTransaction(QStringLiteral("mcp.%1").arg(name), "mcp.tool");
}
// Lazily initialize Ogre/Manager on first tool call
if (!ensureOgreInitialized()) {
if (txn) SentryReporter::finishTransaction(txn);
return makeErrorResult("Error: Ogre 3D engine could not be initialized (no OpenGL available)");
}
QJsonObject toolResult;
// Dispatch to appropriate tool handler
if (name == "create_material") {
toolResult = toolCreateMaterial(args);
} else if (name == "modify_material") {
toolResult = toolModifyMaterial(args);
} else if (name == "get_material") {
toolResult = toolGetMaterial(args);
} else if (name == "list_materials") {
toolResult = toolListMaterials(args);
} else if (name == "apply_material") {
toolResult = toolApplyMaterial(args);
} else if (name == "load_mesh") {
toolResult = toolLoadMesh(args);
} else if (name == "get_mesh_info") {
toolResult = toolGetMeshInfo(args);
} else if (name == "transform_mesh") {
toolResult = toolTransformMesh(args);
} else if (name == "list_textures") {
toolResult = toolListTextures(args);
} else if (name == "set_texture") {
toolResult = toolSetTexture(args);
} else if (name == "export_mesh") {
toolResult = toolExportMesh(args);
} else if (name == "get_scene_info") {
toolResult = toolGetSceneInfo(args);
} else if (name == "take_screenshot") {
toolResult = toolTakeScreenshot(args);
} else if (name == "create_primitive") {
toolResult = toolCreatePrimitive(args);
} else if (name == "animate") {
toolResult = toolAnimate(args);
} else if (name == "list_skeletal_animations") {
toolResult = toolListSkeletalAnimations(args);
} else if (name == "get_animation_info") {
toolResult = toolGetAnimationInfo(args);
} else if (name == "set_animation_length") {
toolResult = toolSetAnimationLength(args);
} else if (name == "set_animation_time") {
toolResult = toolSetAnimationTime(args);
} else if (name == "add_keyframe") {
toolResult = toolAddKeyframe(args);
} else if (name == "remove_keyframe") {
toolResult = toolRemoveKeyframe(args);
} else if (name == "play_animation") {
toolResult = toolPlayAnimation(args);
} else if (name == "toggle_skeleton_debug") {
toolResult = toolToggleSkeletonDebug(args);
} else if (name == "toggle_bone_weights") {
toolResult = toolToggleBoneWeights(args);
} else if (name == "toggle_normals") {
toolResult = toolToggleNormals(args);
} else if (name == "merge_animations") {
toolResult = toolMergeAnimations(args);
} else {
if (txn) SentryReporter::finishTransaction(txn);
return makeErrorResult(QString("Unknown tool: %1").arg(name));
}
// Track errors as breadcrumbs
if (toolResult.contains("isError") && toolResult["isError"].toBool()) {
SentryReporter::addBreadcrumb("mcp.tool",
QStringLiteral("Tool error: %1").arg(name), "error");
}
if (txn) SentryReporter::finishTransaction(txn);
return toolResult;
}
QJsonObject MCPServer::handleResourcesList()
{
QJsonArray resources;
// Add current material as a resource
QJsonObject materialResource;
materialResource["uri"] = "qtmesheditor://material/current";
materialResource["name"] = "Current Material";
materialResource["description"] = "The currently selected material in the editor";
materialResource["mimeType"] = "text/plain";
resources.append(materialResource);
// Add scene info as a resource
QJsonObject sceneResource;
sceneResource["uri"] = "qtmesheditor://scene/info";
sceneResource["name"] = "Scene Information";
sceneResource["description"] = "Information about the current scene";
sceneResource["mimeType"] = "application/json";
resources.append(sceneResource);
QJsonObject result;
result["resources"] = resources;
return result;
}
QJsonObject MCPServer::handleResourcesRead(const QJsonObject ¶ms)
{
QString uri = params["uri"].toString();
QJsonArray contents;
if (uri == "qtmesheditor://material/current") {
QJsonObject content;
content["uri"] = uri;
content["mimeType"] = "text/plain";
// Get material text from the MaterialEditorQML if available
QString materialText = "// No material currently loaded";
if (m_mainWindow) {
MaterialEditorQML* matEditor = m_mainWindow->findChild<MaterialEditorQML*>();
if (matEditor && !matEditor->materialName().isEmpty()) {
materialText = matEditor->materialText();
}
}
content["text"] = materialText;
contents.append(content);
} else if (uri == "qtmesheditor://scene/info") {
QJsonObject content;
content["uri"] = uri;
content["mimeType"] = "application/json";
// Reuse the scene info tool to get real data
QJsonObject sceneResult = toolGetSceneInfo(QJsonObject());
QJsonArray sceneContent = sceneResult["content"].toArray();
QString sceneText = "{}";
if (!sceneContent.isEmpty()) {
sceneText = sceneContent[0].toObject()["text"].toString();
}
content["text"] = sceneText;
contents.append(content);
}
QJsonObject result;
result["contents"] = contents;
return result;
}
// Tool implementations
QJsonObject MCPServer::toolCreateMaterial(const QJsonObject &args)
{
QString name = args["name"].toString();
if (name.isEmpty()) {
return makeErrorResult("Error: Material name is required");
}
try {
// Check if material already exists
Ogre::MaterialPtr existing = Ogre::MaterialManager::getSingleton().getByName(name.toStdString());
if (existing) {
return makeErrorResult(QString("Error: Material '%1' already exists").arg(name));
}
// Create the material programmatically
Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(
name.toStdString(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
// Set properties from colors
QJsonObject colors = args["colors"].toObject();
Ogre::Pass* pass = mat->getTechnique(0)->getPass(0);
if (colors.contains("ambient")) {
QJsonArray a = colors["ambient"].toArray();
pass->setAmbient(a[0].toDouble(0.2), a[1].toDouble(0.2), a[2].toDouble(0.2));
} else {
pass->setAmbient(0.2, 0.2, 0.2);
}
if (colors.contains("diffuse")) {
QJsonArray d = colors["diffuse"].toArray();
pass->setDiffuse(d[0].toDouble(1.0), d[1].toDouble(1.0), d[2].toDouble(1.0), 1.0);
}
if (colors.contains("specular")) {
QJsonArray s = colors["specular"].toArray();
double shininess = colors.value("shininess").toDouble(32.0);
pass->setSpecular(s[0].toDouble(0.5), s[1].toDouble(0.5), s[2].toDouble(0.5), 1.0);
pass->setShininess(shininess);
} else {
pass->setSpecular(0.5, 0.5, 0.5, 1.0);
pass->setShininess(32.0);
}
if (colors.contains("emissive")) {
QJsonArray e = colors["emissive"].toArray();
pass->setSelfIllumination(e[0].toDouble(), e[1].toDouble(), e[2].toDouble());
}
try { mat->load(); } catch (...) { /* headless — no GPU context */ }
// Serialize the created material for display
Ogre::MaterialSerializer serializer;
serializer.queueForExport(mat);
QString materialScript = QString::fromStdString(serializer.getQueuedAsString());
return makeSuccessResult(QString("Created material '%1':\n%2").arg(name).arg(materialScript));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error creating material: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolModifyMaterial(const QJsonObject &args)
{
QString name = args["name"].toString();
if (name.isEmpty()) {
return makeErrorResult("Error: Material name is required");
}
// Try to get the material from Ogre
try {
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(name.toStdString());
if (!material) {
return makeErrorResult(QString("Error: Material '%1' not found").arg(name));
}
// Get the first technique and pass
if (material->getNumTechniques() == 0) {
return makeErrorResult(QString("Error: Material '%1' has no techniques").arg(name));
}
Ogre::Technique* technique = material->getTechnique(0);
if (technique->getNumPasses() == 0) {
return makeErrorResult(QString("Error: Material '%1' technique has no passes").arg(name));
}
Ogre::Pass* pass = technique->getPass(0);
QStringList modifications;
// Apply modifications
if (args.contains("ambient")) {
QJsonArray a = args["ambient"].toArray();
Ogre::ColourValue ambient(a[0].toDouble(), a[1].toDouble(), a[2].toDouble());
pass->setAmbient(ambient);
modifications << QString("ambient: %1 %2 %3")
.arg(a[0].toDouble()).arg(a[1].toDouble()).arg(a[2].toDouble());
}
if (args.contains("diffuse")) {
QJsonArray d = args["diffuse"].toArray();
Ogre::ColourValue diffuse(d[0].toDouble(), d[1].toDouble(), d[2].toDouble());
pass->setDiffuse(diffuse);
modifications << QString("diffuse: %1 %2 %3")
.arg(d[0].toDouble()).arg(d[1].toDouble()).arg(d[2].toDouble());
}
if (args.contains("specular")) {
QJsonArray s = args["specular"].toArray();
double shininess = args.value("shininess").toDouble(pass->getShininess());
Ogre::ColourValue specular(s[0].toDouble(), s[1].toDouble(), s[2].toDouble());
pass->setSpecular(specular);
pass->setShininess(shininess);
modifications << QString("specular: %1 %2 %3 (shininess: %4)")
.arg(s[0].toDouble()).arg(s[1].toDouble()).arg(s[2].toDouble()).arg(shininess);
}
if (args.contains("emissive")) {
QJsonArray e = args["emissive"].toArray();
Ogre::ColourValue emissive(e[0].toDouble(), e[1].toDouble(), e[2].toDouble());
pass->setSelfIllumination(emissive);
modifications << QString("emissive: %1 %2 %3")
.arg(e[0].toDouble()).arg(e[1].toDouble()).arg(e[2].toDouble());
}
return makeSuccessResult(QString("Modified material '%1':\n%2").arg(name).arg(modifications.join("\n")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolGetMaterial(const QJsonObject &args)
{
QString name = args["name"].toString();
if (name.isEmpty()) {
return makeErrorResult("Error: Material name is required");
}
try {
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(name.toStdString());
if (!material) {
return makeErrorResult(QString("Error: Material '%1' not found").arg(name));
}
// Serialize the material to script text
Ogre::MaterialSerializer serializer;
serializer.queueForExport(material);
QString script = QString::fromStdString(serializer.getQueuedAsString());
return makeSuccessResult(QString("Material '%1' script:\n%2").arg(name).arg(script));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolListMaterials(const QJsonObject &args)
{
Q_UNUSED(args);
try {
QStringList materials;
auto& matMgr = Ogre::MaterialManager::getSingleton();
auto it = matMgr.getResourceIterator();
while (it.hasMoreElements()) {
Ogre::ResourcePtr res = it.getNext();
materials << QString::fromStdString(res->getName());
}
materials.sort();
return makeSuccessResult(QString("Available materials (%1):\n%2").arg(materials.size()).arg(materials.join("\n")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolApplyMaterial(const QJsonObject &args)
{
QString materialName = args["material"].toString();
QString meshName = args["mesh"].toString();
if (materialName.isEmpty()) {
return makeErrorResult("Error: Material name is required");
}
try {
// Verify material exists
Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().getByName(materialName.toStdString());
if (!mat) {
return makeErrorResult(QString("Error: Material '%1' not found").arg(materialName));
}
Manager* mgr = Manager::getSingletonPtr();
if (!mgr) {
return makeErrorResult("Error: Manager not available");
}
QStringList appliedTo;
if (!meshName.isEmpty()) {
// Apply to specific entity by name
QList<Ogre::Entity*>& entities = mgr->getEntities();
bool found = false;
for (Ogre::Entity* entity : entities) {
if (entity && QString::fromStdString(entity->getName()) == meshName) {
entity->setMaterialName(materialName.toStdString());
appliedTo << QString::fromStdString(entity->getName());
found = true;
break;
}
}
if (!found) {
return makeErrorResult(QString("Error: Entity '%1' not found").arg(meshName));
}
} else {
// Apply to selected entities
SelectionSet* sel = SelectionSet::getSingleton();
if (!sel || sel->getEntitiesCount() == 0) {
return makeErrorResult("Error: No entity specified and no entities selected");
}
for (int i = 0; i < sel->getEntitiesCount(); ++i) {
Ogre::Entity* entity = sel->getEntity(i);
if (entity) {
entity->setMaterialName(materialName.toStdString());
appliedTo << QString::fromStdString(entity->getName());
}
}
}
return makeSuccessResult(QString("Applied material '%1' to: %2").arg(materialName).arg(appliedTo.join(", ")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolLoadMesh(const QJsonObject &args)
{
QString path = args["path"].toString();
if (path.isEmpty()) {
return makeErrorResult("Error: File path is required");
}
if (!m_mainWindow) {
return makeErrorResult("Error: MainWindow not available. Run with --with-mcp flag for full functionality.");
}
if (!QFile::exists(path)) {
return makeErrorResult(QString("Error: File not found: %1").arg(path));
}
try {
m_mainWindow->importMeshs(QStringList{path});
return makeSuccessResult(QString("Loaded mesh from: %1").arg(path));
} catch (std::exception& e) {
return makeErrorResult(QString("Error loading mesh: %1").arg(e.what()));
}
}
QJsonObject MCPServer::toolGetMeshInfo(const QJsonObject &args)
{
Q_UNUSED(args);
try {
Manager* mgr = Manager::getSingletonPtr();
if (!mgr) {
return makeErrorResult("Error: Manager not available");
}
// Check if there's a selection first, otherwise report all entities
SelectionSet* sel = SelectionSet::getSingleton();
QList<Ogre::Entity*> entitiesToReport;
if (sel && sel->getEntitiesCount() > 0) {
for (int i = 0; i < sel->getEntitiesCount(); ++i) {
entitiesToReport.append(sel->getEntity(i));
}
} else {
entitiesToReport = mgr->getEntities();
}
if (entitiesToReport.isEmpty()) {
return makeSuccessResult("No entities in scene");
}
QStringList infoLines;
for (Ogre::Entity* entity : entitiesToReport) {
if (!entity) continue;
const Ogre::MeshPtr& mesh = entity->getMesh();
if (!mesh) continue;
// Count vertices and indices
unsigned int totalVertices = 0;
unsigned int totalIndices = 0;
unsigned int numSubMeshes = mesh->getNumSubMeshes();
for (unsigned int i = 0; i < numSubMeshes; ++i) {
Ogre::SubMesh* subMesh = mesh->getSubMesh(i);
if (subMesh->vertexData)
totalVertices += subMesh->vertexData->vertexCount;
if (subMesh->indexData)
totalIndices += subMesh->indexData->indexCount;
}
// Shared vertex data
if (mesh->sharedVertexData)
totalVertices += mesh->sharedVertexData->vertexCount;
// Get materials for sub-entities
QStringList materials;
for (unsigned int i = 0; i < entity->getNumSubEntities(); ++i) {
Ogre::SubEntity* subEnt = entity->getSubEntity(i);
if (subEnt && subEnt->getMaterial()) {
materials << QString::fromStdString(subEnt->getMaterial()->getName());
}
}
Ogre::SceneNode* parentNode = entity->getParentSceneNode();
Ogre::Vector3 pos = parentNode ? parentNode->getPosition() : Ogre::Vector3::ZERO;
Ogre::Vector3 scale = parentNode ? parentNode->getScale() : Ogre::Vector3::UNIT_SCALE;
infoLines << QString(
"Entity: %1\n"
" Mesh: %2\n"
" Vertices: %3\n"
" Triangles: %4\n"
" SubMeshes: %5\n"
" Materials: %6\n"
" Position: %7, %8, %9\n"
" Scale: %10, %11, %12"
).arg(QString::fromStdString(entity->getName()))
.arg(QString::fromStdString(mesh->getName()))
.arg(totalVertices)
.arg(totalIndices / 3)
.arg(numSubMeshes)
.arg(materials.join(", "))
.arg(pos.x).arg(pos.y).arg(pos.z)
.arg(scale.x).arg(scale.y).arg(scale.z);
}
return makeSuccessResult(QString("Mesh Information (%1 entities):\n\n%2")
.arg(entitiesToReport.size())
.arg(infoLines.join("\n\n")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
// Helper: parse a vector from JSON (supports both array [x,y,z] and object {x,y,z})
static Ogre::Vector3 parseVector3(const QJsonValue &val) {
if (val.isArray()) {
QJsonArray a = val.toArray();
return Ogre::Vector3(a[0].toDouble(), a[1].toDouble(), a[2].toDouble());
}
if (val.isObject()) {
QJsonObject o = val.toObject();
return Ogre::Vector3(o["x"].toDouble(), o["y"].toDouble(), o["z"].toDouble());
}
return Ogre::Vector3::ZERO;
}
QJsonObject MCPServer::toolTransformMesh(const QJsonObject &args)
{
try {
Manager* mgr = Manager::getSingletonPtr();
if (!mgr) {
return makeErrorResult("Error: Manager not available");
}
// If a name is provided, find and select that node first
QString name = args["name"].toString();
Ogre::SceneNode* targetNode = nullptr;
if (!name.isEmpty()) {
QList<Ogre::SceneNode*> nodes = mgr->getSceneNodes();
for (Ogre::SceneNode* node : nodes) {
if (node && QString::fromStdString(node->getName()) == name) {
targetNode = node;
break;
}
}
if (!targetNode) {
return makeErrorResult(QString("Error: Node '%1' not found").arg(name));
}
} else {
// No name given - require something selected
SelectionSet* sel = SelectionSet::getSingleton();
if (!sel || sel->getNodesCount() == 0) {
return makeErrorResult("Error: No name provided and no scene nodes selected.");
}
targetNode = sel->getNodesSelectionList().first();
}
QStringList transforms;
if (args.contains("position")) {
Ogre::Vector3 pos = parseVector3(args["position"]);
targetNode->setPosition(pos);
transforms << QString("position: %1, %2, %3").arg(pos.x).arg(pos.y).arg(pos.z);
}
if (args.contains("rotation")) {
Ogre::Vector3 rot = parseVector3(args["rotation"]);
Ogre::Quaternion q;
q.FromAngleAxis(Ogre::Degree(rot.x), Ogre::Vector3::UNIT_X);
Ogre::Quaternion qy; qy.FromAngleAxis(Ogre::Degree(rot.y), Ogre::Vector3::UNIT_Y);
Ogre::Quaternion qz; qz.FromAngleAxis(Ogre::Degree(rot.z), Ogre::Vector3::UNIT_Z);
targetNode->setOrientation(qz * qy * q);
transforms << QString("rotation: %1, %2, %3").arg(rot.x).arg(rot.y).arg(rot.z);
}
if (args.contains("scale")) {
Ogre::Vector3 scale = parseVector3(args["scale"]);
targetNode->setScale(scale);
transforms << QString("scale: %1, %2, %3").arg(scale.x).arg(scale.y).arg(scale.z);
}
return makeSuccessResult(QString("Applied transforms to '%1':\n%2")
.arg(QString::fromStdString(targetNode->getName()))
.arg(transforms.join("\n")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolListTextures(const QJsonObject &args)
{
Q_UNUSED(args);
try {
QStringList textures;
auto& texMgr = Ogre::TextureManager::getSingleton();
auto it = texMgr.getResourceIterator();
while (it.hasMoreElements()) {
Ogre::ResourcePtr res = it.getNext();
textures << QString::fromStdString(res->getName());
}
textures.sort();
return makeSuccessResult(QString("Available textures (%1):\n%2")
.arg(textures.size())
.arg(textures.isEmpty() ? "(none)" : textures.join("\n")));
} catch (Ogre::Exception& e) {
return makeErrorResult(QString("Ogre error: %1").arg(QString::fromStdString(e.getFullDescription())));
}
}
QJsonObject MCPServer::toolSetTexture(const QJsonObject &args)
{
QString materialName = args["material"].toString();
QString texturePath = args["texture"].toString();
int textureUnit = args["unit"].toInt(0);
if (materialName.isEmpty() || texturePath.isEmpty()) {
return makeErrorResult("Error: Both material and texture names are required");
}
try {
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(materialName.toStdString());
if (!material) {
return makeErrorResult(QString("Error: Material '%1' not found").arg(materialName));
}
if (material->getNumTechniques() == 0 ||