-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathniflib.cpp
More file actions
1445 lines (1225 loc) · 48.2 KB
/
Copy pathniflib.cpp
File metadata and controls
1445 lines (1225 loc) · 48.2 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
/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
//#define DEBUG // this will produce lots of output
//#define PRINT_OBJECT_NAMES
//#define PRINT_OBJECT_CONTENTS
//#define DEBUG_LINK_PHASE
//#define DEBUG_HEADER_FOOTER
#include "../include/niflib.h"
#include "../include/NIF_IO.h"
#include "../include/ObjectRegistry.h"
#include "../include/kfm.h"
#include "../include/obj/NiObject.h"
#include "../include/obj/NiNode.h"
#include "../include/obj/NiAVObject.h"
#include "../include/obj/NiTextKeyExtraData.h"
#include "../include/obj/NiSequenceStreamHelper.h"
#include "../include/obj/NiControllerManager.h"
#include "../include/obj/NiControllerSequence.h"
#include "../include/obj/NiStringPalette.h"
#include "../include/obj/NiSkinPartition.h"
#include "../include/obj/NiTimeController.h"
#include "../include/obj/NiSingleInterpController.h"
#include "../include/obj/NiInterpolator.h"
#include "../include/obj/NiKeyframeController.h"
#include "../include/obj/NiKeyframeData.h"
#include "../include/obj/NiTransformInterpolator.h"
#include "../include/obj/NiTransformController.h"
#include "../include/obj/NiTransformData.h"
#include "../include/obj/NiMultiTargetTransformController.h"
#include "../include/obj/NiStringExtraData.h"
#include "../include/obj/NiExtraData.h"
#include "../include/obj/bhkConstraint.h"
#include "../include/gen/Header.h"
#include "../include/gen/Footer.h"
namespace Niflib {
//Object Registration
bool g_objects_registered = false;
void RegisterObjects();
//Utility Functions
bool BlockChildBeforeParent( NiObject * root );
void EnumerateObjects( NiObject * root, map<Type*,unsigned int> & type_map, map<NiObjectRef, unsigned int> & link_map );
NiObjectRef FindRoot( vector<NiObjectRef> const & objects );
NiObjectRef GetObjectByType( NiObject * root, const Type & type );
/*!
* Helper function to split off animation from a nif tree. If no animation groups are defined, then both xnif_root and xkf_root will be NULL.
* \param root_object The root object of the full tree.
* \param xnif_root The root object of the tree without animation.
* \param xkf_roots The root objects of the animation trees.
* \param kfm The KFM structure (if required by style).
* \param kf_type What type of keyframe tree to write (Morrowind style, DAoC style, ...).
* \param info A NifInfo structure that contains information such as the version of the NIF file to create.
*/
static void SplitNifTree( NiObject * root_object, NiObjectRef& xnif_root, list<NiObjectRef> & xkf_roots, Kfm & kfm, int kf_type, const NifInfo & info );
//--Function Bodies--//
NiObjectRef ReadNifTree( istream & in, list<NiObjectRef> & missing_link_stack, NifInfo * info ) {
vector<NiObjectRef> objects = ReadNifList( in, missing_link_stack, info );
return FindRoot( objects );
}
NiObjectRef ReadNifTree( string const & file_name, NifInfo * info ) {
//Read object list
vector<NiObjectRef> objects = ReadNifList( file_name, info );
return FindRoot( objects );
}
NiObjectRef ReadNifTree( istream & in, NifInfo * info ) {
//Read object list
vector<NiObjectRef> objects = ReadNifList( in, info );
return FindRoot( objects );
}
NiObjectRef FindRoot( vector<NiObjectRef> const & objects ) {
//--Look for a NiNode that has no parents--//
//Find the first NiObjectNET derived object
NiAVObjectRef root;
for (unsigned int i = 0; i < objects.size(); ++i) {
root = DynamicCast<NiAVObject>(objects[i]);
if ( root != NULL ) {
break;
}
}
//Make sure a node was found, if not return first node
if ( root == NULL )
return objects[0];
//Move up the chain to the root node
while ( root->GetParent() != NULL ) {
root = StaticCast<NiAVObject>(root->GetParent());
}
return StaticCast<NiObject>(root);
}
unsigned int GetNifVersion( string const & file_name ) {
//--Open File--//
ifstream in( file_name.c_str(), ifstream::binary );
//--Read Header String--//
HeaderString header;
NifInfo info;
NifStream( header, in, info );
return info.version;
}
NifInfo ReadHeaderInfo( string const & file_name ) {
//--Open File--//
ifstream in( file_name.c_str(), ifstream::binary );
//--Read Header Info--//
Header nif_header;
NifInfo info;
info = nif_header.Read(in);
return info;
}
Header ReadHeader( string const & file_name ) {
ifstream in( file_name.c_str(), ifstream::binary );
//--Read Header Info--//
Header nif_header;
nif_header.Read(in);
return nif_header;
}
vector<NiObjectRef> ReadNifList( string const & file_name, NifInfo * info ) {
//--Open File--//
ifstream in( file_name.c_str(), ifstream::binary );
vector<NiObjectRef> ret = ReadNifList( in, info );
in.close();
return ret;
}
vector<NiObjectRef> ReadNifList( istream & in, NifInfo * info ) {
list<NiObjectRef> missing_link_stack;
return ReadNifList(in, missing_link_stack, info);
}
vector<NiObjectRef> ReadNifList( istream & in, list<NiObjectRef> & missing_link_stack, NifInfo * info ) {
//Ensure that objects are registered
if ( g_objects_registered == false ) {
g_objects_registered = true;
RegisterObjects();
}
//--Read Header--//
Header header;
hdrInfo hinfo(&header);
// set the header pointer in the stream
in >> hinfo;
//Create a new NifInfo if one isn't given.
bool delete_info = false;
if ( info == NULL ) {
info = new NifInfo();
delete_info = true;
}
//Read header.
*info = header.Read( in );
//If NifInfo structure is provided, fill it with info from header
info->version = header.version;
info->userVersion = header.userVersion;
info->userVersion2 = header.userVersion2;
info->endian = EndianType(header.endianType);
info->creator = header.exportInfo.creator.str;
info->exportInfo1 = header.exportInfo.exportInfo1.str;
info->exportInfo2 = header.exportInfo.exportInfo2.str;
#ifdef DEBUG_HEADER_FOOTER
//Print debug output for header
cout << header.asString();
#endif
#ifdef PRINT_OBJECT_NAMES
cout << endl << "Reading Objects:";
#endif
//--Read Objects--//
size_t numObjects = header.numBlocks;
map<unsigned,NiObjectRef> objects; //Map to hold objects by number
vector<NiObjectRef> obj_list; //Vector to hold links in the order they were created.
list<unsigned int> link_stack; //List to add link values to as they're read in from the file
string objectType;
stringstream errStream;
std::streampos headerpos = in.tellg();
std::streampos nextobjpos = headerpos;
//Loop through all objects in the file
unsigned int i = 0;
NiObjectRef new_obj;
while (true) {
// Check if the size information matches in version 20.3 and greater
if ( header.version >= VER_20_3_0_3 ) {
if (nextobjpos != in.tellg()) {
// incorrect positioning seek to expected location
in.seekg(nextobjpos);
}
// update next location
nextobjpos += header.blockSize[i];
}
//Check for EOF
if (in.eof() ) {
errStream << "End of file reached prematurely. This NIF may be corrupt or improperly supported." << endl;
if ( new_obj != NULL ) {
errStream << "Last successfuly read object was: " << endl;
errStream << "====[ " << "Object " << i - 1 << " | " << new_obj->GetType().GetTypeName() << " ]====" << endl;
errStream << new_obj->asString();
} else {
errStream << "No objects were read successfully." << endl;
}
throw runtime_error( errStream.str() );
}
// Starting position of block in stream
std::streampos startobjpos = in.tellg();
//There are two main ways to read objects
//One before version 5.0.0.1 and one after
if ( header.version >= 0x05000001 ) {
//From version 5.0.0.1 to version 10.0.1.106 there is a zero byte at the begining of each object
if ( header.version <= VER_10_1_0_106 ) {
unsigned int checkValue = ReadUInt( in );
if ( checkValue != 0 ) {
//Throw an exception if it's not zero
errStream << "Read failue - Bad object position. Invalid check value: " << checkValue << endl;
if ( new_obj != NULL ) {
errStream << "Last successfuly read object was: " << endl;
errStream << "====[ " << "Object " << i - 1 << " | " << new_obj->GetType().GetTypeName() << " ]====" << endl;
errStream << new_obj->asString();
} else {
errStream << "No objects were read successfully." << endl;
}
throw runtime_error( errStream.str() );
}
}
// Find which NIF object type this is by using the header arrays
objectType = header.blockTypes[ header.blockTypeIndex[i] ];
#ifdef PRINT_OBJECT_NAMES
cout << endl << i << ": " << objectType;
#endif
} else {
// Find which object type this is by reading the string at this location
unsigned int objectTypeLength = ReadUInt( in );
if (objectTypeLength > 30 || objectTypeLength < 6) {
errStream << "Read failue - Bad object position. Invalid Type Name Length: " << objectTypeLength << endl;
if ( new_obj != NULL ) {
errStream << "Last successfuly read object was: " << endl;
errStream << "====[ " << "Object " << i - 1 << " | " << new_obj->GetType().GetTypeName() << " ]====" << endl;
errStream << new_obj->asString();
} else {
errStream << "No objects were read successfully." << endl;
}
throw runtime_error( errStream.str() );
}
char* charobjectType = new char[objectTypeLength + 1];
in.read( charobjectType, objectTypeLength );
charobjectType[objectTypeLength] = 0;
objectType = string(charobjectType);
delete [] charobjectType;
#ifdef PRINT_OBJECT_NAMES
cout << endl << i << ": " << objectType;
#endif
if ( header.version < VER_3_3_0_13 ) {
//There can be special commands instead of object names
//in these versions
if ( objectType == "Top Level Object" ) {
//Just continue on to the next object
continue;
}
if ( objectType == "End Of File" ) {
//File is finished
break;
}
}
}
//Create object of the type that was found
new_obj = ObjectRegistry::CreateObject(objectType);
//Check for an unknown object type
if ( new_obj == NULL ) {
errStream << "Unknown object type encountered during file read: " << objectType << endl;
if ( new_obj != NULL ) {
errStream << "Last successfully read object was: " << endl;
errStream << "====[ " << "Object " << i - 1 << " | " << new_obj->GetType().GetTypeName() << " ]====" << endl;
errStream << new_obj->asString();
} else {
errStream << "No objects were read successfully." << endl;
}
throw runtime_error( errStream.str() );
}
unsigned int index;
if ( header.version < VER_3_3_0_13 ) {
//These old versions have a pointer value after the name
//which is used as the index
index = ReadUInt(in);
} else {
//These newer verisons use their position in the file as their index
index = i;
}
//Read new object
new_obj->Read( in, link_stack, *info );
//Add object to map
objects[index] = new_obj;
//Add object to list
obj_list.push_back(new_obj);
//Store block number
new_obj->internal_block_number = index;
// Ending position of block in stream
std::streampos endobjpos = in.tellg();
// Check if the size information matches
if ( header.version >= VER_20_3_0_3 ) {
std::streamsize calcobjsize = endobjpos - startobjpos;
unsigned int objsize = header.blockSize[i];
if (calcobjsize != objsize) {
errStream << "Object size mismatch occurred during file read:" << endl;
errStream << "====[ " << "Object " << i << " | " << objectType << " ]====" << endl;
errStream << " Start: " << startobjpos << " Expected Size: " << objsize << " Read Size: " << calcobjsize << endl;
errStream << endl;
}
}
#ifdef PRINT_OBJECT_CONTENTS
cout << endl << new_obj->asString() << endl;
#endif
if ( header.version >= VER_3_3_0_13 ) {
//We know the number of objects, so increment the count
//and break if we've finished
++i;
if ( i >= numObjects ) {
break;
}
}
}
//--Read Footer--//
Footer footer;
footer.Read( in, link_stack, *info );
#ifdef DEBUG_HEADER_FOOTER
//Print footer debug output
footer.asString();
#endif
// Check for accumulated warnings
if (errStream.tellp() > 0) {
throw runtime_error( errStream.str() );
}
#ifdef DEBUG_LINK_PHASE
cout << "Link Stack:" << endl;
list<unsigned int>::iterator it;
for ( it = link_stack.begin(); it != link_stack.end(); ++it ) {
cout << *it << endl;
}
cout << "Fixing Links:" << endl;
#endif
//--Now that all objects are read, go back and fix the links--//
for ( unsigned int i = 0; i < obj_list.size(); ++i ) {
#ifdef DEBUG_LINK_PHASE
cout << " " << i << ": " << obj_list[i] << endl;
#endif
//Fix links & other pre-processing
obj_list[i]->FixLinks( objects, link_stack, missing_link_stack, *info );
}
//delete info if it was dynamically allocated
if ( delete_info ) {
delete info;
}
// clear the header pointer in the stream. Should be in try/catch block
hdrInfo hinfo2(NULL);
in >> hinfo2;
//Return completed object list
return obj_list;
}
NiObjectRef _ResolveMissingLinkStackHelper(NiObject *root, NiObject *obj) {
// search by name
NiNodeRef rootnode = DynamicCast<NiNode>(root);
NiNodeRef objnode = DynamicCast<NiNode>(obj);
if (rootnode != NULL && objnode != NULL) {
if (!(rootnode->GetName().empty()) && rootnode->GetName() == objnode->GetName()) {
return StaticCast<NiObject>(rootnode);
}
list<NiObjectRef> children = root->GetRefs();
for (list<NiObjectRef>::iterator child = children.begin(); child != children.end(); ++child) {
NiObjectRef result = _ResolveMissingLinkStackHelper(*child, obj);
if (result != NULL) {
return result;
}
}
}
// nothing found
return NiObjectRef();
}
list<NiObjectRef> ResolveMissingLinkStack(
NiObject *root,
const list<NiObject *> & missing_link_stack)
{
list<NiObjectRef> result;
for (list<NiObject *>::const_iterator obj = missing_link_stack.begin(); obj != missing_link_stack.end(); ++obj) {
result.push_back(_ResolveMissingLinkStackHelper(root, *obj));
}
return result;
}
// Writes a valid Nif File given an ostream, a list to the root objects of a file tree
// (missing_link_stack stores a stack of links which are referred to but which
// are not inside the tree rooted by roots)
void WriteNifTree( ostream & out, list<NiObjectRef> const & roots, list<NiObject *> & missing_link_stack, const NifInfo & info) {
//Enumerate all objects in tree
map<Type*,unsigned int> type_map;
map<NiObjectRef, unsigned int> link_map;
for (list<NiObjectRef>::const_iterator it = roots.begin(); it != roots.end(); ++it) {
EnumerateObjects( (*it), type_map, link_map );
}
//Build vectors for reverse look-up
vector<NiObjectRef> objects(link_map.size());
for ( map<NiObjectRef, unsigned int>::iterator it = link_map.begin(); it != link_map.end(); ++it ) {
objects[it->second] = it->first;
}
vector<const Type*> types(type_map.size());
for ( map<Type*, unsigned int>::iterator it = type_map.begin(); it != type_map.end(); ++it ) {
types[it->second] = it->first;
}
unsigned int version = info.version;
//--Write Header--//
Header header;
header.version = info.version;
header.userVersion = info.userVersion;
header.userVersion2 = info.userVersion2;
header.endianType = info.endian;
header.exportInfo.creator.str = info.creator;
header.exportInfo.exportInfo1.str = info.exportInfo1;
header.exportInfo.exportInfo2.str = info.exportInfo2;
header.copyright[0].line = "Numerical Design Limited, Chapel Hill, NC 27514";
header.copyright[1].line = "Copyright (c) 1996-2000";
header.copyright[2].line = "All Rights Reserved";
// set the header pointer in the stream
out << hdrInfo(&header);
//Set Type Names
header.blockTypes.resize( types.size() );
for ( unsigned int i = 0; i < types.size(); ++i ) {
header.blockTypes[i] = types[i]->GetTypeName();
}
//Set type number of each object
header.blockTypeIndex.resize( objects.size() );
for ( unsigned int i = 0; i < objects.size(); ++i ) {
header.blockTypeIndex[i] = type_map[(Type*)&(objects[i]->GetType())];
}
// Set object sizes and accumulate string types
if (version >= VER_20_1_0_3)
{
// Zero string information
header.maxStringLength = 0;
header.numStrings = 0;
header.strings.clear();
NifSizeStream ostr;
ostr << hdrInfo(&header);
header.blockSize.resize( objects.size() );
for ( unsigned int i = 0; i < objects.size(); ++i ) {
ostr.reset();
objects[i]->Write( ostr, link_map, missing_link_stack, info );
header.blockSize[i] = (unsigned int) ostr.tellp();
}
header.numStrings = header.strings.size();
}
//Write header to file
header.Write( out, info );
#ifdef PRINT_OBJECT_NAMES
cout << endl << "Writing Objects:";
#endif
//--Write Objects--//
for (unsigned int i = 0; i < objects.size(); ++i) {
#ifdef PRINT_OBJECT_NAMES
cout << endl << i << ": " << objects[i]->GetType().GetTypeName();
#endif
if ( version < VER_3_3_0_13 ) {
//Check if this object is one of the roots.
for ( list<NiObjectRef>::const_iterator it = roots.begin(); it != roots.end(); ++it ) {
if ( objects[i] == *it ) {
//Write "Top Level Object"
WriteString( "Top Level Object", out );
break;
}
}
//Write Object Type
WriteString( objects[i]->GetType().GetTypeName() , out );
//Write pointer number of object
WritePtr32( &(*objects[i]), out );
} else if (version < 0x05000001) {
//Write Object Type
WriteString( objects[i]->GetType().GetTypeName() , out );
} else if (version >= 0x05000001 && version <= VER_10_1_0_106 ) {
WriteUInt( 0, out );
}
objects[i]->Write( out, link_map, missing_link_stack, info );
}
//--Write Footer--//
if ( version < VER_3_3_0_13 ) {
//Write "End Of File"
WriteString( "End Of File", out );
} else {
Footer footer;
footer.numRoots = 0;
if (roots.size() == 1) {
const NiObjectRef& root = roots.front();
if (root->IsDerivedType(NiControllerSequence::TYPE)) {
// KF animation files allow for multiple roots of type NiControllerSequence
for ( unsigned int i = 0; i < objects.size(); ++i ) {
if (objects[i]->IsDerivedType(NiControllerSequence::TYPE)) {
footer.roots.push_back(objects[i]);
}
}
} else { // just assume its correctly passed in
footer.numRoots = 1;
footer.roots.resize(1);
footer.roots[0] = root;
}
} else {
footer.numRoots = roots.size();
footer.roots.insert(footer.roots.end(), roots.begin(), roots.end());
}
footer.Write( out, link_map, missing_link_stack, info );
}
// clear the header pointer in the stream. Should be in try/catch block
out << hdrInfo(NULL);
}
void WriteNifTree( ostream & out, NiObject *root, list<NiObject *> & missing_link_stack, const NifInfo & info) {
list<NiObjectRef> roots;
roots.push_back(root);
WriteNifTree( out, roots, missing_link_stack, info );
}
void WriteNifTree( ostream & out, list<NiObjectRef> const & roots, const NifInfo & info) {
list<NiObject *> missing_link_stack;
WriteNifTree( out, roots, missing_link_stack, info );
}
// Writes a valid Nif File given a file name, a pointer to the root object of a file tree
void WriteNifTree( string const & file_name, NiObject * root, const NifInfo & info ) {
//Open output file
ofstream out( file_name.c_str(), ofstream::binary );
list<NiObjectRef> roots;
roots.push_back(root);
WriteNifTree( out, roots, info );
//Close file
out.close();
}
void WriteNifTree( string const & file_name, list<NiObjectRef> const & roots, const NifInfo & info ) {
//Open output file
ofstream out( file_name.c_str(), ofstream::binary );
WriteNifTree( out, roots, info );
//Close file
out.close();
}
// Writes a valid Nif File given an ostream, a pointer to the root object of a file tree
void WriteNifTree( ostream & out, NiObject * root, const NifInfo & info ) {
list<NiObjectRef> roots;
roots.push_back(root);
WriteNifTree( out, roots, info );
}
// Determine whether block comes before its parent or not, depending on the block type.
// return: 'True' if child should come first, 'False' otherwise.
bool BlockChildBeforeParent( NiObject * root ) {
Type *t = (Type*)&(root->GetType());
return (t->IsDerivedType(bhkRefObject::TYPE) && !t->IsDerivedType(bhkConstraint::TYPE));
}
// This is a helper function for write to set up the list of all blocks,
// the block index map, and the block type map.
void EnumerateObjects( NiObject * root, map<Type*,unsigned int> & type_map, map<NiObjectRef, unsigned int> & link_map ) {
// Ensure that this object has not already been visited
if ( link_map.find( root ) != link_map.end() ) {
//This object has already been visited. Return.
return;
}
list<NiObjectRef> links = root->GetRefs();
Type *t = (Type*)&(root->GetType());
// special case: add bhkConstraint entities before bhkConstraint
// (these are actually links, not refs)
if ( t->IsDerivedType(bhkConstraint::TYPE) ) {
vector< bhkEntity * > entities = ((bhkConstraint *)root)->GetEntities();
for ( vector< bhkEntity * >::iterator it = entities.begin(); it != entities.end(); ++it ) {
if ( *it != NULL ) {
EnumerateObjects( (NiObject*)(*it), type_map, link_map );
}
}
}
// Call this function on all links of this object
// add children that come before the block
for ( list<NiObjectRef>::iterator it = links.begin(); it != links.end(); ++it ) {
if ( *it != NULL && BlockChildBeforeParent(*it) ) {
EnumerateObjects( *it, type_map, link_map );
}
}
// Add this object type to the map if it isn't there already
// TODO: add support for NiDataStreams
if ( type_map.find(t) == type_map.end() ) {
//The type has not yet been registered, so register it
unsigned int n = type_map.size();
type_map[t] = n;
}
// add the block
unsigned int n = link_map.size();
link_map[root] = n;
// add children that come after the block
for ( list<NiObjectRef>::iterator it = links.begin(); it != links.end(); ++it ) {
if ( *it != NULL && !BlockChildBeforeParent(*it) ) {
EnumerateObjects( *it, type_map, link_map );
}
}
}
//TODO: Should this be returning an object of a derived type too?
// Searches for the first object in the hierarchy of type.
NiObjectRef GetObjectByType( NiObject * root, const Type & type ) {
if ( root->IsSameType( type ) ) {
return root;
}
list<NiObjectRef> links = root->GetRefs();
for (list <NiObjectRef>::iterator it = links.begin(); it != links.end(); ++it) {
// Can no longer guarantee that some objects won't be visited twice. Oh well.
NiObjectRef result = GetObjectByType( *it, type );
if ( result != NULL ) {
return result;
}
};
return NULL; // return null reference
};
//TODO: Should this be returning all objects of a derived type too?
// Returns all in the in the tree of type.
list<NiObjectRef> GetAllObjectsByType( NiObject * root, const Type & type ) {
list<NiObjectRef> result;
if ( root->IsSameType(type) ) {
result.push_back( root );
}
list<NiObjectRef> links = root->GetRefs();
for (list<NiObjectRef>::iterator it = links.begin(); it != links.end(); ++it ) {
// Can no longer guarantee that some objects won't be visited twice. Oh well.
list<NiObjectRef> childresult = GetAllObjectsByType( *it, type );
result.merge( childresult );
};
return result;
};
// Create a valid file name
static std::string CreateFileName(std::string name) {
std::string retname = name;
std::string::size_type off = 0;
std::string::size_type pos = 0;
for (;;) {
pos = retname.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_^$~!#%&-{}()@'` ", off);
if (pos == std::string::npos)
break;
retname[pos] = '_';
off = pos;
}
return retname;
}
//TODO: This was written by Amorilia. Figure out how to fix it.
static void SplitNifTree( NiObject* root_object, NiObjectRef& xnif_root, list<NiObjectRef> & xkf_roots, Kfm & kfm, int kf_type, const NifInfo & info ) {
// Do we have animation groups (a NiTextKeyExtraData object)?
// If so, create XNif and XKf trees.
NiObjectRef txtkey = GetObjectByType( root_object, NiTextKeyExtraData::TYPE );
NiTextKeyExtraDataRef txtkey_obj;
if ( txtkey != NULL ) {
txtkey_obj = DynamicCast<NiTextKeyExtraData>(txtkey);
}
if ( txtkey_obj != NULL ) {
if ( kf_type == KF_MW ) {
// Construct the XNif file...
xnif_root = CloneNifTree( root_object, info.version, info.userVersion );
// Now search and locate newer timeframe controllers and convert to keyframecontrollers
list<NiObjectRef> mgrs = GetAllObjectsByType( xnif_root, NiControllerManager::TYPE );
for ( list<NiObjectRef>::iterator it = mgrs.begin(); it != mgrs.end(); ++it) {
NiControllerManagerRef mgr = DynamicCast<NiControllerManager>(*it);
if ( mgr == NULL ) {
continue;
}
NiObjectNETRef target = mgr->GetTarget();
target->RemoveController( StaticCast<NiTimeController>(mgr) );
vector<NiControllerSequenceRef> seqs = mgr->GetControllerSequences();
for (vector<NiControllerSequenceRef>::iterator itr = seqs.begin(); itr != seqs.end(); ++itr) {
NiControllerSequenceRef seq = (*itr);
MergeNifTrees(DynamicCast<NiNode>(target), seq, info.version, info.userVersion );
}
}
// Now the XKf file...
// Create xkf root header.
NiSequenceStreamHelperRef xkf_stream_helper = new NiSequenceStreamHelper;
xkf_roots.push_back( StaticCast<NiObject>(xkf_stream_helper) );
// Append NiNodes with a NiKeyFrameController as NiStringExtraData objects.
list< pair< NiNodeRef, NiKeyframeControllerRef> > node_controllers;
list<NiObjectRef> nodes = GetAllObjectsByType( xnif_root, NiNode::TYPE );
for ( list<NiObjectRef>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
NiNodeRef node = DynamicCast<NiNode>(*it);
if ( node == NULL ) {
continue;
}
//Find the first NiKeyframeController in the controller list, if any
list<NiTimeControllerRef> controllers = node->GetControllers();
NiKeyframeControllerRef key_controller;
for ( list<NiTimeControllerRef>::iterator it = controllers.begin(); it != controllers.end(); ++it ) {
if ((*it)->IsDerivedType(NiKeyframeController::TYPE)) {
key_controller = StaticCast<NiKeyframeController>(*it);
} else if ((*it)->IsDerivedType(NiTransformController::TYPE)) {
NiTransformControllerRef trans = StaticCast<NiTransformController>(*it);
NiTransformInterpolatorRef interp = DynamicCast<NiTransformInterpolator>(trans->GetInterpolator());
if (interp != NULL) {
NiTransformDataRef transData = interp->GetData();
if (transData != NULL) {
NiKeyframeDataRef data = new NiKeyframeData();
data->SetRotateType( transData->GetRotateType() );
data->SetTranslateType( transData->GetTranslateType() );
data->SetScaleType( transData->GetScaleType() );
data->SetXRotateType( transData->GetXRotateType() );
data->SetYRotateType( transData->GetYRotateType() );
data->SetZRotateType( transData->GetZRotateType() );
data->SetTranslateKeys( transData->GetTranslateKeys() );
data->SetQuatRotateKeys( transData->GetQuatRotateKeys() );
data->SetScaleKeys( transData->GetScaleKeys() );
data->SetXRotateKeys( transData->GetXRotateKeys() );
data->SetYRotateKeys( transData->GetYRotateKeys() );
data->SetZRotateKeys( transData->GetZRotateKeys() );
key_controller = new NiKeyframeController();
key_controller->SetFlags( trans->GetFlags() );
key_controller->SetFrequency( trans->GetFrequency() );
key_controller->SetPhase( trans->GetPhase() );
key_controller->SetStartTime( trans->GetStartTime() );
key_controller->SetStopTime( trans->GetStopTime() );
key_controller->SetData( data );
break;
}
}
}
}
//If this node has a keyframe controller, put it in the list
if ( key_controller != NULL ) {
node_controllers.push_back( pair<NiNodeRef,NiKeyframeControllerRef>( node, key_controller ) );
}
}
for ( list< pair< NiNodeRef, NiKeyframeControllerRef> >::reverse_iterator it = node_controllers.rbegin(); it != node_controllers.rend(); ++it ) {
//Add string data
NiStringExtraDataRef nodextra = new NiStringExtraData;
nodextra->SetData( it->first->GetName() );
xkf_stream_helper->AddExtraData( StaticCast<NiExtraData>(nodextra), info.version );
NiKeyframeControllerRef controller = it->second;
(it->first)->RemoveController( StaticCast<NiTimeController>(controller) );
xkf_stream_helper->AddController( StaticCast<NiTimeController>(controller) );
}
// Add a copy of the NiTextKeyExtraData object to the XKf header.
NiTextKeyExtraDataRef xkf_txtkey_obj = new NiTextKeyExtraData;
xkf_stream_helper->AddExtraData( StaticCast<NiExtraData>(xkf_txtkey_obj), info.version );
xkf_txtkey_obj->SetKeys( txtkey_obj->GetKeys() );
} else if (kf_type == KF_CIV4) {
// Construct the Nif file without transform controllers ...
xnif_root = CloneNifTree( root_object, info.version, info.userVersion );
list<NiObjectRef> mgrs = GetAllObjectsByType( xnif_root, NiControllerManager::TYPE );
for ( list<NiObjectRef>::iterator it = mgrs.begin(); it != mgrs.end(); ++it) {
NiControllerManagerRef mgr = DynamicCast<NiControllerManager>(*it);
if ( mgr == NULL ) {
continue;
}
NiObjectNETRef target = mgr->GetTarget();
target->RemoveController( StaticCast<NiTimeController>(mgr) );
vector<NiControllerSequenceRef> seqs = mgr->GetControllerSequences();
for (vector<NiControllerSequenceRef>::iterator itr = seqs.begin(); itr != seqs.end(); ++itr) {
xkf_roots.push_back( StaticCast<NiObject>(*itr) );
}
mgr->ClearSequences();
}
} else if (kf_type == KF_FFVT3R) {
// Construct the Nif file without transform controllers ...
xnif_root = CloneNifTree( root_object, info.version, info.userVersion );
// Delete all NiMultiTargetTransformController
list<NiObjectRef> nodes = GetAllObjectsByType( xnif_root, NiMultiTargetTransformController::TYPE );
for ( list<NiObjectRef>::iterator it = nodes.begin(); it != nodes.end(); ++it) {
if ( NiMultiTargetTransformControllerRef ctrl = DynamicCast<NiMultiTargetTransformController>(*it) ) {
if (NiNodeRef target = DynamicCast<NiNode>(ctrl->GetTarget())) {
target->RemoveController(ctrl);
}
}
}
list<NiObjectRef> mgrs = GetAllObjectsByType( xnif_root, NiControllerManager::TYPE );
for ( list<NiObjectRef>::iterator it = mgrs.begin(); it != mgrs.end(); ++it) {
NiControllerManagerRef mgr = DynamicCast<NiControllerManager>(*it);
if ( mgr == NULL ) {
continue;
}
NiObjectNETRef target = mgr->GetTarget();
target->RemoveController( StaticCast<NiTimeController>(mgr) );
vector<NiControllerSequenceRef> seqs = mgr->GetControllerSequences();
for (vector<NiControllerSequenceRef>::iterator itr = seqs.begin(); itr != seqs.end(); ++itr) {
xkf_roots.push_back( StaticCast<NiObject>(*itr) );
}
mgr->ClearSequences();
}
} else {
throw runtime_error("KF splitting for the requested game is not yet implemented.");
}
} else {
// no animation groups: nothing to do
xnif_root = root_object;
};
}
//TODO: This was written by Amorilia. Figure out how to fix it.
void WriteFileGroup( string const & file_name, NiObject * root_object, const NifInfo & info, ExportOptions export_files, NifGame kf_type ) {
// Get base filename.
unsigned int file_name_slash = (unsigned int)(file_name.rfind("\\") + 1);
string file_name_path = file_name.substr(0, file_name_slash);
string file_name_base = file_name.substr(file_name_slash, file_name.length());
unsigned int file_name_dot = (unsigned int)(file_name_base.rfind("."));
file_name_base = file_name_base.substr(0, file_name_dot);
// Deal with the simple case first
if ( export_files == EXPORT_NIF )
WriteNifTree( file_name_path + file_name_base + ".nif", root_object, info ); // simply export the NIF file!
// Now consider all other cases
else if ( kf_type == KF_MW ) {
if ( export_files == EXPORT_NIF_KF ) {
// for Morrowind we must also write the full NIF file
WriteNifTree( file_name_path + file_name_base + ".nif", root_object, info ); // simply export the NIF file!
NiObjectRef xnif_root;
list<NiObjectRef> xkf_roots;
Kfm kfm; // dummy
SplitNifTree( root_object, xnif_root, xkf_roots, kfm, kf_type, info );
if ( xnif_root != NULL && !xkf_roots.empty()) {
WriteNifTree( file_name_path + "x" + file_name_base + ".nif", xnif_root, info );
WriteNifTree( file_name_path + "x" + file_name_base + ".kf", xkf_roots.front(), info );
};
} else
throw runtime_error("Invalid export option.");
} else if (kf_type == KF_CIV4) {
NiObjectRef xnif_root;
list<NiObjectRef> xkf_roots;
Kfm kfm; // dummy
SplitNifTree( root_object, xnif_root, xkf_roots, kfm, kf_type, info );
if ( export_files == EXPORT_NIF || export_files == EXPORT_NIF_KF || export_files == EXPORT_NIF_KF_MULTI ) {
WriteNifTree( file_name_path + file_name_base + ".nif", xnif_root, info );
}
if ( export_files == EXPORT_NIF_KF || export_files == EXPORT_KF ) {
WriteNifTree( file_name_path + file_name_base + ".kf", xkf_roots, info );
} else if ( export_files == EXPORT_NIF_KF_MULTI || export_files == EXPORT_KF_MULTI ) {
for ( list<NiObjectRef>::iterator it = xkf_roots.begin(); it != xkf_roots.end(); ++it ) {
NiControllerSequenceRef seq = DynamicCast<NiControllerSequence>(*it);
if (seq == NULL)
continue;
string path = file_name_path + file_name_base + "_" + CreateFileName(seq->GetTargetName()) + "_" + CreateFileName(seq->GetName()) + ".kf";
WriteNifTree( path, StaticCast<NiObject>(seq), info );
}
}
} else if (kf_type == KF_FFVT3R) {
NiObjectRef xnif_root;
list<NiObjectRef> xkf_roots;
Kfm kfm; // dummy
SplitNifTree( root_object, xnif_root, xkf_roots, kfm, kf_type, info );
if ( export_files == EXPORT_NIF || export_files == EXPORT_NIF_KF || export_files == EXPORT_NIF_KF_MULTI ) {
WriteNifTree( file_name_path + file_name_base + ".nif", xnif_root, info );
}
if ( export_files == EXPORT_NIF_KF || export_files == EXPORT_KF ) {
WriteNifTree( file_name_path + file_name_base + ".kf", xkf_roots, info );
} else if ( export_files == EXPORT_NIF_KF_MULTI || export_files == EXPORT_KF_MULTI ) {
for ( list<NiObjectRef>::iterator it = xkf_roots.begin(); it != xkf_roots.end(); ++it ) {
NiControllerSequenceRef seq = DynamicCast<NiControllerSequence>(*it);
if (seq == NULL)
continue;
string path = file_name_path + file_name_base + "_" + CreateFileName(seq->GetTargetName()) + "_" + CreateFileName(seq->GetName()) + ".kf";
WriteNifTree( path, StaticCast<NiObject>(seq), info );
}
}
} else
throw runtime_error("Not yet implemented.");
};
void MapNodeNames( map<string,NiNodeRef> & name_map, NiNode * par ) {
//Add the par node to the map, and then call this function for each of its children
name_map[par->GetName()] = par;
vector<NiAVObjectRef> links = par->GetChildren();
for (vector<NiAVObjectRef>::iterator it = links.begin(); it != links.end(); ++it) {
NiNodeRef child_node = DynamicCast<NiNode>(*it);
if ( child_node != NULL ) {
MapNodeNames( name_map, child_node );
};
};
}