forked from hitmen047/Source-PlusPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstudiobyteswap.cpp
3179 lines (2667 loc) · 109 KB
/
studiobyteswap.cpp
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 Valve Corporation, All rights reserved. ============//
//
// Purpose: Swaps the bytes in all file types generated by studiomdl
// (.vvd, .vtx, .mdl, .phy, .ani) so the files can be loaded
// on a big-endian machine, specifically the Xbox360. A new file is generated
// with an extra extension in the form of <filename>.360.<ext>
//
//=============================================================================//
#include "studio.h"
#include "optimize.h"
#include "phyfile.h"
#include "studiobyteswap.h"
#include "vphysics_interface.h"
#undef ALIGN4
#undef ALIGN16
#undef ALIGN32
#define ALIGN4( a ) a = (byte *)((int)((byte *)a + 3) & ~ 3)
#define ALIGN16( a ) a = (byte *)((int)((byte *)a + 15) & ~ 15)
#define ALIGN32( a ) a = (byte *)((int)((byte *)a + 31) & ~ 31)
#define ALIGN64( a ) a = (byte *)((int)((byte *)a + 63) & ~ 63)
// Fixup macros create variables that may not be referenced
#pragma warning( push )
#pragma warning( disable:4189 ) // local variable is initialized but not referenced
#pragma warning( disable:4366 ) // The result of the unary '&' operator may be unaligned
namespace StudioByteSwap
{
static bool g_bVerbose = true;
static bool g_bNativeSrc;
static CByteswap g_Swap;
static IPhysicsCollision *pCollision;
static CompressFunc_t g_pCompressFunc;
void ActivateByteSwapping( bool activate )
{
g_Swap.ActivateByteSwapping( activate );
SourceIsNative( IsPC() );
}
void SourceIsNative( bool bNative )
{
g_bNativeSrc = bNative;
}
void SetCollisionInterface( IPhysicsCollision *pPhysicsCollision )
{
pCollision = pPhysicsCollision;
}
void SetVerbose( bool bVerbose )
{
g_bVerbose = bVerbose;
}
//----------------------------------------------------------------------
// Helper to write a chunk of objects of the same type, and increment the buffer pointers.
//----------------------------------------------------------------------
template<class T> inline void WriteObjects( byte **pOutputBuffer, byte **pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, *pBaseData, sizeof(T) );
g_Swap.SwapFieldsToTargetEndian( &tempObject, &tempObject );
Q_memcpy( *pOutputBuffer, &tempObject, sizeof(T) );
*pOutputBuffer += sizeof(T);
*pBaseData += sizeof(T);
}
}
//----------------------------------------------------------------------
// Helper to write a chunk of objects of the same type, and increment the buffer pointers.
//----------------------------------------------------------------------
template<class T> inline void WriteObjects( T **pOutputBuffer, T **pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, *pBaseData, sizeof(T) );
g_Swap.SwapFieldsToTargetEndian( &tempObject, &tempObject );
Q_memcpy( *pOutputBuffer, &tempObject, sizeof(T) );
++*pOutputBuffer;
++*pBaseData;
}
}
//----------------------------------------------------------------------
// Helper to write a chunk of objects of the same type.
//----------------------------------------------------------------------
template<class T> inline void WriteObjects( byte *pOutputBuffer, byte *pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, pBaseData, sizeof(T) );
g_Swap.SwapFieldsToTargetEndian( &tempObject, &tempObject );
Q_memcpy( pOutputBuffer, &tempObject, sizeof(T) );
pOutputBuffer += sizeof(T);
pBaseData += sizeof(T);
}
}
//----------------------------------------------------------------------
// Helper to write a chunk of objects of the same type.
//----------------------------------------------------------------------
template<class T> inline void WriteObjects( T *pOutputBuffer, T *pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, pBaseData, sizeof(T) );
g_Swap.SwapFieldsToTargetEndian( &tempObject, &tempObject );
Q_memcpy( pOutputBuffer, &tempObject, sizeof(T) );
++pOutputBuffer;
++pBaseData;
}
}
//----------------------------------------------------------------------
// Helper to write a buffer of some integral type, and increment the buffer pointers.
//----------------------------------------------------------------------
template<class T> inline void WriteBuffer( byte **pOutputBuffer, byte **pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, *pBaseData, sizeof(T) );
g_Swap.SwapBufferToTargetEndian( &tempObject, &tempObject );
Q_memcpy( *pOutputBuffer, &tempObject, sizeof(T) );
*pOutputBuffer += sizeof(T);
*pBaseData += sizeof(T);
}
}
//----------------------------------------------------------------------
// Helper to write a buffer of some integral type
//----------------------------------------------------------------------
template<class T> inline void WriteBuffer( byte *pOutputBuffer, byte *pBaseData, int objectCount = 1 )
{
T tempObject;
for ( int i = 0; i < objectCount; ++i )
{
Q_memcpy( &tempObject, pBaseData, sizeof(T) );
g_Swap.SwapBufferToTargetEndian( &tempObject, &tempObject );
Q_memcpy( pOutputBuffer, &tempObject, sizeof(T) );
pOutputBuffer += sizeof(T);
pBaseData += sizeof(T);
}
}
//----------------------------------------------------------------------
// For getting values in the correct source/dest endian format
//----------------------------------------------------------------------
template< class T >
T SrcNative( T *idx )
{
T ret = *idx;
if ( !g_bNativeSrc )
{
g_Swap.SwapBuffer( &ret, idx );
}
return ret;
}
template< class T >
T DestNative( T *idx )
{
T ret = *idx;
if ( g_bNativeSrc )
{
g_Swap.SwapBuffer( &ret, idx );
}
return ret;
}
//----------------------------------------------------------------------
// Declares objects pointers for src/dest buffer
//----------------------------------------------------------------------
#define DECLARE_OBJECT_POINTERS( objPtr, base, type ) \
type* objPtr##Src = (type*)base##Src; \
type* objPtr##Dest = (type*)base##Dest; \
type* objPtr = objPtr##Src;
//----------------------------------------------------------------------
// Declares src/dest byte pointers and sets them to some index offset in the buffers.
//----------------------------------------------------------------------
#define DECLARE_INDEX_POINTERS( ptr, base, index ) \
byte *ptr##Src = (byte*)base##Src + SrcNative( &base##Src->index ); \
byte *ptr##Dest = (byte*)base##Dest + SrcNative( &base##Src->index );
//----------------------------------------------------------------------
// Declares src/dest byte pointers and sets them to some index offset in the buffers.
// If src pointer is misaligned, the fixup method is called.
//----------------------------------------------------------------------
#define DECLARE_INDEX_POINTERS_FIXUP( ptr, base, index ) \
byte *ptr##Src = (byte*)base##Src + SrcNative( &base##Src->index ); \
byte *ptr##Dest = (byte*)base##Dest + SrcNative( &base##Src->index ); \
FIXUP_OFFSETS( ptr, base, index )
//----------------------------------------------------------------------
// Same as DECLARE_OBJECT_POINTERS, but reuses existing type pointers.
//----------------------------------------------------------------------
#define SET_OBJECT_POINTERS( objPtr, base, type ) \
objPtr##Src = (type*)base##Src; \
objPtr##Dest = (type*)base##Dest; \
objPtr = objPtr##Src;
//----------------------------------------------------------------------
// Same as DECLARE_INDEX_POINTERS, but reuses existing byte pointers.
//----------------------------------------------------------------------
#define SET_INDEX_POINTERS( ptr, base, index ) \
ptr##Src = (byte*)base##Src + SrcNative( &base##Src->index ); \
ptr##Dest = (byte*)base##Dest + SrcNative( &base##Src->index );
//----------------------------------------------------------------------
// Same as DECLARE_INDEX_POINTERS, but reuses existing byte pointers.
// If src pointer is misaligned, the fixup method is called.
//----------------------------------------------------------------------
#define SET_INDEX_POINTERS_FIXUP( ptr, base, index ) \
ptr##Src = (byte*)base##Src + SrcNative( &base##Src->index ); \
ptr##Dest = (byte*)base##Dest + SrcNative( &base##Src->index ); \
FIXUP_OFFSETS( ptr, base, index )
//----------------------------------------------------------------------
// for() loop header, updates all three object pointers (src,dest,native)
//----------------------------------------------------------------------
#define ITERATE_BLOCK( objPtr, count ) \
for ( int objPtr##_idx = 0; objPtr##_idx < SrcNative( &count ); ++objPtr##_idx, ++objPtr, ++objPtr##Src, ++objPtr##Dest )
//----------------------------------------------------------------------
// Checks for misaligned source pointer, then calculates the necessary fixup,
// calls the fixup function, and sets the src pointer to the new position.
//----------------------------------------------------------------------
#define FIXUP_OFFSETS( ptr, base, index ) \
{ \
byte *ptr##Fixup = ptr##Src; \
ALIGN4( ptr##Fixup ); \
if ( ptr##Fixup != ptr##Src ) \
{ \
int nShiftBytes = ptr##Fixup - ptr##Src; \
if ( g_bVerbose ) \
Warning( "Shifting misaligned data block by %d bytes at " #base "->" #index "\n", nShiftBytes ); \
int prevBytes = (byte*)ptr##Src - (byte*)g_pDataSrcBase; \
Q_memmove( (byte*)ptr##Src + nShiftBytes, ptr##Src, fixedFileSize - prevBytes ); \
g_pFixPoint = ptr##Src; \
g_nFixupBytes = nShiftBytes; \
fixedFileSize += nShiftBytes; \
if ( fixedFileSize > fileSize + BYTESWAP_ALIGNMENT_PADDING ) \
{ \
Error( "Byteswap buffer overrun - increase BYTESWAP_ALIGNMENT_PADDING!\n" ); \
return 0; \
} \
g_pfnFileProcessFunc( pHdrSrc, UpdateSrcIndexFields ); \
g_pFixPoint = NULL; \
g_nFixupBytes = 0; \
ptr##Src = ptr##Fixup; \
} \
}
typedef void ( *datadescProcessFunc_t)( void *pBase, void *pData, typedescription_t *pFields );
typedef void ( *pfnFixupFunc_t )( void *pDestBase, datadescProcessFunc_t );
static pfnFixupFunc_t g_pfnFileProcessFunc;
static studiohdr_t *g_pHdr;
static const void *g_pDataSrcBase;
static void *g_pFixPoint;
static int g_nFixupBytes;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool UpdateIndex( void *pBase, int *indexMember )
{
bool bUpdateIndex = false;
int idx = *indexMember;
// Update the index fields
if ( pBase < g_pFixPoint )
{
if ( (byte*)pBase + idx >= g_pFixPoint )
{
bUpdateIndex = true;
}
}
else
{
if ( (byte*)pBase + idx < g_pFixPoint )
{
bUpdateIndex = true;
}
}
// Update the member offset by the global fixup
if ( bUpdateIndex && *indexMember )
{
*indexMember = idx + g_nFixupBytes * Sign(idx);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int GetIntegerFromField( void *pData, int fieldType )
{
if ( fieldType == FIELD_INTEGER )
{
return SrcNative( (int*)pData );
}
else if ( fieldType == FIELD_SHORT )
{
return SrcNative( (short*)pData );
}
Error( "Byteswap macro DEFINE_INDEX using unsupported fieldType %d\n", fieldType );
return 0;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void PutIntegerInField( void *pData, int index, int fieldType )
{
if ( fieldType == FIELD_INTEGER )
{
*(int*)pData = SrcNative( &index );
}
else if ( fieldType == FIELD_SHORT )
{
*(short*)pData = SrcNative( &index );
}
else
{
Error( "Byteswap macro DEFINE_INDEX using unsupported fieldType %d\n", fieldType );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void UpdateSrcIndexFields( void *pBase, void *pData, typedescription_t *pField )
{
if ( pField->flags & FTYPEDESC_INDEX )
{
int index = GetIntegerFromField( pData, pField->fieldType );
if ( UpdateIndex( pBase, &index ) )
{
PutIntegerInField( pData, index, pField->fieldType );
}
}
}
//-----------------------------------------------------------------------------
// Pass a datadesc field to a processing function
//-----------------------------------------------------------------------------
void ProcessField( void *pBase, void *pData, typedescription_t *pField, datadescProcessFunc_t pfn )
{
if ( pfn )
{
pfn( pBase, pData, pField );
}
}
//-----------------------------------------------------------------------------
// Process the fields of a datadesc.
//-----------------------------------------------------------------------------
void ProcessFields( void *pBaseAddress, void *pData, datamap_t *pDataMap, datadescProcessFunc_t pfnProcessFunc )
{
// deal with base class first
if ( pDataMap->baseMap )
{
ProcessFields( pBaseAddress, pData, pDataMap->baseMap, pfnProcessFunc );
}
typedescription_t *pFields = pDataMap->dataDesc;
int fieldCount = pDataMap->dataNumFields;
for ( int i = 0; i < fieldCount; ++i )
{
typedescription_t *pField = &pFields[i];
ProcessField( pBaseAddress, (BYTE*)pData + pField->fieldOffset[ TD_OFFSET_NORMAL ], pField, pfnProcessFunc );
}
}
//-----------------------------------------------------------------------------
// Process the fields of a datadesc.
//-----------------------------------------------------------------------------
void ProcessFields( void *pData, datamap_t *pDataMap, datadescProcessFunc_t pfnProcessFunc )
{
ProcessFields( pData, pData, pDataMap, pfnProcessFunc );
}
//-----------------------------------------------------------------------------
// Process a datadesc field by name
//-----------------------------------------------------------------------------
void ProcessFieldByName( void *pBaseAddress, void *pData, datamap_t *pDataMap, const char *pName, datadescProcessFunc_t pfnProcessFunc )
{
// deal with base class first
if ( pDataMap->baseMap )
{
ProcessFieldByName( pBaseAddress, pData, pDataMap->baseMap, pName, pfnProcessFunc );
}
typedescription_t *pFields = pDataMap->dataDesc;
int fieldCount = pDataMap->dataNumFields;
for ( int i = 0; i < fieldCount; ++i )
{
typedescription_t *pField = &pFields[i];
if ( !Q_stricmp( pField->fieldName, pName ) )
{
ProcessField( pBaseAddress, (BYTE*)pData + pField->fieldOffset[ TD_OFFSET_NORMAL ], pField, pfnProcessFunc );
break;
}
}
}
//-----------------------------------------------------------------------------
// Process a datadesc field by name.
//-----------------------------------------------------------------------------
void ProcessFieldByName( void *pData, datamap_t *pDataMap, const char *pName, datadescProcessFunc_t pfnProcessFunc )
{
ProcessFieldByName( pData, pData, pDataMap, pName, pfnProcessFunc );
}
void ProcessANIFields( void *pDataBase, datadescProcessFunc_t pfnProcessFunc );
void ProcessMDLFields( void *pDataBase, datadescProcessFunc_t pfnProcessFunc );
// Fake header declaration for easier phy swapping
struct swapcompactsurfaceheader_t
{
DECLARE_BYTESWAP_DATADESC();
int size;
int vphysicsID;
short version;
short modelType;
int surfaceSize;
Vector dragAxisAreas;
int axisMapSize;
};
BEGIN_BYTESWAP_DATADESC( swapcompactsurfaceheader_t )
DEFINE_FIELD( size, FIELD_INTEGER ),
DEFINE_FIELD( vphysicsID, FIELD_INTEGER ),
DEFINE_FIELD( version, FIELD_SHORT ),
DEFINE_FIELD( modelType, FIELD_SHORT ),
DEFINE_FIELD( surfaceSize, FIELD_INTEGER ),
DEFINE_FIELD( dragAxisAreas, FIELD_VECTOR ),
DEFINE_FIELD( axisMapSize, FIELD_INTEGER ),
END_BYTESWAP_DATADESC()
// Fake header declaration for old style phy format
#if defined( _X360 )
#pragma bitfield_order( push, lsb_to_msb )
#endif
struct legacysurfaceheader_t
{
DECLARE_BYTESWAP_DATADESC();
int size;
float mass_center[3];
float rotation_inertia[3];
float upper_limit_radius;
BEGIN_BITFIELD( bf )
int max_deviation : 8;
int byte_size : 24;
END_BITFIELD()
int offset_ledgetree_root;
int dummy[3];
};
#if defined( _X360 )
#pragma bitfield_order( pop )
#endif
BEGIN_BYTESWAP_DATADESC( legacysurfaceheader_t )
DEFINE_FIELD( size, FIELD_INTEGER ),
DEFINE_ARRAY( mass_center, FIELD_FLOAT, 3 ),
DEFINE_ARRAY( rotation_inertia, FIELD_FLOAT, 3 ),
DEFINE_FIELD( upper_limit_radius, FIELD_FLOAT ),
DEFINE_BITFIELD( bf, FIELD_INTEGER, 32 ),
DEFINE_FIELD( offset_ledgetree_root, FIELD_INTEGER ),
DEFINE_ARRAY( dummy, FIELD_INTEGER, 3 ),
END_BYTESWAP_DATADESC()
//----------------------------------------------------------------------
// Swap a .phy file
// Fixes alignment errors
//----------------------------------------------------------------------
int ByteswapPHY( void *pDestBase, const void *pSrcBase, const int fileSize )
{
Assert( pCollision );
if ( !pCollision )
return 0;
Q_memset( pDestBase, 0, fileSize );
byte *pSrc = (byte*)pSrcBase;
byte *pDest = (byte*)pDestBase;
vcollide_t collide = {0};
// file header
phyheader_t *pHdr = (phyheader_t*)( g_bNativeSrc ? pSrc : pDest );
WriteObjects<phyheader_t>( &pDest, &pSrc );
if ( g_bNativeSrc )
{
// Reset the pointers and let ivp swap the binary physics data
pSrc = (byte*)pSrcBase + pHdr->size;
pDest = (byte*)pDestBase + pHdr->size;
int bufSize = fileSize - pHdr->size;
pCollision->VCollideLoad( &collide, pHdr->solidCount, (const char *)pSrc, bufSize, false );
}
// Swap the collision data headers
for ( int i = 0; i < pHdr->solidCount; ++i )
{
swapcompactsurfaceheader_t *baseHdr = (swapcompactsurfaceheader_t*)( g_bNativeSrc ? pSrc : pDest );
WriteObjects<swapcompactsurfaceheader_t>( pDest, pSrc );
int srcIncrement = baseHdr->surfaceSize + sizeof(swapcompactsurfaceheader_t);
int destIncrement = srcIncrement;
bool bCopyToSrc = !g_bNativeSrc;
if ( baseHdr->vphysicsID != MAKEID('V','P','H','Y') )
{
// May be old phy format
legacysurfaceheader_t *legacyHdr = (legacysurfaceheader_t*)( g_bNativeSrc ? pSrc : pDest );
WriteObjects<legacysurfaceheader_t>( pDest, pSrc );
if ( legacyHdr->dummy[2] == MAKEID('I','V','P','S') || legacyHdr->dummy[2] == 0 )
{
srcIncrement = legacyHdr->byte_size + sizeof(int);
destIncrement = legacyHdr->byte_size + sizeof(swapcompactsurfaceheader_t);
bCopyToSrc = false;
if ( !g_bNativeSrc )
{
// src needs the size member to be native to load vcollides
Q_memcpy( pSrc, pDest, sizeof(int) );
}
}
else
{
// Not recognized
Assert(0);
return 0;
}
}
if ( bCopyToSrc )
{
// src needs the native header data to load the vcollides
Q_memcpy( pSrc, pDest, sizeof(swapcompactsurfaceheader_t) );
}
pSrc += srcIncrement;
pDest += destIncrement;
}
// the rest of the file is text
int currPos = pSrc - (byte*)pSrcBase;
int remainingBytes = fileSize - currPos;
WriteBuffer<char>( &pDest, &pSrc, remainingBytes );
if ( !g_bNativeSrc )
{
// let ivp swap the ledge tree
pSrc = (byte*)pSrcBase + pHdr->size;
int bufSize = fileSize - pHdr->size;
pCollision->VCollideLoad( &collide, pHdr->solidCount, (const char *)pSrc, bufSize, true );
}
// Write out the ledge tree data
pDest = (byte*)pDestBase + pHdr->size;
for ( int i = 0; i < collide.solidCount; ++i )
{
// skip over the size
pDest += sizeof(int);
int offset = pCollision->CollideWrite( (char*)pDest, collide.solids[i], g_bNativeSrc );
int destSize = g_bNativeSrc ? SwapLong( offset ) : offset;
Q_memcpy( pDest - sizeof(int), &destSize, sizeof(int) );
pDest += offset;
}
// Free the memory
pCollision->VCollideUnload( &collide );
int newFileSize = pDest - (byte*)pDestBase + remainingBytes;
if ( g_pCompressFunc )
{
// compress entire swapped PHY
void *pInput = pDestBase;
int inputSize = newFileSize;
void *pOutput;
int outputSize;
if ( g_pCompressFunc( pInput, inputSize, &pOutput, &outputSize ) )
{
// put the compressed version in its place
V_memcpy( pDestBase, pOutput, outputSize );
free( pOutput );
newFileSize = outputSize;
}
}
return newFileSize;
}
//----------------------------------------------------------------------
// Swap a .vvd file
// Doesn't do any alignment fixups
//----------------------------------------------------------------------
int ByteswapVVD( void *pDestBase, const void *pSrcBase, const int fileSize )
{
Q_memset( pDestBase, 0, fileSize );
byte *pDataSrc = (byte*)pSrcBase;
byte *pDataDest = (byte*)pDestBase;
/** FILE HEADER **/
DECLARE_OBJECT_POINTERS( pHdr, pData, vertexFileHeader_t )
WriteObjects<vertexFileHeader_t>( &pDataDest, &pDataSrc );
/** FIXUP TABLE **/
SET_INDEX_POINTERS( pData, pHdr, fixupTableStart )
WriteObjects<vertexFileFixup_t>( &pDataDest, &pDataSrc, SrcNative( &pHdr->numFixups ) );
/** VERTEX DATA **/
SET_INDEX_POINTERS( pData, pHdr, vertexDataStart )
WriteObjects<mstudiovertex_t>( &pDataDest, &pDataSrc, SrcNative( &pHdr->numLODVertexes[0] ) );
/** TANGENT DATA **/
if ( pHdr->tangentDataStart != 0 )
{
SET_INDEX_POINTERS( pData, pHdr, tangentDataStart )
WriteBuffer<float>( &pDataDest, &pDataSrc, 4 * SrcNative( &pHdr->numLODVertexes[0] ) );
}
int newFileSize = pDataDest - (byte*)pDestBase;
if ( g_pCompressFunc )
{
void *pInput = (byte*)pDestBase + sizeof( vertexFileHeader_t );
int inputSize = newFileSize - sizeof( vertexFileHeader_t );
void *pOutput;
int outputSize;
if ( g_pCompressFunc( pInput, inputSize, &pOutput, &outputSize ) )
{
// place the compressed data after the header
V_memcpy( pInput, pOutput, outputSize );
free( pOutput );
newFileSize = sizeof( vertexFileHeader_t ) + outputSize;
}
}
return newFileSize;
}
//----------------------------------------------------------------------
// Swap a .vtx file
// Doesn't do any alignment fixups
//----------------------------------------------------------------------
int ByteswapVTX( void *pDestBase, const void *pSrcBase, const int fileSize )
{
Q_memset( pDestBase, 0, fileSize );
// Do a straight copy first so the string table is transferred
memcpy( pDestBase, pSrcBase, fileSize );
// Start writing the file
byte *pDataSrc = (byte*)pSrcBase;
byte *pDataDest = (byte*)pDestBase;
DECLARE_OBJECT_POINTERS( pVtxHeader, pData, OptimizedModel::FileHeader_t )
WriteObjects( pVtxHeaderDest, pVtxHeaderSrc );
/** BODY PARTS **/
SET_INDEX_POINTERS( pData, pVtxHeader, bodyPartOffset )
DECLARE_OBJECT_POINTERS( pBodyPartHeader, pData, OptimizedModel::BodyPartHeader_t )
ITERATE_BLOCK( pBodyPartHeader, pVtxHeader->numBodyParts )
{
WriteObjects( pBodyPartHeaderDest, pBodyPartHeaderSrc );
/** MODELS **/
SET_INDEX_POINTERS( pData, pBodyPartHeader, modelOffset )
DECLARE_OBJECT_POINTERS( pModelHeader, pData, OptimizedModel::ModelHeader_t )
ITERATE_BLOCK( pModelHeader, pBodyPartHeader->numModels )
{
WriteObjects( pModelHeaderDest, pModelHeaderSrc );
/** MODEL LODS **/
unsigned int meshOffset = 0;
SET_INDEX_POINTERS( pData, pModelHeader, lodOffset )
DECLARE_OBJECT_POINTERS( pModelLODHeader, pData, OptimizedModel::ModelLODHeader_t )
ITERATE_BLOCK( pModelLODHeader, pModelHeader->numLODs )
{
WriteObjects( pModelLODHeaderDest, pModelLODHeaderSrc );
/** MESHES **/
unsigned int prevOffset = meshOffset;
meshOffset = SrcNative( &pModelLODHeader->meshOffset );
if ( prevOffset - sizeof(OptimizedModel::ModelLODHeader_t) == meshOffset )
{
// This LOD shares data with the previous LOD - don't reswap.
continue;
}
SET_INDEX_POINTERS( pData, pModelLODHeader, meshOffset )
DECLARE_OBJECT_POINTERS( pMeshHeader, pData, OptimizedModel::MeshHeader_t )
ITERATE_BLOCK( pMeshHeader, pModelLODHeader->numMeshes )
{
WriteObjects( pMeshHeaderDest, pMeshHeaderSrc );
/** STRIP GROUPS **/
SET_INDEX_POINTERS( pData, pMeshHeader, stripGroupHeaderOffset )
DECLARE_OBJECT_POINTERS( pStripGroupHeader, pData, OptimizedModel::StripGroupHeader_t )
ITERATE_BLOCK( pStripGroupHeader, pMeshHeader->numStripGroups )
{
WriteObjects( pStripGroupHeaderDest, pStripGroupHeaderSrc );
/** STRIP VERTS **/
SET_INDEX_POINTERS( pData, pStripGroupHeader, vertOffset )
WriteObjects<OptimizedModel::Vertex_t>( pDataDest, pDataSrc, SrcNative( &pStripGroupHeader->numVerts ) );
/** VERT INDICES **/
SET_INDEX_POINTERS( pData, pStripGroupHeader, indexOffset )
WriteBuffer<short>( pDataDest, pDataSrc, SrcNative( &pStripGroupHeader->numIndices ) );
/** STRIPS **/
SET_INDEX_POINTERS( pData, pStripGroupHeader, stripOffset )
DECLARE_OBJECT_POINTERS( pStripHeader, pData, OptimizedModel::StripHeader_t )
ITERATE_BLOCK( pStripHeader, pStripGroupHeader->numStrips )
{
WriteObjects( pStripHeaderDest, pStripHeaderSrc );
/** BONE STATE CHANGES **/
SET_INDEX_POINTERS( pData, pStripHeader, boneStateChangeOffset )
WriteObjects<OptimizedModel::BoneStateChangeHeader_t>( pDataDest, pDataSrc, SrcNative( &pStripHeader->numBoneStateChanges ) );
}
}
}
}
}
}
/** MATERIAL REPLACEMENT HEADERS **/
SET_INDEX_POINTERS( pData, pVtxHeader, materialReplacementListOffset )
DECLARE_OBJECT_POINTERS( pMatRepListHeader, pData, OptimizedModel::MaterialReplacementListHeader_t )
ITERATE_BLOCK( pMatRepListHeader, pVtxHeader->numLODs )
{
WriteObjects( pMatRepListHeaderDest, pMatRepListHeaderSrc );
/** MATERIAL REPLACEMENTS **/
SET_INDEX_POINTERS( pData, pMatRepListHeader, replacementOffset )
WriteObjects<OptimizedModel::MaterialReplacementHeader_t>( &pDataDest, &pDataSrc, SrcNative( &pMatRepListHeader->numReplacements ) );
}
int newFileSize = fileSize;
if ( g_pCompressFunc )
{
void *pInput = (byte*)pDestBase + sizeof( OptimizedModel::FileHeader_t );
int inputSize = fileSize - sizeof( OptimizedModel::FileHeader_t );
void *pOutput;
int outputSize;
if ( g_pCompressFunc( pInput, inputSize, &pOutput, &outputSize ) )
{
// place the compressed data after the header
V_memcpy( pInput, pOutput, outputSize );
free( pOutput );
newFileSize = sizeof( OptimizedModel::FileHeader_t ) + outputSize;
}
}
return newFileSize;
}
//----------------------------------------------------------------------
// Swap animation data
// Fixes alignment errors
//----------------------------------------------------------------------
void ByteswapAnimData( mstudioanimdesc_t *pAnimDesc, int section, byte *&pDataSrc, byte *&pDataDest )
{
/** ANIMATIONS **/
DECLARE_OBJECT_POINTERS( pAnimation, pData, mstudioanim_t )
WriteObjects( pAnimationDest, pAnimationSrc );
if ( pAnimation->bone == 255 )
{
// No animation data
pAnimation = 0;
}
while( pAnimation )
{
if ( pAnimation->flags & ( STUDIO_ANIM_RAWROT | STUDIO_ANIM_RAWPOS | STUDIO_ANIM_RAWROT2 ) )
{
if ( pAnimation->flags & STUDIO_ANIM_RAWROT )
{
int offset = (byte*)pAnimation->pQuat48() - (byte*)pAnimation;
pDataSrc = (byte*)pAnimationSrc + offset;
pDataDest = (byte*)pAnimationDest + offset;
// Write the quaternion (bit fields contained in 3 unsigned shorts)
WriteBuffer<short>( &pDataDest, &pDataSrc, 3 );
}
if ( pAnimation->flags & STUDIO_ANIM_RAWROT2 )
{
int offset = (byte*)pAnimation->pQuat64() - (byte*)pAnimation;
pDataSrc = (byte*)pAnimationSrc + offset;
pDataDest = (byte*)pAnimationDest + offset;
// Write the quaternion (bit fields contained in 1 64 bit int
WriteBuffer<int64>( &pDataDest, &pDataSrc, 1 );
}
if ( pAnimation->flags & STUDIO_ANIM_RAWPOS )
{
int offset = (byte*)pAnimation->pPos() - (byte*)pAnimation;
pDataSrc = (byte*)pAnimationSrc + offset;
pDataDest = (byte*)pAnimationDest + offset;
// Write the vector (3 float16)
WriteBuffer<short>( &pDataDest, &pDataSrc, 3 );
}
}
else
{
int offset = (byte*)pAnimation->pRotV() - (byte*)pAnimation;
pDataSrc = (byte*)pAnimationSrc + offset;
pDataDest = (byte*)pAnimationDest + offset;
mstudioanim_valueptr_t *rotvptr = (mstudioanim_valueptr_t*)pDataSrc;
WriteObjects<mstudioanim_valueptr_t>( &pDataDest, &pDataSrc );
int animValueCt = 0;
for ( int idx = 0; idx < 3; ++idx )
{
animValueCt += rotvptr->offset[idx] ? 1 : 0;
}
if ( pAnimation->flags & STUDIO_ANIM_ANIMPOS )
{
int offset = (byte*)pAnimation->pPosV() - (byte*)pAnimation;
pDataSrc = (byte*)pAnimationSrc + offset;
pDataDest = (byte*)pAnimationDest + offset;
mstudioanim_valueptr_t *posvptr = (mstudioanim_valueptr_t*)pDataSrc;
WriteObjects<mstudioanim_valueptr_t>( &pDataDest, &pDataSrc );
for ( int idx = 0; idx < 3; ++idx )
{
animValueCt += posvptr->offset[idx] ? 1 : 0;
}
}
// Write position and rotation animations
// Note: destanimvalue_t is a union that can be either two bytes or a short.
// This structure is used to compress animation data using RLE.
// The first object of a chunk acts as the header, and uses the two bytes to
// store how many objects follow, and how many frames are encoded by them.
// The objects that follow use the short to store a value.
// The total number of chunks has been determined by counting the number of valid (non-zero) offsets.
for ( int animValue = 0; animValue < animValueCt; ++animValue )
{
int encodedFrames = 0;
int totalFrames = SrcNative( &pAnimDesc->numframes );
int sectionFrames = SrcNative( &pAnimDesc->sectionframes );
if ( sectionFrames )
{
int iStartFrame = section * sectionFrames;
int iEndFrame = (section + 1) * sectionFrames;
iStartFrame = min( iStartFrame, totalFrames - 1 );
iEndFrame = min( iEndFrame, totalFrames - 1 );
totalFrames = iEndFrame - iStartFrame + 1;
}
while ( encodedFrames < totalFrames )
{
// Write the first animation value (struct of 2 bytes)
mstudioanimvalue_t *pDestAnimvalue = (mstudioanimvalue_t*)( g_bNativeSrc ? pDataSrc : pDataDest );
WriteBuffer<char>( &pDataDest, &pDataSrc, 2 );
// Write the remaining animation values from this group (shorts)
WriteBuffer<short>( &pDataDest, &pDataSrc, pDestAnimvalue->num.valid );
encodedFrames += pDestAnimvalue->num.total;
}
}
}
// TODOKD: Could add a fixup here with some more work, hasn't been necessary yet
if ( pAnimation->nextoffset )
{
// Set pointers to the next animation
pAnimationSrc = (mstudioanim_t*)( (byte*)pAnimationSrc + SrcNative( &pAnimation->nextoffset ) );
pAnimationDest = (mstudioanim_t*)( (byte*)pAnimationDest + SrcNative( &pAnimation->nextoffset ) );
pAnimation = pAnimationSrc;
// Swap the next animation
WriteObjects( pAnimationDest, pAnimationSrc );
}
else
{
pAnimation = 0;
pDataSrc += sizeof( mstudioanim_t );
pDataDest += sizeof( mstudioanim_t );
}
}
ALIGN4( pDataSrc );
ALIGN4( pDataDest );
}
int ByteswapIKRules( studiohdr_t *&pHdrSrc, int numikrules, int numFrames, byte *&pDataSrc, byte *&pDataDest, int &fixedFileSize, const int fileSize )
{
DECLARE_OBJECT_POINTERS( pIKRule, pData, mstudioikrule_t )
ITERATE_BLOCK( pIKRule, numikrules )
{
WriteObjects<mstudioikrule_t>( pIKRuleDest, pIKRuleSrc );
/** IK ERROR KEYS **/
// Calculate the number of ikerrors by converting the ikerror start and end float values to
// frame numbers. (See the generation of these values in simplify.cpp: ProcessIKRules()).
float start = floorf( SrcNative( &pIKRule->start ) * (numFrames - 1) + 0.5f );
float end = floorf( SrcNative( &pIKRule->end ) * (numFrames - 1) + 0.5f );
int totalerror = (int)( end - start + 1 );
if ( end >= numFrames )
totalerror += 2;
// Uncompressed - only found in some older models (shipped hl2)
if ( pIKRule->ikerrorindex )
{
SET_INDEX_POINTERS_FIXUP( pData, pIKRule, ikerrorindex )
WriteObjects<mstudioikerror_t>( pDataDest, pDataSrc, totalerror );
}
// Compressed - all models since hl2
if ( pIKRule->compressedikerrorindex )
{
SET_INDEX_POINTERS_FIXUP( pData, pIKRule, compressedikerrorindex )
WriteObjects<mstudiocompressedikerror_t>( pDataDest, pDataSrc );
mstudiocompressedikerror_t *pCompressed = (mstudiocompressedikerror_t *)pDataSrc;
// Write the animvalues.
for ( int idx = 0; idx < 6; ++idx )
{
if ( pCompressed->offset[idx] )
{
byte *pAnimvalueSrc = pDataSrc + SrcNative( &pCompressed->offset[idx] );
byte *pAnimvalueDest = pDataDest + SrcNative( &pCompressed->offset[idx] );
int numerror = 0;
while ( numerror < totalerror )
{
// Write the first animation value (struct of 2 bytes)
mstudioanimvalue_t *pDestAnimvalue = (mstudioanimvalue_t*)( g_bNativeSrc ? pAnimvalueSrc : pAnimvalueDest );
WriteBuffer<char>( &pAnimvalueDest, &pAnimvalueSrc, 2 );
// Write the remaining animation values from this group (shorts)
WriteBuffer<short>( &pAnimvalueDest, &pAnimvalueSrc, pDestAnimvalue->num.valid );
numerror += pDestAnimvalue->num.total;
}
}
}
if ( pIKRule->szattachmentindex )
{
SET_INDEX_POINTERS( pData, pIKRule, szattachmentindex )
int size = strlen( (char*)pDataSrc ) + 1;
WriteBuffer<char>( pDataDest, pDataSrc, size );
}
}