forked from OpenKotOR/mdledit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarywrite.cpp
More file actions
2536 lines (2259 loc) · 127 KB
/
Copy pathbinarywrite.cpp
File metadata and controls
2536 lines (2259 loc) · 127 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 "MDL.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <limits>
#include <sstream>
#include <utility>
/**
Functions:
MDL::Compile()
MDL::WriteAabb()
MDL::WriteNodes()
*/
unsigned nMdxPrevPadding = 0;
namespace {
unsigned char placeholder[4] = {0xFF, 0xFF, 0xFF, 0xFF};
std::string sAabbNodePrefix;
std::string sWriteNodePrefix;
std::vector<const Node*> vWrittenNodes;
std::vector<std::pair<const Node*, unsigned>> vMdxOffsetPlaceholders;
std::vector<std::pair<const Node*, unsigned int>> vNodeWriteOffsets;
std::vector<unsigned int> vAnimationWriteOffsets;
unsigned nHeadRootPlaceholder = 0;
bool bHeadRootPlaceholderPending = false;
class BinaryFileRollbackGuard{
struct Entry{
BinaryFile * file = nullptr;
BinaryFile::BufferState state;
};
std::vector<Entry> entries;
bool bActive = true;
public:
void Track(BinaryFile * file){
if(file == nullptr) return;
Entry entry;
entry.file = file;
entry.state = file->CaptureBufferState();
entries.push_back(std::move(entry));
}
void Commit(){
bActive = false;
}
void Rollback(){
if(!bActive) return;
for(auto it = entries.rbegin(); it != entries.rend(); ++it){
if(it->file != nullptr) it->file->RestoreBufferState(it->state);
}
bActive = false;
}
~BinaryFileRollbackGuard(){
Rollback();
}
};
class CompileOutputRollbackGuard{
MDL & mdl;
BinaryFileRollbackGuard buffers;
bool bHadMdx = false;
bool bActive = true;
public:
explicit CompileOutputRollbackGuard(MDL & mdl_) : mdl(mdl_), bHadMdx(static_cast<bool>(mdl_.Mdx)){
buffers.Track(&mdl);
if(mdl.Mdx) buffers.Track(mdl.Mdx.get());
if(mdl.Wok) buffers.Track(mdl.Wok.get());
if(mdl.Pwk) buffers.Track(mdl.Pwk.get());
if(mdl.Dwk0) buffers.Track(mdl.Dwk0.get());
if(mdl.Dwk1) buffers.Track(mdl.Dwk1.get());
if(mdl.Dwk2) buffers.Track(mdl.Dwk2.get());
}
void Commit(){
bActive = false;
buffers.Commit();
}
~CompileOutputRollbackGuard(){
if(!bActive) return;
// Restore tracked output buffers before discarding any writer-created
// companion objects.
buffers.Rollback();
if(!bHadMdx) mdl.Mdx.reset();
}
};
void RememberMdxOffsetPlaceholder(const Node & node, unsigned nPlaceholder){
for(auto & entry : vMdxOffsetPlaceholders){
if(entry.first == &node){
entry.second = nPlaceholder;
return;
}
}
vMdxOffsetPlaceholders.push_back(std::make_pair(&node, nPlaceholder));
}
bool HasMdxOffsetPlaceholder(const Node & node){
for(const auto & entry : vMdxOffsetPlaceholders){
if(entry.first == &node) return true;
}
return false;
}
unsigned GetMdxOffsetPlaceholder(const Node & node){
for(const auto & entry : vMdxOffsetPlaceholders){
if(entry.first == &node) return entry.second;
}
throw mdlexception("Internal writer error: requested MDX offset placeholder before the mesh header was written.");
}
void RememberNodeWriteOffset(const Node & node, unsigned int nOffset){
for(auto & entry : vNodeWriteOffsets){
if(entry.first == &node){
entry.second = nOffset;
return;
}
}
vNodeWriteOffsets.push_back(std::make_pair(&node, nOffset));
}
unsigned int GetNodeWriteOffset(const Node & node){
for(const auto & entry : vNodeWriteOffsets){
if(entry.first == &node) return entry.second;
}
throw mdlexception("Internal writer error: requested node offset before the node was written.");
}
void RememberAnimationWriteOffset(std::size_t nIndex, unsigned int nOffset){
if(nIndex >= vAnimationWriteOffsets.size()){
throw mdlexception("Internal writer error: animation offset index is out of range.");
}
vAnimationWriteOffsets[nIndex] = nOffset;
}
unsigned int GetAnimationWriteOffset(unsigned int nIndex){
if(nIndex >= vAnimationWriteOffsets.size()){
throw mdlexception("Internal writer error: animation root offset index is out of range.");
}
return vAnimationWriteOffsets[nIndex];
}
bool IsEmptyNodeSlot(const Node & node){
return node.Head.nType == 0 && !node.Head.nNameIndex.Valid();
}
std::size_t CountNonEmptyNodes(const std::vector<Node> & nodes){
std::size_t nCount = 0;
for(const Node & node : nodes){
if(!IsEmptyNodeSlot(node)) ++nCount;
}
return nCount;
}
void ValidateUniqueNodeNameIndices(const std::vector<Node> & nodes, std::size_t nNameCount, const std::string & sContext){
std::vector<const Node*> seen(nNameCount, nullptr);
for(const Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(node.Head.nType == 0 || !node.Head.nNameIndex.Valid()){
throw mdlexception(sContext + " contains a non-empty node slot with no node type or an invalid name index; refusing to write ambiguous hierarchy data.");
}
const unsigned short nNameIndex = static_cast<unsigned short>(node.Head.nNameIndex);
if(nNameIndex >= nNameCount){
throw mdlexception(sContext + " contains a node name index outside the model name table.");
}
if(seen.at(nNameIndex) != nullptr){
throw mdlexception(sContext + " contains duplicate node name indices; refusing to choose one and possibly move child data to the wrong node.");
}
seen.at(nNameIndex) = &node;
}
}
Node & FindNodeByNameIndex(std::vector<Node> & nodes, unsigned short nNameIndex, const std::string & sContext){
for(Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(node.Head.nNameIndex.Valid() && static_cast<unsigned short>(node.Head.nNameIndex) == nNameIndex){
return node;
}
}
throw mdlexception("Cannot write " + sContext + ": root/tree-order node is not present in the node array.");
}
Node & FindGeometryRootNodeForWrite(ModelHeader & mh){
if(!mh.NameIndicesInTreeOrder.empty()){
const unsigned short nRootNameIndex = mh.NameIndicesInTreeOrder.front();
if(nRootNameIndex >= mh.Names.size()){
throw mdlexception("Cannot write geometry: preserved tree-order root is outside the model name table.");
}
return FindNodeByNameIndex(mh.ArrayOfNodes, nRootNameIndex, "geometry");
}
Node * pRoot = nullptr;
for(Node & node : mh.ArrayOfNodes){
if(IsEmptyNodeSlot(node)) continue;
if(!node.Head.nParentIndex.Valid()){
if(pRoot != nullptr){
throw mdlexception("Cannot write geometry: multiple root nodes were found and no preserved tree order is available; refusing to choose one and omit the rest.");
}
pRoot = &node;
}
}
if(pRoot == nullptr){
throw mdlexception("Cannot write geometry: no root node is available.");
}
return *pRoot;
}
Node & FindAnimationRootNodeForWrite(std::vector<Node> & nodes, const std::string & sContext){
Node * pRoot = nullptr;
for(Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(!node.Head.nParentIndex.Valid()){
if(pRoot != nullptr){
throw mdlexception("Cannot write " + sContext + ": multiple root nodes were found; refusing to choose one and omit the rest.");
}
pRoot = &node;
}
}
if(pRoot != nullptr) return *pRoot;
if(nodes.empty()){
throw mdlexception("Cannot write " + sContext + ": animation contains no nodes.");
}
if(IsEmptyNodeSlot(nodes.front())){
throw mdlexception("Cannot write " + sContext + ": the first animation node slot is empty and no root node was found.");
}
// Some animation arrays preserve a root-first ordering even when the parent
// metadata is inherited from/supermodel-linked. Prefer preserving that
// ordering over silently dropping the animation, then verify reachability.
return nodes.front();
}
void EnsureAllNodesWritten(const std::vector<Node> & nodes, const std::string & sContext){
for(const Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(std::find(vWrittenNodes.begin(), vWrittenNodes.end(), &node) == vWrittenNodes.end()){
throw mdlexception(sContext + " contains a node that is not reachable from the selected root; refusing to silently drop it from the binary output.");
}
}
}
void ValidateHierarchyForWrite(const Node & root, const std::vector<Node> & nodes, std::size_t nNameCount, const std::string & sContext){
std::vector<const Node*> byName(nNameCount, nullptr);
for(const Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(!node.Head.nNameIndex.Valid()){
throw mdlexception(sContext + " contains a node with an invalid name index.");
}
const unsigned short nNameIndex = static_cast<unsigned short>(node.Head.nNameIndex);
if(nNameIndex >= nNameCount){
throw mdlexception(sContext + " contains a node name index outside the model name table.");
}
if(byName.at(nNameIndex) != nullptr){
throw mdlexception(sContext + " contains duplicate node name indices in the hierarchy map.");
}
byName.at(nNameIndex) = &node;
}
std::vector<unsigned short> active;
std::vector<unsigned short> visited;
std::function<void(const Node&)> Visit = [&](const Node & node){
if(!node.Head.nNameIndex.Valid()){
throw mdlexception(sContext + " hierarchy contains a node with an invalid name index.");
}
const unsigned short nNameIndex = static_cast<unsigned short>(node.Head.nNameIndex);
if(nNameIndex >= nNameCount || byName.at(nNameIndex) != &node){
throw mdlexception(sContext + " hierarchy root/child does not resolve to the node array by name index.");
}
if(std::find(active.begin(), active.end(), nNameIndex) != active.end()){
throw mdlexception(sContext + " hierarchy contains a child cycle; refusing to write cyclic node data.");
}
if(std::find(visited.begin(), visited.end(), nNameIndex) != visited.end()){
throw mdlexception(sContext + " hierarchy reaches the same node more than once; refusing to write ambiguous shared child data.");
}
active.push_back(nNameIndex);
visited.push_back(nNameIndex);
std::vector<unsigned short> localChildren;
localChildren.reserve(node.Head.ChildIndices.size());
for(const auto & childIndex : node.Head.ChildIndices){
if(!childIndex.Valid()){
throw mdlexception(sContext + " hierarchy contains an invalid child name index.");
}
const unsigned short nChildIndex = static_cast<unsigned short>(childIndex);
if(nChildIndex >= nNameCount){
throw mdlexception(sContext + " hierarchy contains a child name index outside the model name table.");
}
if(nChildIndex == nNameIndex){
throw mdlexception(sContext + " hierarchy contains a node listed as its own child.");
}
if(std::find(localChildren.begin(), localChildren.end(), nChildIndex) != localChildren.end()){
throw mdlexception(sContext + " hierarchy contains the same child more than once under one parent.");
}
const Node * child = byName.at(nChildIndex);
if(child == nullptr){
throw mdlexception(sContext + " hierarchy child name index does not resolve to a node.");
}
if(!child->Head.nParentIndex.Valid()){
throw mdlexception(sContext + " hierarchy lists a root node as a child; refusing to write inconsistent parent/child pointers.");
}
if(static_cast<unsigned short>(child->Head.nParentIndex) != nNameIndex){
throw mdlexception(sContext + " hierarchy child parent index does not match the parent that lists it; refusing to write a node under one parent while its header points to another.");
}
localChildren.push_back(nChildIndex);
Visit(*child);
}
active.pop_back();
};
Visit(root);
}
void ResetBinaryWriterState(){
vWrittenNodes.clear();
vMdxOffsetPlaceholders.clear();
vNodeWriteOffsets.clear();
vAnimationWriteOffsets.clear();
nHeadRootPlaceholder = 0;
bHeadRootPlaceholderPending = false;
}
template<typename T>
struct ScopedValueRestore{
T & ref;
T oldValue;
explicit ScopedValueRestore(T & value) : ref(value), oldValue(value) {}
~ScopedValueRestore(){ ref = oldValue; }
ScopedValueRestore(const ScopedValueRestore &) = delete;
ScopedValueRestore & operator=(const ScopedValueRestore &) = delete;
};
unsigned short SkinCompactSlotToFullBone(const Node & node, unsigned int nSlot){
if(nSlot < 16) return node.Skin.nBoneIndices.at(nSlot);
if(nSlot == 16) return node.Skin.nPadding1;
throw mdlexception("Skin compact slot is outside the vanilla 0..16 range.");
}
unsigned short CheckedUShortCount(std::size_t nValue, const std::string & sWhat){
if(nValue > std::numeric_limits<unsigned short>::max()){
throw mdlexception(sWhat + " exceeds the 16-bit count limit and cannot be written without truncating data.");
}
return static_cast<unsigned short>(nValue);
}
unsigned int CheckedUIntCount(std::size_t nValue, const std::string & sWhat){
if(nValue > std::numeric_limits<unsigned int>::max()){
throw mdlexception(sWhat + " exceeds the 32-bit count limit and cannot be written without truncating data.");
}
return static_cast<unsigned int>(nValue);
}
unsigned int CheckedUIntTripleCount(std::size_t nValue, const std::string & sWhat){
if(nValue > std::numeric_limits<unsigned int>::max() / 3u){
throw mdlexception(sWhat + " exceeds the 32-bit count limit and cannot be written without truncating data.");
}
return static_cast<unsigned int>(nValue * 3u);
}
unsigned short MaxUsedNodeNameIndex(const std::vector<Node> & nodes, const std::string & sContext){
bool bAnyNode = false;
unsigned short nMaxNameIndex = 0;
for(const Node & node : nodes){
if(IsEmptyNodeSlot(node)) continue;
if(!node.Head.nNameIndex.Valid()){
throw mdlexception(sContext + " contains a non-empty node with an invalid name index.");
}
const unsigned short nNameIndex = static_cast<unsigned short>(node.Head.nNameIndex);
if(!bAnyNode || nNameIndex > nMaxNameIndex) nMaxNameIndex = nNameIndex;
bAnyNode = true;
}
if(!bAnyNode){
throw mdlexception(sContext + " contains no non-empty nodes.");
}
return nMaxNameIndex;
}
unsigned int AnimationNodeCountForWrite(const Animation & anim, const std::string & sContext, std::size_t nFallbackNameCount){
const unsigned short nMaxUsedNameIndex = MaxUsedNodeNameIndex(anim.ArrayOfNodes, sContext);
const std::size_t nMinimumCount = static_cast<std::size_t>(nMaxUsedNameIndex) + 1u;
const std::size_t nLocalNodeCount = CountNonEmptyNodes(anim.ArrayOfNodes);
const std::size_t nRequiredCount = std::max(nMinimumCount, nLocalNodeCount);
const std::size_t nCandidateCount = anim.nNumberOfNames != 0 ? static_cast<std::size_t>(anim.nNumberOfNames) : nFallbackNameCount;
if(nCandidateCount < nRequiredCount){
throw mdlexception(sContext + " has a preserved node-count/header value smaller than the node name indices it actually uses; refusing to write a header that could truncate or move animation nodes.");
}
return CheckedUIntCount(nCandidateCount, sContext + " node count");
}
unsigned NextMdxPadding(unsigned nEndOffset){
const unsigned nRemainder = nEndOffset % 16u;
return nRemainder == 0u ? 0u : 16u - nRemainder;
}
struct MdxLayout{
unsigned int nMdxDataSize = 0;
unsigned short nNumberOfVerts = 0;
MdlInteger<unsigned int> nOffsetToMdxVertex;
MdlInteger<unsigned int> nOffsetToMdxNormal;
MdlInteger<unsigned int> nOffsetToMdxColor;
MdlInteger<unsigned int> nOffsetToMdxUV1;
MdlInteger<unsigned int> nOffsetToMdxUV2;
MdlInteger<unsigned int> nOffsetToMdxUV3;
MdlInteger<unsigned int> nOffsetToMdxUV4;
MdlInteger<unsigned int> nOffsetToMdxTangent1;
MdlInteger<unsigned int> nOffsetToMdxTangent2;
MdlInteger<unsigned int> nOffsetToMdxTangent3;
MdlInteger<unsigned int> nOffsetToMdxTangent4;
MdlInteger<unsigned int> nOffsetToMdxWeightValues;
MdlInteger<unsigned int> nOffsetToMdxBoneIndices;
};
void AddMdxComponentOffset(bool bPresent, unsigned int nComponentSize, unsigned int & nMdxSize, MdlInteger<unsigned int> & nOffset){
if(bPresent){
nOffset = nMdxSize;
if(nComponentSize > std::numeric_limits<unsigned int>::max() - nMdxSize){
throw mdlexception("MDX vertex layout is too large to write safely.");
}
nMdxSize += nComponentSize;
}
else{
nOffset = MdlInteger<unsigned int>();
}
}
MdxLayout BuildMdxLayout(const Node & node, bool bXbox, const std::string & sNodeName){
MdxLayout layout;
layout.nNumberOfVerts = CheckedUShortCount(node.Mesh.Vertices.size(),
"Node '" + sNodeName + "' vertex count");
unsigned int nMdxSize = 0;
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_VERTEX) != 0, 12, nMdxSize, layout.nOffsetToMdxVertex);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_NORMAL) != 0, bXbox ? 4 : 12, nMdxSize, layout.nOffsetToMdxNormal);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_COLOR) != 0, 12, nMdxSize, layout.nOffsetToMdxColor);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_UV1) != 0, 8, nMdxSize, layout.nOffsetToMdxUV1);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_UV2) != 0, 8, nMdxSize, layout.nOffsetToMdxUV2);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_UV3) != 0, 8, nMdxSize, layout.nOffsetToMdxUV3);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_UV4) != 0, 8, nMdxSize, layout.nOffsetToMdxUV4);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_TANGENT1) != 0, bXbox ? 12 : 36, nMdxSize, layout.nOffsetToMdxTangent1);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_TANGENT2) != 0, bXbox ? 12 : 36, nMdxSize, layout.nOffsetToMdxTangent2);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_TANGENT3) != 0, bXbox ? 12 : 36, nMdxSize, layout.nOffsetToMdxTangent3);
AddMdxComponentOffset((node.Mesh.nMdxDataBitmap & MDX_FLAG_TANGENT4) != 0, bXbox ? 12 : 36, nMdxSize, layout.nOffsetToMdxTangent4);
if(node.Head.nType & NODE_SKIN){
layout.nOffsetToMdxWeightValues = nMdxSize;
if(16u > std::numeric_limits<unsigned int>::max() - nMdxSize){
throw mdlexception("MDX skin weight layout is too large to write safely.");
}
nMdxSize += 16u;
layout.nOffsetToMdxBoneIndices = nMdxSize;
const unsigned int nBoneIndexBytes = bXbox ? 8u : 16u;
if(nBoneIndexBytes > std::numeric_limits<unsigned int>::max() - nMdxSize){
throw mdlexception("MDX skin bone-index layout is too large to write safely.");
}
nMdxSize += nBoneIndexBytes;
}
layout.nMdxDataSize = nMdxSize;
if(node.Mesh.Vertices.empty()) layout.nMdxDataSize = INVALID_INT;
if(node.Head.nType & NODE_SABER) layout.nMdxDataSize = 0;
return layout;
}
void ValidateMeshFaceIndices(const Node & node, const std::string & sNodeName){
const std::size_t nVertexCount = node.Mesh.Vertices.size();
for(std::size_t f = 0; f < node.Mesh.Faces.size(); ++f){
const Face & face = node.Mesh.Faces.at(f);
for(int i = 0; i < 3; ++i){
const MdlInteger<unsigned short> & nIndex = face.nIndexVertex.at(i);
if(!nIndex.Valid()){
throw mdlexception("Face " + std::to_string(f) + " on node '" + sNodeName + "' has an invalid vertex index.");
}
if(static_cast<unsigned short>(nIndex) >= nVertexCount){
throw mdlexception("Face " + std::to_string(f) + " on node '" + sNodeName + "' references vertex " +
std::to_string(static_cast<unsigned short>(nIndex)) + ", but the node only has " +
std::to_string(nVertexCount) + " vertices.");
}
}
}
}
void ValidateMeshDerivedIndexData(const Node & node, const std::string & sNodeName){
ValidateMeshFaceIndices(node, sNodeName);
const std::size_t nVertexCount = node.Mesh.Vertices.size();
if((node.Head.nType & NODE_MESH) && !(node.Head.nType & NODE_SABER) && !node.Mesh.Faces.empty()){
if(node.Mesh.VertIndices.size() != node.Mesh.Faces.size()){
throw mdlexception("Node '" + sNodeName + "' has " + std::to_string(node.Mesh.Faces.size()) +
" faces but " + std::to_string(node.Mesh.VertIndices.size()) +
" inverted-index rows; refusing to write malformed mesh index data.");
}
for(std::size_t f = 0; f < node.Mesh.VertIndices.size(); ++f){
for(int i = 0; i < 3; ++i){
if(node.Mesh.VertIndices.at(f).at(i) >= nVertexCount){
throw mdlexception("Node '" + sNodeName + "' inverted-index row " + std::to_string(f) +
" references vertex " + std::to_string(node.Mesh.VertIndices.at(f).at(i)) +
", which is outside the vertex array.");
}
}
}
}
}
bool HasPreservedArrayHeader(const ArrayHead & array){
return array.nOffset != 0 || array.nCount != 0 || array.nCount2 != 0;
}
void ValidateSkinArrayHeaderParity(const Node & node, const std::string & sNodeName){
if(!(node.Head.nType & NODE_SKIN)) return;
const unsigned int nBoneCount = CheckedUIntCount(node.Skin.Bones.size(),
"Node '" + sNodeName + "' skin bone count");
auto CheckArray = [&](const ArrayHead & array, const std::string & sArrayName){
if(!HasPreservedArrayHeader(array)) return;
if(array.nCount != nBoneCount || array.nCount2 != nBoneCount){
throw mdlexception("Node '" + sNodeName + "' has a preserved " + sArrayName +
" count that does not match the skin bone count; refusing to normalize and erase mismatched binary header data.");
}
};
CheckArray(node.Skin.QBoneArray, "QBoneArray");
CheckArray(node.Skin.TBoneArray, "TBoneArray");
CheckArray(node.Skin.Array8Array, "boneconstantindices/Array8Array");
}
void ValidateModelTotalNodeCountForWrite(const ModelHeader & mh){
const std::size_t nLocalNodeCount = CountNonEmptyNodes(mh.ArrayOfNodes);
if(nLocalNodeCount > std::numeric_limits<unsigned int>::max()){
throw mdlexception("Geometry node count exceeds the 32-bit header range.");
}
if(mh.GH.nTotalNumberOfNodes < nLocalNodeCount){
throw mdlexception("Geometry totalnodes value is smaller than the number of local geometry nodes; refusing to write a header that can truncate or misrepresent the model hierarchy.");
}
}
void ValidateBwmForWrite(const BWMHeader & data){
const std::size_t nVertexCount = data.verts.size();
const std::size_t nFaceCount = data.faces.size();
if(nFaceCount > std::numeric_limits<unsigned int>::max() / 3u){
throw mdlexception("Walkmesh face count is too large to validate adjacency indices safely.");
}
const unsigned int nMaxEdgeReference = static_cast<unsigned int>(nFaceCount * 3u);
for(std::size_t f = 0; f < nFaceCount; ++f){
const Face & face = data.faces.at(f);
for(int i = 0; i < 3; ++i){
const MdlInteger<unsigned short> & nIndex = face.nIndexVertex.at(i);
if(!nIndex.Valid()){
throw mdlexception("Walkmesh face " + std::to_string(f) + " has an invalid vertex index; refusing to write malformed walkmesh data.");
}
if(static_cast<unsigned short>(nIndex) >= nVertexCount){
throw mdlexception("Walkmesh face " + std::to_string(f) + " references vertex " +
std::to_string(static_cast<unsigned short>(nIndex)) +
", but the walkmesh only has " + std::to_string(nVertexCount) + " vertices.");
}
const MdlInteger<unsigned short> & nAdjacent = face.nAdjacentFaces.at(i);
if(nAdjacent.Valid() && static_cast<unsigned short>(nAdjacent) >= nMaxEdgeReference){
throw mdlexception("Walkmesh face " + std::to_string(f) + " adjacent edge reference " +
std::to_string(static_cast<unsigned short>(nAdjacent)) +
" is outside the walkmesh edge-reference range.");
}
}
}
for(std::size_t a = 0; a < data.aabb.size(); ++a){
const Aabb & aabb = data.aabb.at(a);
auto CheckChild = [&](const MdlInteger<unsigned int> & nChild, const char * sChild){
if(!nChild.Valid()) return;
const unsigned int nChildIndex = static_cast<unsigned int>(nChild);
if(nChildIndex >= data.aabb.size()){
throw mdlexception(std::string("Walkmesh AABB ") + std::to_string(a) + " " + sChild +
" references node " + std::to_string(nChildIndex) +
", but only " + std::to_string(data.aabb.size()) + " AABB nodes exist.");
}
if(nChildIndex == a){
throw mdlexception(std::string("Walkmesh AABB ") + std::to_string(a) + " " + sChild +
" references itself; refusing to write cyclic AABB data.");
}
};
CheckChild(aabb.nChild1, "child1");
CheckChild(aabb.nChild2, "child2");
if(aabb.nID.Valid() && static_cast<unsigned short>(aabb.nID) >= nFaceCount){
throw mdlexception("Walkmesh AABB " + std::to_string(a) + " references face " +
std::to_string(static_cast<unsigned short>(aabb.nID)) +
", but the walkmesh only has " + std::to_string(nFaceCount) + " faces.");
}
}
for(std::size_t e = 0; e < data.edges.size(); ++e){
const Edge & edge = data.edges.at(e);
if(edge.nIndex.Valid() && static_cast<unsigned int>(edge.nIndex) >= nMaxEdgeReference){
throw mdlexception("Walkmesh outer edge " + std::to_string(e) + " references a face edge outside the flattened face-edge array.");
}
}
for(std::size_t p = 0; p < data.perimeters.size(); ++p){
if(data.perimeters.at(p).nPerimeter > data.edges.size()){
throw mdlexception("Walkmesh perimeter " + std::to_string(p) + " references more edges than exist in the edge array.");
}
}
}
struct NodeWriteStateGuard{
Node & node;
unsigned int nOffset;
MdlInteger<unsigned int> nHeadOffsetToParent;
ArrayHead ChildrenArray;
ArrayHead ControllerArray;
ArrayHead ControllerDataArray;
ArrayHead FlareSizeArray;
ArrayHead FlarePositionArray;
ArrayHead FlareColorShiftArray;
ArrayHead FlareTextureNameArray;
std::vector<unsigned int> FlareTextureNameOffsets;
ArrayHead FaceArray;
ArrayHead IndexCounterArray;
ArrayHead IndexLocationArray;
ArrayHead MeshInvertedCounterArray;
unsigned int nMdxDataSize;
MdlInteger<unsigned int> nOffsetToMdxVertex;
MdlInteger<unsigned int> nOffsetToMdxNormal;
MdlInteger<unsigned int> nOffsetToMdxColor;
MdlInteger<unsigned int> nOffsetToMdxUV1;
MdlInteger<unsigned int> nOffsetToMdxUV2;
MdlInteger<unsigned int> nOffsetToMdxUV3;
MdlInteger<unsigned int> nOffsetToMdxUV4;
MdlInteger<unsigned int> nOffsetToMdxTangent1;
MdlInteger<unsigned int> nOffsetToMdxTangent2;
MdlInteger<unsigned int> nOffsetToMdxTangent3;
MdlInteger<unsigned int> nOffsetToMdxTangent4;
unsigned short nNumberOfVerts;
unsigned int nOffsetToVertArray;
unsigned int nVertIndicesCount;
unsigned int nVertIndicesLocation;
MdlInteger<unsigned int> nMeshInvertedCounter;
MdlInteger<unsigned int> nOffsetToMdxWeightValues;
MdlInteger<unsigned int> nOffsetToMdxBoneIndices;
unsigned int nOffsetToBonemap;
unsigned int nNumberOfBonemap;
ArrayHead QBoneArray;
ArrayHead TBoneArray;
ArrayHead Array8Array;
ArrayHead ConstraintArray;
unsigned int nOffsetToData2;
MdlInteger<unsigned int> nOffsetToAabb;
unsigned int nOffsetToSaberVerts;
unsigned int nOffsetToSaberUVs;
unsigned int nOffsetToSaberNormals;
explicit NodeWriteStateGuard(Node & node_) :
node(node_),
nOffset(node_.nOffset),
nHeadOffsetToParent(node_.Head.nOffsetToParent),
ChildrenArray(node_.Head.ChildrenArray),
ControllerArray(node_.Head.ControllerArray),
ControllerDataArray(node_.Head.ControllerDataArray),
FlareSizeArray(node_.Light.FlareSizeArray),
FlarePositionArray(node_.Light.FlarePositionArray),
FlareColorShiftArray(node_.Light.FlareColorShiftArray),
FlareTextureNameArray(node_.Light.FlareTextureNameArray),
FaceArray(node_.Mesh.FaceArray),
IndexCounterArray(node_.Mesh.IndexCounterArray),
IndexLocationArray(node_.Mesh.IndexLocationArray),
MeshInvertedCounterArray(node_.Mesh.MeshInvertedCounterArray),
nMdxDataSize(node_.Mesh.nMdxDataSize),
nOffsetToMdxVertex(node_.Mesh.nOffsetToMdxVertex),
nOffsetToMdxNormal(node_.Mesh.nOffsetToMdxNormal),
nOffsetToMdxColor(node_.Mesh.nOffsetToMdxColor),
nOffsetToMdxUV1(node_.Mesh.nOffsetToMdxUV1),
nOffsetToMdxUV2(node_.Mesh.nOffsetToMdxUV2),
nOffsetToMdxUV3(node_.Mesh.nOffsetToMdxUV3),
nOffsetToMdxUV4(node_.Mesh.nOffsetToMdxUV4),
nOffsetToMdxTangent1(node_.Mesh.nOffsetToMdxTangent1),
nOffsetToMdxTangent2(node_.Mesh.nOffsetToMdxTangent2),
nOffsetToMdxTangent3(node_.Mesh.nOffsetToMdxTangent3),
nOffsetToMdxTangent4(node_.Mesh.nOffsetToMdxTangent4),
nNumberOfVerts(node_.Mesh.nNumberOfVerts),
nOffsetToVertArray(node_.Mesh.nOffsetToVertArray),
nVertIndicesCount(node_.Mesh.nVertIndicesCount),
nVertIndicesLocation(node_.Mesh.nVertIndicesLocation),
nMeshInvertedCounter(node_.Mesh.nMeshInvertedCounter),
nOffsetToMdxWeightValues(node_.Skin.nOffsetToMdxWeightValues),
nOffsetToMdxBoneIndices(node_.Skin.nOffsetToMdxBoneIndices),
nOffsetToBonemap(node_.Skin.nOffsetToBonemap),
nNumberOfBonemap(node_.Skin.nNumberOfBonemap),
QBoneArray(node_.Skin.QBoneArray),
TBoneArray(node_.Skin.TBoneArray),
Array8Array(node_.Skin.Array8Array),
ConstraintArray(node_.Dangly.ConstraintArray),
nOffsetToData2(node_.Dangly.nOffsetToData2),
nOffsetToAabb(node_.Walkmesh.nOffsetToAabb),
nOffsetToSaberVerts(node_.Saber.nOffsetToSaberVerts),
nOffsetToSaberUVs(node_.Saber.nOffsetToSaberUVs),
nOffsetToSaberNormals(node_.Saber.nOffsetToSaberNormals)
{
FlareTextureNameOffsets.reserve(node_.Light.FlareTextureNames.size());
for(const auto & name : node_.Light.FlareTextureNames){
FlareTextureNameOffsets.push_back(name.nOffset);
}
}
~NodeWriteStateGuard(){
node.nOffset = nOffset;
node.Head.nOffsetToParent = nHeadOffsetToParent;
node.Head.ChildrenArray = ChildrenArray;
node.Head.ControllerArray = ControllerArray;
node.Head.ControllerDataArray = ControllerDataArray;
node.Light.FlareSizeArray = FlareSizeArray;
node.Light.FlarePositionArray = FlarePositionArray;
node.Light.FlareColorShiftArray = FlareColorShiftArray;
node.Light.FlareTextureNameArray = FlareTextureNameArray;
for(std::size_t i = 0; i < FlareTextureNameOffsets.size() && i < node.Light.FlareTextureNames.size(); ++i){
node.Light.FlareTextureNames[i].nOffset = FlareTextureNameOffsets[i];
}
node.Mesh.FaceArray = FaceArray;
node.Mesh.IndexCounterArray = IndexCounterArray;
node.Mesh.IndexLocationArray = IndexLocationArray;
node.Mesh.MeshInvertedCounterArray = MeshInvertedCounterArray;
node.Mesh.nMdxDataSize = nMdxDataSize;
node.Mesh.nOffsetToMdxVertex = nOffsetToMdxVertex;
node.Mesh.nOffsetToMdxNormal = nOffsetToMdxNormal;
node.Mesh.nOffsetToMdxColor = nOffsetToMdxColor;
node.Mesh.nOffsetToMdxUV1 = nOffsetToMdxUV1;
node.Mesh.nOffsetToMdxUV2 = nOffsetToMdxUV2;
node.Mesh.nOffsetToMdxUV3 = nOffsetToMdxUV3;
node.Mesh.nOffsetToMdxUV4 = nOffsetToMdxUV4;
node.Mesh.nOffsetToMdxTangent1 = nOffsetToMdxTangent1;
node.Mesh.nOffsetToMdxTangent2 = nOffsetToMdxTangent2;
node.Mesh.nOffsetToMdxTangent3 = nOffsetToMdxTangent3;
node.Mesh.nOffsetToMdxTangent4 = nOffsetToMdxTangent4;
node.Mesh.nNumberOfVerts = nNumberOfVerts;
node.Mesh.nOffsetToVertArray = nOffsetToVertArray;
node.Mesh.nVertIndicesCount = nVertIndicesCount;
node.Mesh.nVertIndicesLocation = nVertIndicesLocation;
node.Mesh.nMeshInvertedCounter = nMeshInvertedCounter;
node.Skin.nOffsetToMdxWeightValues = nOffsetToMdxWeightValues;
node.Skin.nOffsetToMdxBoneIndices = nOffsetToMdxBoneIndices;
node.Skin.nOffsetToBonemap = nOffsetToBonemap;
node.Skin.nNumberOfBonemap = nNumberOfBonemap;
node.Skin.QBoneArray = QBoneArray;
node.Skin.TBoneArray = TBoneArray;
node.Skin.Array8Array = Array8Array;
node.Dangly.ConstraintArray = ConstraintArray;
node.Dangly.nOffsetToData2 = nOffsetToData2;
node.Walkmesh.nOffsetToAabb = nOffsetToAabb;
node.Saber.nOffsetToSaberVerts = nOffsetToSaberVerts;
node.Saber.nOffsetToSaberUVs = nOffsetToSaberUVs;
node.Saber.nOffsetToSaberNormals = nOffsetToSaberNormals;
}
};
}
bool MDL::Compile(){
ReportObject ReportMdl(*this);
Timer tCompile;
CompileOutputRollbackGuard compileRollback(*this);
nPosition = 0;
sBuffer.resize(0);
bKnown.resize(0);
bDataLoaded = true;
ResetBinaryWriterState();
nMdxPrevPadding = 0;
if(!Mdx) Mdx.reset(new MDX());
else{
Mdx->GetBuffer().clear();
Mdx->GetKnownData().clear();
Mdx->nPosition = 0;
}
FileHeader &Data = *FH;
std::string sFileHeader = "File Header";
/// File header
WriteNumber(&Data.nZero, 8, sFileHeader + " > Padding");
unsigned PHnMdlLength = WriteBytes(placeholder, 4, 1, sFileHeader + " > MDL File Size"); // to be filled later
unsigned PHnMdxLength = WriteBytes(placeholder, 4, 1, sFileHeader + " > MDX File Size"); // to be filled later
MarkDataBorder(nPosition - 1);
/// Geo Header
std::string sGeometryHeader = "Geometry Header";
// Function pointers
unsigned int nModelFunctionPointer0 = FunctionPointer1(FN_PTR_MODEL);
unsigned int nModelFunctionPointer1 = FunctionPointer2(FN_PTR_MODEL);
WriteNumber(&nModelFunctionPointer0, 9, sGeometryHeader + " > Function Pointers");
WriteNumber(&nModelFunctionPointer1, 9, sGeometryHeader + " > Function Pointers");
// Model name
WriteString(&Data.MH.GH.sName, 32, 3, sGeometryHeader + " > Name");
// Write placeholder for root node offset
unsigned PHnOffsetToRootNode = WriteBytes(placeholder, 4, 6, sGeometryHeader + " > Offset to Root Node");
// Total number of nodes
ValidateModelTotalNodeCountForWrite(Data.MH);
unsigned int nTotalNumberOfNodesToWrite = Data.MH.GH.nTotalNumberOfNodes;
WriteNumber(&nTotalNumberOfNodesToWrite, 1, sGeometryHeader + " > Number of Nodes");
// Empty runtime arrays
WriteNumber(&Data.MH.GH.RuntimeArray1.nOffset, 8, sGeometryHeader + " > Runtime Arrays");
WriteNumber(&Data.MH.GH.RuntimeArray1.nCount, 8, sGeometryHeader + " > Runtime Arrays");
WriteNumber(&Data.MH.GH.RuntimeArray1.nCount2, 8, sGeometryHeader + " > Runtime Arrays");
WriteNumber(&Data.MH.GH.RuntimeArray2.nOffset, 8, sGeometryHeader + " > Runtime Arrays");
WriteNumber(&Data.MH.GH.RuntimeArray2.nCount, 8, sGeometryHeader + " > Runtime Arrays");
WriteNumber(&Data.MH.GH.RuntimeArray2.nCount2, 8, sGeometryHeader + " > Runtime Arrays");
// Reference count
WriteNumber(&Data.MH.GH.nRefCount, 8, sGeometryHeader + " > Reference Count");
// Model type
WriteNumber(&Data.MH.GH.nModelType, 7, sGeometryHeader + " > Type");
// Padding (3 bytes)
WriteNumber(&Data.MH.GH.nPadding[0], 11, sGeometryHeader + " > Padding");
WriteNumber(&Data.MH.GH.nPadding[1], 11, sGeometryHeader + " > Padding");
WriteNumber(&Data.MH.GH.nPadding[2], 11, sGeometryHeader + " > Padding");
// Mark the end of geo header
MarkDataBorder(nPosition - 1);
/// Model header
std::string sModelHeader = "Model Header";
// Classification
WriteNumber(&Data.MH.nClassification, 7, sModelHeader + " > Classification");
// "Sub-classification" (not understood)
WriteNumber(&Data.MH.nSubclassification, 10, sModelHeader + " > Unknown1");
// Empty byte (can be used for SG presence marking)
unsigned char nModelUnknown = bWriteSmoothing ? 1 : Data.MH.nUnknown;
WriteNumber(&nModelUnknown, 8, sModelHeader + " > Unknown1");
// Affected By Fog
WriteNumber(&Data.MH.nAffectedByFog, 7, sModelHeader + " > Affected By Fog");
// Child model count
WriteNumber(&Data.MH.nChildModelCount, 8, sModelHeader + " > Number of Child Models");
// Animation ArrayHead
unsigned int nAnimationCountToWrite = CheckedUIntCount(Data.MH.Animations.size(), "model animation count");
unsigned PHnOffsetToAnimationArray = WriteBytes(placeholder, 4, 6, sModelHeader + " > Offset to Animation Array"); // Write placeholder offset
WriteNumber(&nAnimationCountToWrite, 1, sModelHeader + " > Number of Animations"); // Write count1
WriteNumber(&nAnimationCountToWrite, 1, sModelHeader + " > Number of Animations"); // Write count2
// Supermodel Reference
WriteNumber(&Data.MH.nSupermodelReference, 11, sModelHeader + " > Supermodel Reference");
// BB min and max, radius, scale
WriteFloat(&Data.MH.vBBmin.fX, 2, sModelHeader + " > Bounding Box Min");
WriteFloat(&Data.MH.vBBmin.fY, 2, sModelHeader + " > Bounding Box Min");
WriteFloat(&Data.MH.vBBmin.fZ, 2, sModelHeader + " > Bounding Box Min");
WriteFloat(&Data.MH.vBBmax.fX, 2, sModelHeader + " > Bounding Box Max");
WriteFloat(&Data.MH.vBBmax.fY, 2, sModelHeader + " > Bounding Box Max");
WriteFloat(&Data.MH.vBBmax.fZ, 2, sModelHeader + " > Bounding Box Max");
WriteFloat(&Data.MH.fRadius, 2, sModelHeader + " > Radius");
WriteFloat(&Data.MH.fScale, 2, sModelHeader + " > Animation Scale");
// Supermodel name
WriteString(&Data.MH.cSupermodelName, 32, 3, sModelHeader + " > Supermodel Name");
// Offset to head root node
unsigned PHnOffsetToHeadRootNode = WriteBytes(placeholder, 4, 6, sModelHeader + " > Offset to Head Root");
// Padding (4 bytes)
WriteNumber(&Data.MH.nPadding, 8, sModelHeader + " > Padding");
// Mdx size
unsigned PHnMdxLength2 = WriteBytes(placeholder, 4, 1, sModelHeader + " > MDX File Size");
// Mdx offset
WriteNumber(&Data.MH.nOffsetIntoMdx, 8, sModelHeader + " > MDX Data Offset");
// Name ArrayHead
unsigned int nNameCountToWrite = CheckedUIntCount(Data.MH.Names.size(), "model name count");
unsigned PHnOffsetToNameArray = WriteBytes(placeholder, 4, 6, sModelHeader + " > Offset to Name Array");
WriteNumber(&nNameCountToWrite, 1, sModelHeader + " > Number of Names");
WriteNumber(&nNameCountToWrite, 1, sModelHeader + " > Number of Names");
// Mark the end of model header
MarkDataBorder(nPosition - 1);
/// Create Name array
std::string sNameArrayPointers = "Name Array > Pointers > Pointer ";
std::string sNameArrayStrings = "Name Array > Strings > \"";
// Record the offset of the name array
unsigned int nNameArrayOffsetToWrite = Data.MH.Names.empty() ? 0u : nPosition - 12;
WriteNumber(&nNameArrayOffsetToWrite, 0, "", &PHnOffsetToNameArray);
std::vector<unsigned> PHnOffsetToName;
for(unsigned c = 0; c < Data.MH.Names.size(); c++){
// Write placeholder
PHnOffsetToName.push_back(WriteBytes(placeholder, 4, 6, sNameArrayPointers + std::to_string(c)));
MarkDataBorder(nPosition - 1);
}
for(unsigned c = 0; c < Data.MH.Names.size(); c++){
// Write offset to placeholder
unsigned int nNameOffsetToWrite = nPosition - 12;
WriteNumber(&nNameOffsetToWrite, 0, "", &PHnOffsetToName.at(c));
// Write name
WriteString(&Data.MH.Names[c].sName, 0, 3, sNameArrayStrings + std::string(Data.MH.Names[c].sName.c_str()) + "\"");
MarkDataBorder(nPosition - 1);
}
/// Create Animation array
vAnimationWriteOffsets.assign(Data.MH.Animations.size(), 0u);
// Write offset to placeholder
unsigned int nAnimationArrayOffsetToWrite = Data.MH.Animations.empty() ? 0u : nPosition - 12;
WriteNumber(&nAnimationArrayOffsetToWrite, 0, "", &PHnOffsetToAnimationArray);
std::vector<unsigned> pnOffsetsToAnimation;
for(unsigned c = 0; c < Data.MH.Animations.size(); c++){
std::string sAnimationPointer = "Animations > Pointers > Pointer" + std::to_string(c);
// Write placeholder
pnOffsetsToAnimation.push_back(WriteBytes(placeholder, 4, 6, sAnimationPointer));
MarkDataBorder(nPosition - 1);
}
for(unsigned c = 0; c < Data.MH.Animations.size(); c++){
/// This is where we fill EVERYTHING about the animation
Animation & anim = Data.MH.Animations[c];
if(anim.ArrayOfNodes.empty()){
throw mdlexception("Cannot write animation '" + anim.sName + "': animation contains no nodes.");
}
ValidateUniqueNodeNameIndices(anim.ArrayOfNodes, Data.MH.Names.size(), "Animation '" + anim.sName + "'");
ScopedValueRestore<ArrayHead> restoreEventArray(anim.EventArray);
ScopedValueRestore<unsigned int> restoreAnimationOffset(anim.nOffset);
ScopedValueRestore<unsigned int> restoreRootAnimationOffset(anim.nOffsetToRootAnimationNode);
std::string sAnimation = "Animations > " + std::string(anim.sName.c_str()) + " > ";
std::string sAnimationGeometryHeader = sAnimation + "Geometry Header";
// Write offset to placeholder
unsigned int nAnimationOffsetToWrite = nPosition - 12;
RememberAnimationWriteOffset(c, nAnimationOffsetToWrite);
WriteNumber(&nAnimationOffsetToWrite, 0, "", &pnOffsetsToAnimation[c]);
// Write function pointers. Preserve binary-derived values exposed by ASCII;
// synthesize defaults for author-authored ASCII that did not specify them.
unsigned int nAnimFunctionPointer0 = anim.nFunctionPointer0 != 0 ? anim.nFunctionPointer0 : FunctionPointer1(FN_PTR_ANIM);
unsigned int nAnimFunctionPointer1 = anim.nFunctionPointer1 != 0 ? anim.nFunctionPointer1 : FunctionPointer2(FN_PTR_ANIM);
WriteNumber(&nAnimFunctionPointer0, 9, sAnimationGeometryHeader + " > Function Pointers");
WriteNumber(&nAnimFunctionPointer1, 9, sAnimationGeometryHeader + " > Function Pointers");
// Animation name
WriteString(&anim.sName, 32, 3, sAnimationGeometryHeader + " > Name");
// Offset to root node
unsigned PHnOffsetToFirstNode = WriteBytes(placeholder, 4, 6, sAnimationGeometryHeader + " > Offset to Root Node");
// Number of nodes (total possible = number of names). Preserve explicit
// ASCII value when supplied; default to the current name count otherwise,
// but refuse to under-report the local animation node table.
unsigned int nAnimationNumberOfNames = AnimationNodeCountForWrite(anim, "Animation '" + anim.sName + "'", Data.MH.Names.size());
WriteNumber(&nAnimationNumberOfNames, 1, sAnimationGeometryHeader + " > Number of Nodes");
// Empty runtime arrays
WriteNumber(&anim.RuntimeArray1.nOffset, 8, sAnimationGeometryHeader + " > Runtime Arrays");
WriteNumber(&anim.RuntimeArray1.nCount, 8, sAnimationGeometryHeader + " > Runtime Arrays");
WriteNumber(&anim.RuntimeArray1.nCount2, 8, sAnimationGeometryHeader + " > Runtime Arrays");
WriteNumber(&anim.RuntimeArray2.nOffset, 8, sAnimationGeometryHeader + " > Runtime Arrays");
WriteNumber(&anim.RuntimeArray2.nCount, 8, sAnimationGeometryHeader + " > Runtime Arrays");
WriteNumber(&anim.RuntimeArray2.nCount2, 8, sAnimationGeometryHeader + " > Runtime Arrays");