Repository navigation
Expand file tree
/
Copy pathmain_cli.cpp
More file actions
1331 lines (1259 loc) · 57.9 KB
/
Copy pathmain_cli.cpp
File metadata and controls
1331 lines (1259 loc) · 57.9 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 "core/StructuralModel.hpp"
#include "io/AppLogger.hpp"
#include "io/DxfInterop.hpp"
#include "io/IfcInterop.hpp"
#include "io/PdfReportGenerator.hpp"
#include "io/ProjectSerializer.hpp"
#include "io/Utf8Path.hpp"
#include "os/WindowsCliIntegration.hpp"
#include "kernel/analysis/BucklingSolver.hpp"
#include "kernel/analysis/DynamicSolver.hpp"
#include "kernel/analysis/NonlinearSolver.hpp"
#include "solver/FemSolver3D.hpp"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGuiApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QString>
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cmath>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif
#ifndef OMNIFRAME_APP_VERSION
#define OMNIFRAME_APP_VERSION "2026.11.15.0"
#endif
namespace {
using namespace omniframe;
std::string toLowerAscii(std::string s) {
for (char& ch : s) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
return s;
}
bool endsWithCi(const std::string& str, const std::string& suffix) {
if (str.size() < suffix.size()) return false;
return toLowerAscii(str.substr(str.size() - suffix.size())) == toLowerAscii(suffix);
}
bool createBuiltInExample(const std::string& rawName, StructuralModel& outModel, std::string& canonicalName) {
const std::string key = toLowerAscii(rawName);
if (key == "1" || key == "building" || key == "portico" || key == "edificio" || key == "frame") {
outModel = StructuralModel::createBuildingFrameExample();
canonicalName = "building";
return true;
}
if (key == "2" || key == "cantilever" || key == "balanco" || key == "lframe") {
outModel = StructuralModel::createCantileverLFrameExample();
canonicalName = "cantilever";
return true;
}
if (key == "3" || key == "truss" || key == "trelica" || key == "passarela") {
outModel = StructuralModel::createSpaceTrussExample();
canonicalName = "truss";
return true;
}
return false;
}
void printUsage() {
std::cout << "OmniFrame 3D CLI v" << OMNIFRAME_APP_VERSION << " (Kernel C++23 / Eigen 3.4.0 / Schema 2.1.0)\n"
<< "Uso no Windows 10/11 (CMD e PowerShell):\n"
<< " omniframe-cli --version | -v\n"
<< " omniframe-cli --help | -h\n"
<< " omniframe-cli --list-examples [--json] [--output <caminho.json>]\n"
<< " omniframe-cli --validate <arquivo.omniframe|dxf|ifc> [--output <caminho.json>] [--json]\n"
<< " omniframe-cli --validate --example <building|cantilever|truss|1|2|3> [--output <caminho.json>]\n"
<< " omniframe-cli --analyze <arquivo.omniframe|dxf|ifc> [opções]\n"
<< " omniframe-cli --example <building|cantilever|truss|1|2|3> [opções]\n"
<< " omniframe-cli --nbr-audit [<arquivo.omniframe|dxf|ifc>] [opções]\n"
<< " omniframe-cli --check-windows-integration [--json]\n"
<< " omniframe-cli --install-windows-integration [--json]\n"
<< " omniframe-cli --uninstall-windows-integration [--json]\n\n"
<< "Opções de modelo e entrada:\n"
<< " --validate [<arquivo>] Valida topologia, conectividade, finitude e malhas 2D/3D (0=válido, 2=inválido)\n"
<< " --analyze [<arquivo>] Executa análise estrutural sobre arquivo de entrada ou --example\n"
<< " --example <nome|1|2|3> Usa modelo embutido (1=building, 2=cantilever, 3=truss)\n"
<< " --list-examples Lista os 3 exemplos oficiais embutidos do OmniFrame 3D\n"
<< " --nbr-audit | --audit-nbr Executa auditoria ABNT NBR (6118/8800/6120/6122/6123/7480)\n\n"
<< "Opções de análise, solver e não linearidade:\n"
<< " --analysis <tipo> static | modal | buckling | nonlinear | pdelta | harmonic |\n"
<< " spectrum | transient | seismic (padrão=static)\n"
<< " --solver <tipo> auto | ldlt | llt | sparselu | cg | bicgstab (padrão=auto)\n"
<< " --modes <N> Número de modos (modal/buckling/spectrum, padrão=6)\n"
<< " --steps <N> Passos incrementais ou temporais (padrão=20)\n"
<< " --dt <seg> Passo de tempo para transient/seismic em segundos (padrão=0.02)\n"
<< " --scheme <newmark|hht> Integrador transiente/sísmico (Newmark-beta ou HHT-alpha, padrão=newmark)\n"
<< " --case <id> ID do Caso de Carga (static/transient)\n"
<< " --combo <id> ID da Combinação NBR (static)\n"
<< " --method <nr|arclength> Método não linear: Newton-Raphson ou Arc-Length Crisfield (padrão=nr)\n"
<< " --load-factor <fator> Fator de carga alvo para nonlinear/pdelta (padrão=1.0)\n"
<< " --full-tangent Atualiza matriz tangente Kt a cada iteração (Full NR, padrão)\n"
<< " --modified-newton Mantém Kt constante por incremento (Modified Newton)\n"
<< " --line-search Habilita line search com retrocesso em NR (padrão)\n"
<< " --no-line-search Desabilita line search em NR\n"
<< " --imperfection <amp_m> Perturba geometria pelo modo de flambagem antes de resolver/exportar\n"
<< " --imperfection-mode <N> Modo de flambagem base 1 usado em --imperfection (padrão=1)\n\n"
<< "Opções de exportação, memorial e integração Windows:\n"
<< " --export <fmt> <caminho> Exporta modelo/resultados: json | csv | vtk | dxf | ifc\n"
<< " --report <fmt> <caminho> Gera memorial técnico: md | html | pdf\n"
<< " --output <caminho.json> Grava resumo JSON estruturado no disco\n"
<< " --json Emite resumo JSON no stdout\n"
<< " --check-windows-integration Consulta PATH, App Paths e associação .omniframe no Windows 10/11\n"
<< " --install-windows-integration Registra omniframe-cli e .omniframe no HKCU do Windows (sem admin)\n"
<< " --uninstall-windows-integration Remove o registro HKCU da CLI e associação .omniframe\n";
}
bool loadModelAnyFormat(const std::string& path, StructuralModel& model, std::string& errOut) {
if (endsWithCi(path, ".dxf")) {
io::DxfInteropReport rep;
if (!io::DxfInterop::importFromFile(path, model, nullptr, io::DxfImportOptions{}, &rep)) {
errOut = rep.errorMessage;
return false;
}
return true;
}
if (endsWithCi(path, ".ifc")) {
io::IfcInteropReport rep;
if (!io::IfcInterop::importFromFile(path, model, nullptr, nullptr, &rep)) {
errOut = rep.errorMessage;
return false;
}
return true;
}
if (!ProjectSerializer::loadFromFile(QString::fromUtf8(path), model)) {
errOut = "Falha ao carregar projeto .omniframe: " + path;
return false;
}
return true;
}
QJsonObject windowsStatusToJson(const os::CliIntegrationStatus& st) {
QJsonObject j;
j["isWindows"] = st.isWindows;
j["cliBinaryExists"] = st.cliBinaryExists;
j["guiBinaryExists"] = st.guiBinaryExists;
j["installDirInUserPath"] = st.installDirInUserPath;
j["installDirInSystemPath"] = st.installDirInSystemPath;
j["installDirInProcessPath"] = st.installDirInProcessPath;
j["appPathsCliRegistered"] = st.appPathsCliRegistered;
j["appPathsGuiRegistered"] = st.appPathsGuiRegistered;
j["fileAssocRegistered"] = st.fileAssocRegistered;
j["readyForCmdAndPowerShell"] = st.isReadyForCmdAndPowerShell();
j["installDirectory"] = st.installDirectory;
j["cliBinaryPath"] = st.cliBinaryPath;
j["guiBinaryPath"] = st.guiBinaryPath;
return j;
}
QJsonObject nbrAuditToJson(const io::ModelNbrAudit& audit) {
QJsonObject j;
j["passedAll"] = audit.passedAll;
j["maxDcr"] = audit.maxDcr;
j["governingSummary"] = audit.governingSummary;
j["steelMembersCount"] = static_cast<int>(audit.steelMembers.size());
j["concreteBeamsCount"] = static_cast<int>(audit.concreteBeams.size());
j["concreteColumnsCount"] = static_cast<int>(audit.concreteColumns.size());
j["foundationsCount"] = static_cast<int>(audit.foundations.size());
QJsonObject els;
els["passed"] = audit.elsDisplacement.passed;
els["dcrMax"] = audit.elsDisplacement.dcrMax;
els["governingCriterion"] = QString::fromStdString(audit.elsDisplacement.governingCriterion);
j["elsDisplacement"] = els;
QJsonObject wind;
wind["vk_ms"] = audit.sampleWind6123.vk_ms;
wind["q_kPa"] = audit.sampleWind6123.q_kPa;
j["wind6123"] = wind;
QJsonArray covArr;
for (const auto& c : audit.coverageMatrix) {
QJsonObject cj;
cj["code"] = QString::fromStdString(c.codeId);
cj["title"] = QString::fromStdString(c.title);
const char* statusStr = "outOfLocalPdfScope";
if (c.status == kernel::codes::ComplianceScopeStatus::LocalPdfVerified) {
statusStr = "localPdfVerified";
} else if (c.status == kernel::codes::ComplianceScopeStatus::PartialReferenceOnly) {
statusStr = "partialReferenceOnly";
}
cj["status"] = statusStr;
cj["localPdfFile"] = QString::fromStdString(c.localPdfFile);
cj["scopeNote"] = QString::fromStdString(c.scopeNote);
covArr.append(cj);
}
j["coverageMatrix"] = covArr;
return j;
}
const char* meshCellTypeName(kernel::MeshCellType t) {
switch (t) {
case kernel::MeshCellType::Line2: return "Line2";
case kernel::MeshCellType::Tri3: return "Tri3";
case kernel::MeshCellType::Quad4: return "Quad4";
case kernel::MeshCellType::Quad8: return "Quad8";
case kernel::MeshCellType::Tet4: return "Tet4";
case kernel::MeshCellType::Tet10: return "Tet10";
case kernel::MeshCellType::Hex8: return "Hex8";
case kernel::MeshCellType::Hex20: return "Hex20";
}
return "Unknown";
}
int vtkCellTypeCode(kernel::MeshCellType t) {
switch (t) {
case kernel::MeshCellType::Line2: return 3; // VTK_LINE
case kernel::MeshCellType::Tri3: return 5; // VTK_TRIANGLE
case kernel::MeshCellType::Quad4: return 9; // VTK_QUAD
case kernel::MeshCellType::Quad8: return 23; // VTK_QUADRATIC_QUAD
case kernel::MeshCellType::Tet4: return 10; // VTK_TETRA
case kernel::MeshCellType::Tet10: return 24; // VTK_QUADRATIC_TETRA
case kernel::MeshCellType::Hex8: return 12; // VTK_HEXAHEDRON
case kernel::MeshCellType::Hex20: return 25; // VTK_QUADRATIC_HEXAHEDRON
}
return 1; // VTK_VERTEX
}
const char* issueSeverityName(IssueSeverity s) {
switch (s) {
case IssueSeverity::Error: return "error";
case IssueSeverity::Warning: return "warning";
case IssueSeverity::Info: return "info";
}
return "info";
}
bool exportCsvFile(const std::string& path, const StructuralModel& model) {
std::ofstream os(io::pathFromUtf8(path), std::ios::binary);
if (!os.is_open()) return false;
os << "# OmniFrame 3D Nodal Displacements & Reactions (SI: m, rad, kN, kN*m)\n";
os << "NodeID,X,Y,Z,UX,UY,UZ,RX,RY,RZ,FX_Reac,FY_Reac,FZ_Reac,MX_Reac,MY_Reac,MZ_Reac\n";
for (const auto& n : model.getNodes()) {
os << n.id << "," << std::setprecision(9)
<< n.position.x << "," << n.position.y << "," << n.position.z;
for (int d = 0; d < 6; ++d) os << "," << n.displacement[d];
for (int d = 0; d < 6; ++d) os << "," << n.reaction[d];
os << "\n";
}
os << "\n# Element Local End Forces\n";
os << "ElementID,NodeStart,NodeEnd,HasResults,N_i,Vy_i,Vz_i,Tx_i,My_i,Mz_i,N_j,Vy_j,Vz_j,Tx_j,My_j,Mz_j\n";
for (const auto& e : model.getElements()) {
os << e.id << "," << e.nodeStart << "," << e.nodeEnd << "," << (e.hasResults ? 1 : 0);
for (int d = 0; d < 12; ++d) os << "," << (e.hasResults ? e.localEndForces(d) : 0.0);
os << "\n";
}
if (!model.surfaceMesh().nodes.empty()) {
os << "\n# Continuum Surface/Solid Mesh Nodes\n";
os << "MeshNodeID,X,Y,Z,UX,UY,UZ,RX,RY,RZ,FX_Reac,FY_Reac,FZ_Reac,MX_Reac,MY_Reac,MZ_Reac\n";
for (const auto& mn : model.surfaceMesh().nodes) {
os << mn.id << "," << std::setprecision(9)
<< mn.position.x() << "," << mn.position.y() << "," << mn.position.z();
for (int d = 0; d < 6; ++d) os << "," << mn.displacement[d];
for (int d = 0; d < 6; ++d) os << "," << mn.reaction[d];
os << "\n";
}
}
if (!model.surfaceMesh().elements.empty()) {
os << "\n# Continuum 2D/3D Element Stresses & Resultants\n";
os << "ElementID,CellType,HasResults,VonMises_kPa,Sigma1_kPa,Sigma3_kPa,"
"Nxx,Nyy,Nxy,Mxx,Myy,Mxy,Sxx,Syy,Szz,Txy,Tyz,Tzx\n";
for (const auto& me : model.surfaceMesh().elements) {
os << me.id << "," << meshCellTypeName(me.type) << "," << (me.hasResults ? 1 : 0) << ","
<< std::setprecision(9)
<< me.vonMisesStress << "," << me.maxPrincipalStress << "," << me.minPrincipalStress << ","
<< me.membraneResultants[0] << "," << me.membraneResultants[1] << "," << me.membraneResultants[2] << ","
<< me.bendingResultants[0] << "," << me.bendingResultants[1] << "," << me.bendingResultants[2] << ","
<< me.stressVoigt[0] << "," << me.stressVoigt[1] << "," << me.stressVoigt[2] << ","
<< me.stressVoigt[3] << "," << me.stressVoigt[4] << "," << me.stressVoigt[5] << "\n";
}
}
return os.good();
}
bool exportVtkFile(const std::string& path, const StructuralModel& model) {
std::ofstream os(io::pathFromUtf8(path), std::ios::binary);
if (!os.is_open()) return false;
struct VtkPoint {
double x = 0.0, y = 0.0, z = 0.0;
std::array<double, 3> disp{0.0, 0.0, 0.0};
std::array<double, 3> reac{0.0, 0.0, 0.0};
bool hasResults = false;
};
struct VtkCell {
int vtkType = 3;
std::vector<int> ptIds;
double vonMises = 0.0;
double sigma1 = 0.0;
double sigma3 = 0.0;
};
std::vector<VtkPoint> points;
const auto& frameNodes = model.getNodes();
const auto& frameElems = model.getElements();
const auto& mesh = model.surfaceMesh();
points.reserve(frameNodes.size() + mesh.nodes.size());
std::unordered_map<NodeId, int> frameIdxMap;
frameIdxMap.reserve(frameNodes.size());
SpatialPointHash frameHash(1e-4);
frameHash.reserve(frameNodes.size());
for (int i = 0; i < static_cast<int>(frameNodes.size()); ++i) {
const auto& n = frameNodes[i];
frameIdxMap[n.id] = static_cast<int>(points.size());
frameHash.insert(n.position.x, n.position.y, n.position.z, static_cast<std::size_t>(i));
const bool nodeHasData = (n.displacement[0] != 0.0 || n.displacement[1] != 0.0 || n.displacement[2] != 0.0 ||
n.reaction[0] != 0.0 || n.reaction[1] != 0.0 || n.reaction[2] != 0.0);
points.push_back({
n.position.x, n.position.y, n.position.z,
{n.displacement[0], n.displacement[1], n.displacement[2]},
{n.reaction[0], n.reaction[1], n.reaction[2]},
nodeHasData
});
}
std::unordered_map<NodeId, int> meshIdxMap;
meshIdxMap.reserve(mesh.nodes.size());
for (const auto& mn : mesh.nodes) {
int matched = -1;
std::size_t matchedIdx = 0;
if (frameHash.findNearestWithinSq(mn.position.x(), mn.position.y(), mn.position.z(), 1e-12, &matchedIdx)) {
matched = static_cast<int>(matchedIdx);
}
if (matched >= 0) {
meshIdxMap[mn.id] = matched;
if (mn.hasResults && !points[matched].hasResults) {
points[matched].disp = {mn.displacement[0], mn.displacement[1], mn.displacement[2]};
points[matched].reac = {mn.reaction[0], mn.reaction[1], mn.reaction[2]};
points[matched].hasResults = true;
}
} else {
const int newIdx = static_cast<int>(points.size());
meshIdxMap[mn.id] = newIdx;
points.push_back({
mn.position.x(), mn.position.y(), mn.position.z(),
{mn.displacement[0], mn.displacement[1], mn.displacement[2]},
{mn.reaction[0], mn.reaction[1], mn.reaction[2]},
mn.hasResults
});
}
}
std::vector<VtkCell> cells;
cells.reserve(frameElems.size() + mesh.elements.size());
int totalCellListInts = 0;
for (const auto& e : frameElems) {
const auto itA = frameIdxMap.find(e.nodeStart);
const auto itB = frameIdxMap.find(e.nodeEnd);
if (itA == frameIdxMap.end() || itB == frameIdxMap.end()) continue;
cells.push_back({3, {itA->second, itB->second}, 0.0, 0.0, 0.0});
totalCellListInts += 3;
}
for (const auto& me : mesh.elements) {
std::vector<int> pts;
pts.reserve(me.nodeIds.size());
bool valid = !me.nodeIds.empty();
for (NodeId nid : me.nodeIds) {
const auto it = meshIdxMap.find(nid);
if (it == meshIdxMap.end()) {
valid = false;
break;
}
pts.push_back(it->second);
}
if (!valid) continue;
totalCellListInts += 1 + static_cast<int>(pts.size());
cells.push_back({
vtkCellTypeCode(me.type),
std::move(pts),
me.vonMisesStress,
me.maxPrincipalStress,
me.minPrincipalStress
});
}
os << "# vtk DataFile Version 3.0\n"
<< "OmniFrame 3D Unified 1D/2D/3D Structural Analysis Export\n"
<< "ASCII\n"
<< "DATASET UNSTRUCTURED_GRID\n";
os << "POINTS " << points.size() << " double\n";
for (const auto& pt : points) {
os << std::setprecision(10) << pt.x << " " << pt.y << " " << pt.z << "\n";
}
os << "CELLS " << cells.size() << " " << totalCellListInts << "\n";
for (const auto& c : cells) {
os << c.ptIds.size();
for (int pid : c.ptIds) os << " " << pid;
os << "\n";
}
os << "CELL_TYPES " << cells.size() << "\n";
for (const auto& c : cells) {
os << c.vtkType << "\n";
}
os << "POINT_DATA " << points.size() << "\n";
os << "VECTORS Displacement double\n";
for (const auto& pt : points) {
os << std::setprecision(10) << pt.disp[0] << " " << pt.disp[1] << " " << pt.disp[2] << "\n";
}
os << "SCALARS DisplacementMagnitude double 1\n"
<< "LOOKUP_TABLE default\n";
for (const auto& pt : points) {
const double mag = std::sqrt(pt.disp[0] * pt.disp[0] + pt.disp[1] * pt.disp[1] + pt.disp[2] * pt.disp[2]);
os << std::setprecision(10) << mag << "\n";
}
os << "VECTORS ReactionForce double\n";
for (const auto& pt : points) {
os << std::setprecision(10) << pt.reac[0] << " " << pt.reac[1] << " " << pt.reac[2] << "\n";
}
if (!cells.empty()) {
os << "CELL_DATA " << cells.size() << "\n";
os << "SCALARS von_mises_kPa double 1\nLOOKUP_TABLE default\n";
for (const auto& c : cells) os << std::setprecision(10) << c.vonMises << "\n";
os << "SCALARS sigma1_kPa double 1\nLOOKUP_TABLE default\n";
for (const auto& c : cells) os << std::setprecision(10) << c.sigma1 << "\n";
os << "SCALARS sigma3_kPa double 1\nLOOKUP_TABLE default\n";
for (const auto& c : cells) os << std::setprecision(10) << c.sigma3 << "\n";
}
return os.good();
}
bool parseStrictInt(const std::string& raw, int& outVal) {
if (raw.empty()) return false;
const char* begin = raw.data();
const char* end = begin + raw.size();
int val = 0;
const auto [ptr, ec] = std::from_chars(begin, end, val, 10);
if (ec != std::errc{} || ptr != end) return false;
outVal = val;
return true;
}
bool parseStrictDouble(const std::string& raw, double& outVal) {
if (raw.empty()) return false;
const char* begin = raw.data();
const char* end = begin + raw.size();
double val = 0.0;
const auto [ptr, ec] = std::from_chars(begin, end, val);
if (ec != std::errc{} || ptr != end || !std::isfinite(val)) return false;
outVal = val;
return true;
}
QString formatJsonErrorBytes(const QString& errMsg) {
QJsonObject errObj;
errObj[QStringLiteral("success")] = false;
errObj[QStringLiteral("error")] = errMsg;
return QString::fromUtf8(QJsonDocument(errObj).toJson(QJsonDocument::Compact));
}
} // namespace
static int runCliImpl(int argc, char* argv[], bool& jsonStdout) {
const std::vector<std::string> args = os::commandLineArgumentsUtf8(argc, argv);
std::string outputJsonPath;
for (size_t i = 1; i < args.size(); ++i) {
if (args[i] == "--json") {
jsonStdout = true;
} else if (args[i] == "--output" && i + 1 < args.size()) {
outputJsonPath = args[++i];
}
}
auto writeJsonFile = [&](const QJsonObject& obj) {
if (!outputJsonPath.empty()) {
QFile f(QString::fromUtf8(outputJsonPath));
if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
f.write(QJsonDocument(obj).toJson(QJsonDocument::Indented));
}
}
};
auto emitCliError = [&](const QString& errMsg) {
QJsonObject errObj;
errObj[QStringLiteral("success")] = false;
errObj[QStringLiteral("error")] = errMsg;
writeJsonFile(errObj);
if (jsonStdout) {
std::cout << QJsonDocument(errObj).toJson(QJsonDocument::Compact).toStdString() << "\n";
} else {
std::cerr << errMsg.toStdString() << "\n";
}
};
bool needsPdfGui = false;
for (size_t i = 1; i + 1 < args.size(); ++i) {
if (args[i] == "--report" && toLowerAscii(args[i + 1]) == "pdf") {
needsPdfGui = true;
break;
}
}
if (needsPdfGui && qEnvironmentVariableIsEmpty("QT_QPA_PLATFORM")) {
qputenv("QT_QPA_PLATFORM", "offscreen");
}
#ifdef Q_OS_WIN
if (needsPdfGui && qEnvironmentVariableIsEmpty("QT_QPA_FONTDIR")) {
const QByteArray winDir = qgetenv("WINDIR");
const QString baseWin = winDir.isEmpty()
? QStringLiteral("C:/Windows")
: QDir::fromNativeSeparators(QString::fromLocal8Bit(winDir));
const QString sysFontsDir = QDir(baseWin).filePath(QStringLiteral("Fonts"));
if (QDir(sysFontsDir).exists()) {
qputenv("QT_QPA_FONTDIR", QDir::toNativeSeparators(sysFontsDir).toLocal8Bit());
}
}
#endif
std::unique_ptr<QCoreApplication> app = needsPdfGui
? std::make_unique<QGuiApplication>(argc, argv)
: std::make_unique<QCoreApplication>(argc, argv);
QCoreApplication::setApplicationName(QStringLiteral("OmniFrame"));
QCoreApplication::setOrganizationName(QStringLiteral("OmniFrame"));
QCoreApplication::setApplicationVersion(QStringLiteral(OMNIFRAME_APP_VERSION));
omniframe::io::AppLogger::initialize(true, false);
omniframe::io::AppLogger::installTerminateHandler();
struct CliLoggerScope {
~CliLoggerScope() {
omniframe::io::AppLogger::shutdown();
}
} cliLoggerScope;
omniframe::io::AppLogger::info(
QStringLiteral("CLI"),
QStringLiteral("Execucao omniframe-cli iniciada (%1 argumento(s))").arg(args.size() > 0 ? args.size() - 1 : 0));
if (args.size() <= 1) {
if (jsonStdout) {
emitCliError(QStringLiteral("Nenhum argumento fornecido."));
} else {
printUsage();
}
return 1;
}
bool doValidate = false;
bool doAnalyze = false;
bool doNbrAudit = false;
bool listExamples = false;
bool checkWinInt = false;
bool installWinInt = false;
bool uninstallWinInt = false;
bool fullNewtonTangent = true;
bool enableLineSearch = true;
std::string inputPath;
std::string exampleName;
std::string analysisType = "static";
std::string solverStr = "auto";
std::string nlMethodStr = "nr";
std::string transientSchemeStr = "newmark";
int modesCount = 6;
int stepsCount = 20;
double dtSec = 0.02;
int caseId = -1;
int comboId = -1;
double targetLoadFactor = 1.0;
double imperfectionAmp = 0.0;
int imperfectionMode = 1;
std::vector<std::pair<std::string, std::string>> exports;
std::vector<std::pair<std::string, std::string>> reports;
auto nextIsValue = [&](size_t idx) -> bool {
return idx + 1 < args.size() && !args[idx + 1].empty() && args[idx + 1][0] != '-';
};
for (size_t i = 1; i < args.size(); ++i) {
const std::string& arg = args[i];
if (arg == "--version" || arg == "-v") {
std::cout << "OmniFrame 3D CLI v" << OMNIFRAME_APP_VERSION
<< " (C++23 / Eigen 3.4.0 / Schema 2.1.0)\n";
return 0;
}
if (arg == "--help" || arg == "-h") {
printUsage();
return 0;
}
if (arg == "--json") {
jsonStdout = true;
} else if (arg == "--list-examples") {
listExamples = true;
} else if (arg == "--check-windows-integration") {
checkWinInt = true;
} else if (arg == "--install-windows-integration") {
installWinInt = true;
} else if (arg == "--uninstall-windows-integration") {
uninstallWinInt = true;
} else if (arg == "--nbr-audit" || arg == "--audit-nbr") {
doNbrAudit = true;
if (nextIsValue(i) && inputPath.empty()) {
inputPath = args[++i];
}
} else if (arg == "--example" && i + 1 < args.size()) {
exampleName = args[++i];
} else if (arg == "--validate") {
doValidate = true;
if (nextIsValue(i)) {
inputPath = args[++i];
}
} else if (arg == "--analyze") {
doAnalyze = true;
if (nextIsValue(i)) {
inputPath = args[++i];
}
} else if (arg == "--analysis" && i + 1 < args.size()) {
analysisType = toLowerAscii(args[++i]);
} else if (arg == "--solver" && i + 1 < args.size()) {
solverStr = toLowerAscii(args[++i]);
} else if (arg == "--method" && i + 1 < args.size()) {
nlMethodStr = toLowerAscii(args[++i]);
} else if (arg == "--scheme" && i + 1 < args.size()) {
transientSchemeStr = toLowerAscii(args[++i]);
} else if (arg == "--modes" && i + 1 < args.size()) {
int parsed = 0;
const std::string& raw = args[++i];
if (!parseStrictInt(raw, parsed) || parsed < 1 || parsed > 1000) {
emitCliError(QString("Valor invalido para --modes: '%1' (esperado inteiro entre 1 e 1000).")
.arg(QString::fromUtf8(raw)));
return 1;
}
modesCount = parsed;
} else if (arg == "--steps" && i + 1 < args.size()) {
int parsed = 0;
const std::string& raw = args[++i];
if (!parseStrictInt(raw, parsed) || parsed < 1 || parsed > 1000000) {
emitCliError(QString("Valor invalido para --steps: '%1' (esperado inteiro entre 1 e 1000000).")
.arg(QString::fromUtf8(raw)));
return 1;
}
stepsCount = parsed;
} else if (arg == "--dt" && i + 1 < args.size()) {
double parsed = 0.0;
const std::string& raw = args[++i];
if (!parseStrictDouble(raw, parsed) || parsed <= 0.0 || parsed > 100.0) {
emitCliError(QString("Valor invalido para --dt: '%1' (esperado numero finito em (0, 100]).")
.arg(QString::fromUtf8(raw)));
return 1;
}
dtSec = parsed;
} else if (arg == "--case" && i + 1 < args.size()) {
int parsed = 0;
const std::string& raw = args[++i];
if (!parseStrictInt(raw, parsed) || parsed < 1) {
emitCliError(QString("Valor invalido para --case: '%1' (esperado inteiro >= 1).")
.arg(QString::fromUtf8(raw)));
return 1;
}
caseId = parsed;
} else if (arg == "--combo" && i + 1 < args.size()) {
int parsed = 0;
const std::string& raw = args[++i];
if (!parseStrictInt(raw, parsed) || parsed < 1) {
emitCliError(QString("Valor invalido para --combo: '%1' (esperado inteiro >= 1).")
.arg(QString::fromUtf8(raw)));
return 1;
}
comboId = parsed;
} else if (arg == "--load-factor" && i + 1 < args.size()) {
double parsed = 0.0;
const std::string& raw = args[++i];
if (!parseStrictDouble(raw, parsed) || parsed <= 0.0) {
emitCliError(QString("Valor invalido para --load-factor: '%1' (esperado numero finito > 0).")
.arg(QString::fromUtf8(raw)));
return 1;
}
targetLoadFactor = parsed;
} else if (arg == "--full-tangent") {
fullNewtonTangent = true;
} else if (arg == "--modified-newton") {
fullNewtonTangent = false;
} else if (arg == "--line-search") {
enableLineSearch = true;
} else if (arg == "--no-line-search") {
enableLineSearch = false;
} else if (arg == "--imperfection" && i + 1 < args.size()) {
double parsed = 0.0;
const std::string& raw = args[++i];
if (!parseStrictDouble(raw, parsed)) {
emitCliError(QString("Valor invalido para --imperfection: '%1' (esperado numero finito).")
.arg(QString::fromUtf8(raw)));
return 1;
}
imperfectionAmp = parsed;
} else if (arg == "--imperfection-mode" && i + 1 < args.size()) {
int parsed = 0;
const std::string& raw = args[++i];
if (!parseStrictInt(raw, parsed) || parsed < 1 || parsed > 1000) {
emitCliError(QString("Valor invalido para --imperfection-mode: '%1' (esperado inteiro entre 1 e 1000).")
.arg(QString::fromUtf8(raw)));
return 1;
}
imperfectionMode = parsed;
} else if (arg == "--output" && i + 1 < args.size()) {
outputJsonPath = args[++i];
} else if (arg == "--export" && i + 2 < args.size()) {
const std::string fmt = toLowerAscii(args[++i]);
const std::string& outP = args[++i];
exports.emplace_back(fmt, outP);
} else if (arg == "--report" && i + 2 < args.size()) {
const std::string fmt = toLowerAscii(args[++i]);
const std::string& outP = args[++i];
reports.emplace_back(fmt, outP);
} else {
emitCliError(QString("Argumento desconhecido ou incompleto: %1").arg(QString::fromUtf8(arg)));
return 1;
}
}
if (listExamples) {
const StructuralModel ex1 = StructuralModel::createBuildingFrameExample();
const StructuralModel ex2 = StructuralModel::createCantileverLFrameExample();
const StructuralModel ex3 = StructuralModel::createSpaceTrussExample();
QJsonArray arr;
auto addEx = [&](int id, const char* key, const char* label, const StructuralModel& m) {
QJsonObject o;
o["id"] = id;
o["name"] = QString::fromLatin1(key);
o["title"] = QString::fromUtf8(label);
o["nodes"] = static_cast<int>(m.getNodes().size());
o["elements"] = static_cast<int>(m.getElements().size());
o["loadCases"] = static_cast<int>(m.getLoadCases().size());
o["loadCombinations"] = static_cast<int>(m.getLoadCombinations().size());
arr.append(o);
};
addEx(1, "building", "Pórtico Espacial de Edifício (2 Pavimentos, Vento e Sobrecarga)", ex1);
addEx(2, "cantilever", "Balanço Espacial em L Sujeito a Flexo-Torção", ex2);
addEx(3, "truss", "Treliça Espacial / Passarela Metálica 3D", ex3);
QJsonObject out;
out["success"] = true;
out["schemaVersion"] = QStringLiteral("2.1.0");
out["examples"] = arr;
writeJsonFile(out);
if (jsonStdout) {
std::cout << QJsonDocument(out).toJson(QJsonDocument::Indented).toStdString();
} else {
std::cout << "Exemplos embutidos do OmniFrame 3D:\n"
<< " 1 | building — Pórtico Espacial de Edifício (" << ex1.getNodes().size()
<< " nós, " << ex1.getElements().size() << " barras)\n"
<< " 2 | cantilever — Balanço Espacial em L (" << ex2.getNodes().size()
<< " nós, " << ex2.getElements().size() << " barras)\n"
<< " 3 | truss — Treliça Espacial 3D (" << ex3.getNodes().size()
<< " nós, " << ex3.getElements().size() << " barras)\n";
}
return 0;
}
if (installWinInt || uninstallWinInt || checkWinInt) {
QString details;
bool ok = true;
std::string action = "check";
if (installWinInt) {
action = "install";
ok = os::installWindowsCliIntegration(QString(), &details);
} else if (uninstallWinInt) {
action = "uninstall";
ok = os::uninstallWindowsCliIntegration(QString(), &details);
}
const os::CliIntegrationStatus st = os::queryWindowsCliIntegration();
QJsonObject out = windowsStatusToJson(st);
out["action"] = QString::fromLatin1(action.c_str());
out["success"] = ok;
if (!details.isEmpty()) {
out["details"] = details;
}
writeJsonFile(out);
if (jsonStdout) {
std::cout << QJsonDocument(out).toJson(QJsonDocument::Indented).toStdString();
} else {
std::cout << "Integração Windows 10/11 (CMD & PowerShell) [" << action << "]: "
<< (ok ? "OK" : "FALHA") << "\n"
<< " Diretório instalado: " << st.installDirectory.toStdString() << "\n"
<< " omniframe-cli.exe existe: " << (st.cliBinaryExists ? "Sim" : "Não") << "\n"
<< " OmniFrame.exe existe: " << (st.guiBinaryExists ? "Sim" : "Não") << "\n"
<< " PATH do usuário (HKCU): " << (st.installDirInUserPath ? "Sim" : "Não") << "\n"
<< " PATH do sistema (HKLM): " << (st.installDirInSystemPath ? "Sim" : "Não") << "\n"
<< " App Paths omniframe-cli: " << (st.appPathsCliRegistered ? "Sim" : "Não") << "\n"
<< " App Paths OmniFrame.exe: " << (st.appPathsGuiRegistered ? "Sim" : "Não") << "\n"
<< " Associação .omniframe: " << (st.fileAssocRegistered ? "Sim" : "Não") << "\n"
<< " Pronto no CMD/PowerShell: " << (st.isReadyForCmdAndPowerShell() ? "Sim" : "Não") << "\n";
if (!details.isEmpty()) {
std::cout << " Detalhes: " << details.toStdString() << "\n";
}
}
return ok ? 0 : 1;
}
if (doNbrAudit && !doValidate && !doAnalyze && (!inputPath.empty() || !exampleName.empty())) {
doAnalyze = true;
}
if (!exampleName.empty() && !doValidate && !doAnalyze) {
doAnalyze = true;
}
if ((inputPath.empty() && exampleName.empty()) || (!doValidate && !doAnalyze)) {
if (jsonStdout) {
emitCliError(QStringLiteral("Informe um arquivo de entrada ou --example com --validate/--analyze."));
} else {
printUsage();
}
return 1;
}
StructuralModel model;
std::string canonicalExample;
if (!exampleName.empty()) {
if (!createBuiltInExample(exampleName, model, canonicalExample)) {
emitCliError(QString("Exemplo desconhecido: %1 (use building, cantilever, truss ou 1, 2, 3)")
.arg(QString::fromUtf8(exampleName)));
return 1;
}
} else {
std::string loadErr;
if (!loadModelAnyFormat(inputPath, model, loadErr)) {
emitCliError(QString::fromUtf8(loadErr));
return 1;
}
}
const ModelValidation val = model.validate();
QJsonObject root;
root["schemaVersion"] = "2.1.0";
root["inputFile"] = !inputPath.empty()
? QString::fromUtf8(inputPath)
: QString("example:%1").arg(QString::fromStdString(canonicalExample));
if (!canonicalExample.empty()) {
root["exampleName"] = QString::fromStdString(canonicalExample);
}
root["nodes"] = static_cast<int>(model.getNodes().size());
root["elements"] = static_cast<int>(model.getElements().size());
root["surfaceNodes"] = static_cast<int>(model.surfaceMesh().nodes.size());
root["surfaceElements"] = static_cast<int>(model.surfaceMesh().elements.size());
root["valid"] = val.valid;
QJsonArray errArr, warnArr, issuesArr;
for (const auto& e : val.errors) errArr.append(QString::fromStdString(e));
for (const auto& w : val.warnings) warnArr.append(QString::fromStdString(w));
for (const auto& iss : val.issues) {
QJsonObject ij;
ij["severity"] = QString::fromLatin1(issueSeverityName(iss.severity));
ij["code"] = QString::fromStdString(iss.code);
ij["category"] = QString::fromStdString(iss.category);
ij["entityId"] = QString::fromStdString(iss.entityId);
ij["message"] = QString::fromStdString(iss.message);
issuesArr.append(ij);
}
root["validationErrors"] = errArr;
root["validationWarnings"] = warnArr;
root["validationIssues"] = issuesArr;
auto emitJson = [&](const QJsonObject& obj) {
writeJsonFile(obj);
if (jsonStdout || !doAnalyze) {
const QByteArray bytes = QJsonDocument(obj).toJson(QJsonDocument::Indented);
std::cout << bytes.toStdString();
}
};
if (doValidate && !doAnalyze) {
root["success"] = val.valid;
emitJson(root);
return val.valid ? 0 : 2;
}
if (!val.valid) {
root["success"] = false;
emitJson(root);
return 2;
}
kernel::LinearSolverOptions linOpts = model.solverOptions();
if (solverStr == "ldlt") linOpts.type = kernel::LinearSolverType::SimplicialLDLT;
else if (solverStr == "llt") linOpts.type = kernel::LinearSolverType::SimplicialLLT;
else if (solverStr == "sparselu") linOpts.type = kernel::LinearSolverType::SparseLU;
else if (solverStr == "cg") linOpts.type = kernel::LinearSolverType::ConjugateGradient;
else if (solverStr == "bicgstab") linOpts.type = kernel::LinearSolverType::BiCGSTAB;
else linOpts.type = kernel::LinearSolverType::Auto;
if (std::abs(imperfectionAmp) > 0.0) {
kernel::BucklingOptions preBo;
preBo.numModes = std::max(modesCount, imperfectionMode);
const auto preBRes = FemSolver3D::solveBuckling(model, preBo);
std::string impErr;
if (!FemSolver3D::applyBucklingImperfection(
model, preBRes, imperfectionMode - 1, imperfectionAmp, &impErr)) {
root["success"] = false;
root["error"] = QString::fromStdString(
impErr.empty() ? "Falha ao aplicar imperfeição geométrica de flambagem." : impErr);
emitJson(root);
return 2;
}
QJsonObject impObj;
impObj["amplitudeM"] = imperfectionAmp;
impObj["mode"] = imperfectionMode;
if (imperfectionMode - 1 < static_cast<int>(preBRes.loadFactors.size())) {
impObj["criticalLoadFactor"] = preBRes.loadFactors[static_cast<size_t>(imperfectionMode - 1)];
}
root["appliedImperfection"] = impObj;
}
SolverResult staticRes;
std::optional<kernel::ModalResult> modalResOpt;
std::optional<kernel::BucklingResult> bucklingResOpt;
std::optional<kernel::NonlinearResult> nlResOpt;
bool analysisSuccess = false;
root["analysisType"] = QString::fromStdString(analysisType);
if (analysisType == "static") {
staticRes = FemSolver3D::solveWithOptions(model, linOpts);
analysisSuccess = staticRes.success;
root["success"] = staticRes.success;
root["error"] = QString::fromStdString(staticRes.errorMessage);
root["totalDofs"] = staticRes.totalDofs;
root["restrainedDofs"] = staticRes.restrainedDofs;
root["totalSurfaceNodes"] = staticRes.totalSurfaceNodes;
root["totalSurfaceElements"] = staticRes.totalSurfaceElements;
root["maxNodalDisplacement"] = staticRes.maxNodalDisplacement;
root["maxShellVonMises"] = staticRes.maxShellVonMises;
root["maxSolidVonMises"] = staticRes.maxSolidVonMises;
root["totalStrainEnergy"] = staticRes.totalStrainEnergy;
root["equilibriumBalanced"] = staticRes.equilibrium.isBalanced;
root["relativeResidual"] = staticRes.solverStats.relativeResidual;
root["solverMessage"] = QString::fromStdString(staticRes.solverStats.message);
root["usedFallback"] = (staticRes.solverStats.message.find("Fallback") != std::string::npos ||
staticRes.solverStats.message.find("fallback") != std::string::npos);
root["executionTimeMs"] = staticRes.executionTimeMs;
QJsonArray contArr;
for (const auto& cr : staticRes.continuumElementResults) {
QJsonObject cj;
cj["elementId"] = cr.elementId;
cj["cellType"] = QString::fromStdString(cr.cellTypeName);
cj["isShell"] = cr.isShell;
cj["isSolid"] = cr.isSolid;
cj["vonMisesStress"] = cr.vonMisesStress;
cj["maxPrincipalStress"] = cr.maxPrincipalStress;
cj["minPrincipalStress"] = cr.minPrincipalStress;
contArr.append(cj);
}
root["continuumElements"] = contArr;
if (staticRes.success && (caseId > 0 || comboId > 0)) {
std::vector<kernel::CaseDisplacementResult> caseRes, comboRes;
kernel::EnvelopeExtremes env;
std::string ccErr;
if (!FemSolver3D::solveLoadCasesAndCombinations(model, linOpts, caseRes, comboRes, env, &ccErr)) {
analysisSuccess = false;
root["success"] = false;
root["error"] = QString::fromStdString(ccErr.empty() ? "Falha ao resolver casos/combinacoes" : ccErr);
} else {
const kernel::CaseDisplacementResult* chosen = nullptr;
if (comboId > 0) {
for (const auto& c : comboRes) {
if (c.caseOrComboId == comboId) { chosen = &c; break; }
}
} else {
for (const auto& c : caseRes) {
if (c.caseOrComboId == caseId) { chosen = &c; break; }
}
}
if (!chosen) {
analysisSuccess = false;
root["success"] = false;
root["error"] = QString("Caso/Combinacao especificado (%1) nao encontrado").arg(comboId > 0 ? comboId : caseId);
} else {
const auto field = FemSolver3D::extractNodalDisplacements(model, chosen->U_full);
for (auto& fn : model.getNodes()) {
const auto it = field.frameNodes.find(fn.id);