-
Notifications
You must be signed in to change notification settings - Fork 3
/
rw.cpp
2287 lines (2108 loc) · 64.4 KB
/
rw.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
#include "rw.h"
#include "rwext.h"
#include <cassert>
#include <stb_image.h>
#include <map>
#include <squish.h>
#include <algorithm>
struct DDS_PIXELFORMAT {
uint32_t dwSize, dwFlags, dwFourCC, dwRGBBitCount, dwRBitMask, dwGBitMask, dwBBitMask, dwABitMask;
};
struct DDS_HEADER {
uint32_t dwSize, dwFlags, dwHeight, dwWidth, dwLinearSize, dwDepth, dwMipMapCount;
uint32_t dwReserved1[11];
DDS_PIXELFORMAT ddpf;
uint32_t dwCaps, dwCaps2, dwCaps3, dwCaps4;
uint32_t dwReserved2;
};
static constexpr uint16_t byteswap16(uint16_t val) { return ((val & 255) << 8) | ((val >> 8) & 255); }
static constexpr uint32_t byteswap32(uint32_t val) { return ((val & 255) << 24) | (((val >> 8) & 255) << 16) | (((val >> 16) & 255) << 8) | ((val >> 24) & 255); }
static constexpr float byteswapFlt(float val) { auto b = byteswap32(*(uint32_t*)&val); return *(float*)&b; }
uint32_t HeaderWriter::rwver = 0x1803FFFF;
RwsHeader rwReadHeader(File * file)
{
uint32_t h_type = file->readUint32();
uint32_t h_size = file->readUint32();
uint32_t h_ver = file->readUint32();
HeaderWriter::rwver = h_ver; // very hacky :/
return RwsHeader(h_type, h_size, h_ver);
}
RwsHeader rwFindHeader(File * file, uint32_t type)
{
RwsHeader head;
while(true) {
head = rwReadHeader(file);
assert(head.rwVersion == HeaderWriter::rwver);
if (head.type == type)
break;
file->seek(head.length, SEEK_CUR);
}
return RwsHeader();
}
uint32_t rwCheckHeader(File *file, uint32_t type)
{
uint32_t h_type = file->readUint32();
uint32_t h_size = file->readUint32();
uint32_t h_ver = file->readUint32();
assert(h_type == type);
HeaderWriter::rwver = h_ver; // very hacky :/
return h_size;
}
void rwCheckAndSkipHeader(File *file, uint32_t type)
{
file->seek(rwCheckHeader(file, type), SEEK_CUR);
}
void rwWriteString(File * file, const std::string & str)
{
uint32_t len = str.size() + 1;
uint32_t pad = (len + 3) & ~3;
file->writeUint32(2);
file->writeUint32(pad);
file->writeUint32(HeaderWriter::rwver);
if (str.empty()) {
file->writeUint32(0xDDDDDD00); // we need this for binary matching with original
}
else {
file->write(str.c_str(), len);
for (uint32_t i = 0; i < pad - len; i++)
file->writeUint8(0);
}
}
void RwsExtHolder::read(File * file, void *parent, uint32_t parentType) {
RwsHeader ctrhead = rwReadHeader(file);
assert(ctrhead.type == 3);
uint32_t bytesRead = 0;
while (bytesRead < ctrhead.length) {
RwsHeader exthead = rwReadHeader(file);
uint32_t startoff = file->tell();
auto ext = RwExtCreate(exthead.type, parentType);
ext->deserialize(file, exthead, parent);
assert(file->tell() == startoff + exthead.length);
this->exts.push_back(std::move(ext));
bytesRead += 12 + exthead.length;
}
}
void RwsExtHolder::write(File * file)
{
HeaderWriter ctrhead;
ctrhead.begin(file, 3);
for (auto& ext : exts)
ext->serialize(file);
ctrhead.end(file);
}
RwExtension * RwsExtHolder::find(uint32_t type)
{
for (auto& ext : exts)
if (ext->getType() == type)
return ext.get();
return nullptr;
}
const RwExtension * RwsExtHolder::find(uint32_t type) const
{
for (auto& ext : exts)
if (ext->getType() == type)
return ext.get();
return nullptr;
}
RwsExtHolder::RwsExtHolder() = default;
RwsExtHolder::~RwsExtHolder() = default;
RwsExtHolder::RwsExtHolder(const RwsExtHolder & orig)
{
exts.reserve(orig.exts.size());
for (auto& ext : orig.exts)
exts.push_back(ext->clone());
}
RwsExtHolder::RwsExtHolder(RwsExtHolder&& old) noexcept = default;
RwsExtHolder& RwsExtHolder::operator=(const RwsExtHolder & orig)
{
exts.clear();
exts.reserve(orig.exts.size());
for (auto& ext : orig.exts)
exts.push_back(ext->clone());
return *this;
}
RwsExtHolder& RwsExtHolder::operator=(RwsExtHolder&& old) noexcept = default;
void RwFrame::deserialize(File * file)
{
for (int r = 0; r < 4; r++)
for (int c = 0; c < 3; c++)
matrix[r][c] = file->readFloat();
index = file->readUint32();
flags = file->readUint32();
}
void RwFrame::serialize(File * file)
{
for (int r = 0; r < 4; r++)
for (int c = 0; c < 3; c++)
file->writeFloat(matrix[r][c]);
file->writeUint32(index);
file->writeUint32(flags);
}
void RwFrameList::deserialize(File * file)
{
rwCheckHeader(file, 1);
uint32_t numFrames = file->readUint32();
frames.resize(numFrames);
for (RwFrame &frame : frames) {
frame.deserialize(file);
}
extensions.resize(numFrames);
for (RwsExtHolder &reh : extensions)
reh.read(file, this);
}
void RwFrameList::serialize(File * file)
{
HeaderWriter head1, head2;
head1.begin(file, 0xE);
{
head2.begin(file, 1);
file->writeUint32(this->frames.size());
for (RwFrame &frame : frames) {
frame.serialize(file);
}
head2.end(file);
for (RwsExtHolder &reh : extensions)
reh.write(file);
}
head1.end(file);
}
void RwGeometry::deserialize(File * file)
{
rwCheckHeader(file, 1);
flags = file->readUint32();
numTris = file->readUint32();
numVerts = file->readUint32();
numMorphs = file->readUint32();
if ((flags & RWGEOFLAG_NATIVE) == 0) {
if (flags & RWGEOFLAG_PRELIT) {
colors.reserve(numVerts);
for (uint32_t i = 0; i < numVerts; i++)
colors.push_back(file->readUint32());
}
uint32_t numSets = (flags >> 16) & 255;
if (numSets == 0) {
if (flags & RWGEOFLAG_TEXTURED2) numSets = 2;
else if (flags & RWGEOFLAG_TEXTURED) numSets = 1;
}
texSets.resize(numSets);
for (auto &texCoords : texSets) {
texCoords.reserve(numVerts);
for (uint32_t i = 0; i < numVerts; i++) {
std::array<float, 2> tc;
for (float &c : tc)
c = file->readFloat();
texCoords.push_back(std::move(tc));
}
}
tris.resize(numTris);
for (Triangle &tri : tris) {
tri.indices[0] = file->readUint16();
tri.indices[1] = file->readUint16();
tri.materialId = file->readUint16();
tri.indices[2] = file->readUint16();
}
}
assert(numMorphs == 1);
spherePos.x = file->readFloat();
spherePos.y = file->readFloat();
spherePos.z = file->readFloat();
sphereRadius = file->readFloat();
hasVertices = file->readUint32();
hasNormals = file->readUint32();
if (hasVertices) {
verts.resize(numVerts);
for (Vector3 &v : verts) {
v.x = file->readFloat();
v.y = file->readFloat();
v.z = file->readFloat();
}
}
if (hasNormals) {
norms.resize(numVerts);
for (Vector3 &n : norms) {
n.x = file->readFloat();
n.y = file->readFloat();
n.z = file->readFloat();
}
}
rwCheckHeader(file, 8);
this->materialList.deserialize(file);
extensions.read(file, this);
if (flags & RWGEOFLAG_NATIVE) {
auto old = std::make_shared<RwGeometry>(std::move(*this));
*this = old->convertToPI();
this->nativeVersion = std::move(old);
}
}
void RwGeometry::serialize(File * file)
{
if (nativeVersion) {
nativeVersion->serialize(file);
return;
}
HeaderWriter head1, head2;
head1.begin(file, 0xF);
{
head2.begin(file, 1);
{
if (texSets.size() > 2)
printf("Writing a geometry with %zu texcoord sets!!!\n", texSets.size());
uint32_t flagsToWrite;
if (flags & RWGEOFLAG_NATIVE) {
flagsToWrite = flags;
}
else {
flagsToWrite = flags & ~uint32_t(0x00FF0000 | RWGEOFLAG_TEXTURED | RWGEOFLAG_TEXTURED2);
flagsToWrite |= (uint32_t)texSets.size() << 16;
if (texSets.size() == 1) flagsToWrite |= RWGEOFLAG_TEXTURED;
if (texSets.size() == 2) flagsToWrite |= RWGEOFLAG_TEXTURED2;
}
file->writeUint32(flagsToWrite);
file->writeUint32(numTris);
file->writeUint32(numVerts);
file->writeUint32(numMorphs);
if ((flags & RWGEOFLAG_NATIVE) == 0) {
if (flags & RWGEOFLAG_PRELIT) {
for (uint32_t color : colors)
file->writeUint32(color);
}
for (auto& texCoords : texSets)
for (auto& tc : texCoords)
for (float& c : tc)
file->writeFloat(c);
for (Triangle& tri : tris) {
file->writeUint16(tri.indices[0]);
file->writeUint16(tri.indices[1]);
file->writeUint16(tri.materialId);
file->writeUint16(tri.indices[2]);
}
}
file->writeFloat(spherePos.x);
file->writeFloat(spherePos.y);
file->writeFloat(spherePos.z);
file->writeFloat(sphereRadius);
file->writeUint32(hasVertices);
file->writeUint32(hasNormals);
if (hasVertices) {
for (Vector3 &v : verts) {
file->writeFloat(v.x);
file->writeFloat(v.y);
file->writeFloat(v.z);
}
}
if (hasNormals) {
for (Vector3 &n : norms) {
file->writeFloat(n.x);
file->writeFloat(n.y);
file->writeFloat(n.z);
}
}
}
head2.end(file);
materialList.serialize(file);
extensions.write(file);
}
head1.end(file);
}
void RwGeometry::merge(const RwGeometry & other)
{
assert(numMorphs == other.numMorphs == 1);
//printf("norms: %i %i", norms.size(), other.norms.size());
const uint32_t toleratedFlags = 0x00FF0000 | RWGEOFLAG_TRISTRIP | RWGEOFLAG_NORMALS | RWGEOFLAG_LIGHT | RWGEOFLAG_MODULATECOLOR
| RWGEOFLAG_TEXTURED | RWGEOFLAG_TEXTURED2;
assert((flags | toleratedFlags) == (other.flags | toleratedFlags));
assert(hasVertices == other.hasVertices);
uint16_t newmatstart = materialList.slots.size();
uint16_t newtristart = verts.size();
for (const Triangle &tri : other.tris) {
Triangle newtri = tri;
for (uint16_t &ix : newtri.indices)
ix += newtristart;
newtri.materialId += newmatstart;
tris.push_back(std::move(newtri));
}
// update number of texture coordinate sets
if (other.texSets.size() > texSets.size()) {
size_t oldTexSetsCount = texSets.size();
texSets.resize(other.texSets.size());
for (size_t i = oldTexSetsCount; i < texSets.size(); ++i) {
texSets[i].assign(numVerts, { 0.0f, 0.0f });
}
}
numTris += other.numTris;
numVerts += other.numVerts;
if ((hasNormals != 0) ^ (other.hasNormals != 0)) {
if (hasNormals == 0) {
for (int i = 0; i < verts.size(); i++)
norms.push_back(Vector3(0, 0, 0));
hasNormals = 1;
flags |= RWGEOFLAG_NORMALS;
}
if (other.hasNormals == 0) {
assert(other.norms.size() == 0);
for (int i = 0; i < other.verts.size(); i++)
norms.push_back(Vector3(0, 0, 0));
}
}
for (auto &vert : other.verts)
verts.push_back(vert);
for (auto &norm : other.norms)
norms.push_back(norm);
for (auto &color : other.colors)
colors.push_back(color);
for (size_t i = 0; i < texSets.size(); i++) {
if (i < other.texSets.size()) {
for (auto& coord : other.texSets[i])
texSets[i].push_back(coord);
}
else {
texSets[i].insert(texSets[i].end(), other.numVerts, {0.0f, 0.0f});
}
}
if (spherePos == other.spherePos)
sphereRadius = std::max(sphereRadius, other.sphereRadius);
else {
Vector3 n_t2o = (other.spherePos - spherePos).normal();
Vector3 ext_t = spherePos - n_t2o * sphereRadius;
Vector3 ext_o = other.spherePos + n_t2o * other.sphereRadius;
if ((ext_o - spherePos).len3() <= sphereRadius);
else if ((ext_t - other.spherePos).len3() <= other.sphereRadius) {
spherePos = other.spherePos;
sphereRadius = other.sphereRadius;
}
else {
spherePos = (ext_t + ext_o) * 0.5f;
sphereRadius = 0.5f * (ext_o - ext_t).len3();
}
}
for (uint32_t slot : other.materialList.slots)
materialList.slots.push_back((slot == 0xFFFFFFFF) ? slot : (slot + newmatstart));
for (auto &mat : other.materialList.materials)
materialList.materials.push_back(mat);
RwsExtHolder newholder;
if (RwExtension *ext = extensions.find(0x116)) {
auto skinUP = ext->clone();
RwExtSkin* skin = (RwExtSkin*)skinUP.get();
skin->merge(*(RwExtSkin*)other.extensions.find(0x116));
newholder.exts.push_back(std::move(skinUP));
}
extensions = std::move(newholder);
}
std::vector<std::unique_ptr<RwGeometry>> RwGeometry::splitByMaterial()
{
std::vector<std::unique_ptr<RwGeometry>> geolist;
std::vector<std::map<uint16_t, uint16_t>> ixmaps;
size_t numMats = materialList.materials.size();
RwExtSkin *oskin = (RwExtSkin*)extensions.find(0x116);
for (size_t i = 0; i < numMats; i++) {
std::unique_ptr<RwGeometry> sgeo = std::make_unique<RwGeometry>();
sgeo->flags = flags & ~RWGEOFLAG_TRISTRIP;
sgeo->numVerts = 0;
sgeo->numTris = 0;
sgeo->numMorphs = numMorphs;
sgeo->texSets.resize(texSets.size());
sgeo->spherePos = spherePos;
sgeo->sphereRadius = sphereRadius;
sgeo->hasVertices = hasVertices;
sgeo->hasNormals = hasNormals;
sgeo->materialList.slots = { 0xFFFFFFFF };
sgeo->materialList.materials.push_back(materialList.materials[i]);
if (oskin) {
auto nskin = std::make_unique<RwExtSkin>();
nskin->numBones = oskin->numBones;
nskin->numUsedBones = oskin->numBones;
nskin->usedBones = oskin->usedBones;
nskin->maxWeightPerVertex = oskin->maxWeightPerVertex;
nskin->matrices = oskin->matrices;
nskin->isSplit = oskin->isSplit;
nskin->boneLimit = 0;
sgeo->extensions.exts.push_back(std::move(nskin));
}
geolist.push_back(std::move(sgeo));
}
ixmaps.resize(numMats);
for (Triangle &tri : tris) {
uint16_t matid = tri.materialId;
RwGeometry *sgeo = geolist[matid].get();
std::map<uint16_t, uint16_t> &ixmap = ixmaps[matid];
Triangle stri;
stri.materialId = 0;
for (int i = 0; i < 3; i++) {
uint16_t oi = tri.indices[i];
auto it = ixmap.find(oi);
if (it != ixmap.end())
stri.indices[i] = it->second;
else {
uint16_t ni = sgeo->numVerts++;
stri.indices[i] = ni;
ixmap[oi] = ni;
if(flags & RWGEOFLAG_POSITIONS)
sgeo->verts.push_back(verts[oi]);
if(hasNormals != 0)
sgeo->norms.push_back(norms[oi]);
if(flags & RWGEOFLAG_PRELIT)
sgeo->colors.push_back(colors[oi]);
for (int ts = 0; ts < sgeo->texSets.size(); ts++)
sgeo->texSets[ts].push_back(texSets[ts][oi]);
if (oskin) {
RwExtSkin *nskin = (RwExtSkin*)sgeo->extensions.exts[0].get();
nskin->vertexIndices.push_back(oskin->vertexIndices[oi]);
nskin->vertexWeights.push_back(oskin->vertexWeights[oi]);
}
}
}
sgeo->tris.push_back(stri);
sgeo->numTris++;
}
return geolist;
}
RwGeometry RwGeometry::convertToPI()
{
assert(flags & RWGEOFLAG_NATIVE);
RwExtNativeData* nat = (RwExtNativeData*)extensions.find(0x510);
assert(nat);
assert(nat->data.size() >= 4);
uint32_t platform = *(uint32_t*)nat->data.data();
switch (platform) {
case 6:
return convertToPI_GCN();
case byteswap32(9):
return convertToPI_X360();
default: {
// give an empty geometry for unsupported platforms
RwGeometry empty;
empty.flags = 0;
empty.numTris = 0;
empty.numVerts = 0;
empty.numMorphs = 0;
return empty;
}
}
assert(false && "unknown platform for native RwGeometry");
return {};
}
RwGeometry RwGeometry::convertToPI_GCN()
{
RwGeometry* geo = this;
RwGeometry cvt;
cvt.flags = 0;
cvt.numTris = 0;
cvt.numVerts = 0;
cvt.numMorphs = 1;
cvt.texSets.resize(1);
cvt.spherePos = geo->spherePos;
cvt.sphereRadius = geo->sphereRadius;
cvt.hasVertices = 0;
cvt.hasNormals = 0;
cvt.materialList = geo->materialList;
//cvt.extensions = geo->extensions;
RwExtNativeData* nat = (RwExtNativeData*)geo->extensions.find(0x510);
assert(nat);
bool hasSkinIndices = false;
RwExtSkin* skin = (RwExtSkin*)geo->extensions.find(0x116);
RwExtSkin* cvtSkin = nullptr;
std::vector<uint8_t> cmpIndices;
std::vector<uint8_t> cmpWeights;
if (skin && *(uint32_t*)skin->nativeData.data() == 6) {
hasSkinIndices = true;
auto cvtUniquePtr = std::make_unique<RwExtSkin>();
cvtSkin = cvtUniquePtr.get();
cvt.extensions.exts.push_back(std::move(cvtUniquePtr));
// On GC, skin native data looks almost like non-native one, except:
// - if numOfWeights == 1, vertex weights+indices are missing,
// instead, vertex indices are stored in the geometry's native data (and weight is always 1.0)
// - else, only numOfWeights vertex indices are stored per vertex (no useless 0 when numOfWeights < 4)
// and numOfWeights vertex weights are stored per vertex, each being 8 bits, from 0x00 = 0.0 to 0x80 = 1.0
// sum of weights should be 0x80 = 1.0
// - matrices are byte-swapped
MemFile data{ skin->nativeData.data() };
uint32_t skinPlatform = data.readUint32();
assert(skinPlatform == 6);
cvtSkin->numBones = data.readUint8();
cvtSkin->numUsedBones = data.readUint8();
cvtSkin->maxWeightPerVertex = data.readUint8();
data.readUint8();
cvtSkin->usedBones.reserve(cvtSkin->numUsedBones);
for (int i = 0; i < cvtSkin->numUsedBones; i++)
cvtSkin->usedBones.push_back(data.readUint8());
if (cvtSkin->maxWeightPerVertex >= 2) {
cmpIndices.resize(geo->numVerts * cvtSkin->maxWeightPerVertex);
cmpWeights.resize(geo->numVerts * cvtSkin->maxWeightPerVertex);
data.read(cmpIndices.data(), cmpIndices.size());
data.read(cmpWeights.data(), cmpWeights.size());
}
cvtSkin->matrices.resize(cvtSkin->numBones);
for (Matrix& mat : cvtSkin->matrices) {
if (cvtSkin->maxWeightPerVertex == 0)
data.readUint32();
for (int i = 0; i < 16; i++)
mat.v[i] = byteswapFlt(data.readFloat());
}
cvtSkin->isSplit = cvtSkin->numUsedBones != 0; // TODO: Find a better way to detect the presence of split data
if (cvtSkin->isSplit) {
cvtSkin->boneLimit = data.readUint32();
cvtSkin->boneGroups.resize(data.readUint32());
cvtSkin->boneGroupIndices.resize(data.readUint32());
assert(cvtSkin->maxWeightPerVertex < 2 || cvtSkin->boneLimit == 0);
if (!cvtSkin->boneGroups.empty()) {
cvtSkin->boneIndexRemap.resize(cvtSkin->numBones);
data.read(cvtSkin->boneIndexRemap.data(), cvtSkin->boneIndexRemap.size());
for (auto& grp : cvtSkin->boneGroups) {
grp.first = data.readUint8();
grp.second = data.readUint8();
}
for (auto& gi : cvtSkin->boneGroupIndices) {
gi.first = data.readUint8();
gi.second = data.readUint8();
}
}
}
}
MemFile mf(nat->data.data());
auto platform = mf.readUint32();
auto headSize = mf.readUint32();
auto gfxDataSize = mf.readUint32();
auto headOffset = mf.tell();
auto gfxDataOffset = headOffset + headSize;
mf.readUint32();
mf.readUint32();
auto numAttribs = byteswap32(mf.readUint32());
struct Attribute {
uint32_t offset;
uint8_t type;
uint8_t stride;
uint8_t indexType, unk2;
};
std::vector<Attribute> attribs(numAttribs);
for (auto& atb : attribs) {
atb.offset = byteswap32(mf.readUint32());
atb.type = mf.readUint8();
atb.stride = mf.readUint8();
atb.indexType = mf.readUint8();
atb.unk2 = mf.readUint8();
switch (atb.type) {
case 9: // POS
cvt.flags |= RWGEOFLAG_POSITIONS;
cvt.hasVertices = 1;
break;
case 10: // NRM
cvt.flags |= RWGEOFLAG_NORMALS;
cvt.hasNormals = 1;
break;
case 11: // CLR0
cvt.flags |= RWGEOFLAG_PRELIT;
break;
case 13: // TEX0
cvt.flags |= RWGEOFLAG_TEXTURED;
break;
}
}
int numMeshes = (headSize - (12 + 8 * numAttribs)) / 8;
std::vector<std::pair<uint32_t, uint32_t>> meshes(numMeshes);
for (auto& mesh : meshes) {
mesh.first = byteswap32(mf.readUint32());
mesh.second = byteswap32(mf.readUint32());
}
uint16_t vtxind = 0;
int meshIndex = 0;
assert(!hasSkinIndices || cvtSkin->boneLimit == 0 || cvtSkin->boneGroups.size() == (size_t)numMeshes);
for (auto& mesh : meshes) {
auto cmdOffset = mesh.first;
auto cmdSize = mesh.second;
uint8_t* cmdStart = nat->data.data() + gfxDataOffset + cmdOffset;
uint8_t* cmd = cmdStart;
while (cmd - cmdStart < cmdSize) {
uint8_t prim = *cmd++;
if (prim == 0)
break;
assert(prim == 0x90 || prim == 0x98);
uint8_t unk = *cmd++;
uint16_t count = *cmd++ | (unk << 8);
cvt.numVerts += count;
cvt.colors.insert(cvt.colors.end(), count, 0xFFFFFFFF);
cvt.texSets[0].insert(cvt.texSets[0].end(), count, { 0.0f,0.0f });
cvt.verts.insert(cvt.verts.end(), count, Vector3(0.0f, 0.0f, 0.0f));
if (cvt.hasNormals)
cvt.norms.insert(cvt.norms.end(), count, Vector3(0.0f, 0.0f, 0.0f));
if (hasSkinIndices) {
cvtSkin->vertexIndices.insert(cvtSkin->vertexIndices.end(), count, { 0, 0, 0, 0 });
cvtSkin->vertexWeights.insert(cvtSkin->vertexWeights.end(), count, { 0.0f, 0.0f, 0.0f, 0.0f });
}
for (int i = 0; i < count; i++) {
uint8_t skinByte = 0;
if (hasSkinIndices && cvtSkin->maxWeightPerVertex == 1)
skinByte = *cmd++;
for (int a = 0; a < attribs.size(); a++) {
auto& atb = attribs[a];
uint16_t index = *cmd++;
if (atb.indexType == 3)
index = (index << 8) | *cmd++;
uint8_t* gdptr = nat->data.data() + gfxDataOffset + atb.offset + atb.stride * index;
if (atb.type == 9) { // POS
float x = byteswapFlt(*(float*)(gdptr + 0));
float y = byteswapFlt(*(float*)(gdptr + 4));
float z = byteswapFlt(*(float*)(gdptr + 8));
cvt.verts[vtxind] = Vector3(x, y, z);
if (hasSkinIndices) {
// vertex weight + indices
std::array<uint8_t, 4> nativeBoneIndices = { 0,0,0,0 };
std::array<float, 4> nativeBoneWeights = { 0.0f, 0.0f, 0.0f, 0.0f };
if (cvtSkin->maxWeightPerVertex == 1) {
assert(skinByte % 3 == 0);
nativeBoneIndices[0] = skinByte / 3;
nativeBoneWeights[0] = 1.0f;
}
else if (cvtSkin->maxWeightPerVertex >= 2) {
for (int w = 0; w < cvtSkin->maxWeightPerVertex; ++w) {
nativeBoneIndices[w] = cmpIndices[index * cvtSkin->maxWeightPerVertex + w];
nativeBoneWeights[w] = (float)cmpWeights[index * cvtSkin->maxWeightPerVertex + w] / 128.0f;
}
}
// apply bone index remapping
if (!cvtSkin->boneGroups.empty()) {
auto [remStart, remCount] = cvtSkin->boneGroups[meshIndex];
for (int w = 0; w < cvtSkin->maxWeightPerVertex; ++w) {
uint8_t& boneIndex = nativeBoneIndices[w];
for (uint8_t rem = remStart; rem < remStart + remCount; ++rem) {
auto [riStart, riCount] = cvtSkin->boneGroupIndices[rem];
auto itStart = cvtSkin->boneIndexRemap.begin() + riStart;
auto itEnd = cvtSkin->boneIndexRemap.begin() + riStart + riCount;
auto it = std::find(itStart, itEnd, boneIndex);
if (it != itEnd) {
boneIndex = (uint8_t)(it - itStart) + riStart;
break;
}
}
}
}
cvtSkin->vertexIndices[vtxind] = nativeBoneIndices;
cvtSkin->vertexWeights[vtxind] = nativeBoneWeights;
}
}
else if (atb.type == 10) { // NRM
float x = byteswapFlt(*(float*)(gdptr + 0));
float y = byteswapFlt(*(float*)(gdptr + 4));
float z = byteswapFlt(*(float*)(gdptr + 8));
cvt.norms[vtxind] = Vector3(x, y, z);
}
else if (atb.type == 11) { // CLR0
cvt.colors[vtxind] = *(uint32_t*)gdptr;
}
else if (atb.type == 13) { // TEX0
float x = byteswapFlt(*(float*)(gdptr + 0));
float y = byteswapFlt(*(float*)(gdptr + 4));
cvt.texSets[0][vtxind] = { x,y };
}
}
if (prim == 0x90) { // TRIANGLES
if ((i % 3) == 2) {
cvt.tris.push_back({ {vtxind, (uint16_t)(vtxind - 1), (uint16_t)(vtxind - 2)}, (uint16_t)0 });
}
}
else if (prim == 0x98) { // TRIANGLESTRIP
if (i >= 2) {
std::array<uint16_t, 3> arr = { vtxind, (uint16_t)(vtxind - 1), (uint16_t)(vtxind - 2) };
if (i & 1) std::swap(arr[0], arr[1]);
cvt.tris.push_back({ arr, (uint16_t)0 });
}
}
vtxind++;
}
}
meshIndex++;
}
cvt.numTris = cvt.tris.size();
if (hasSkinIndices) {
// we just applied the remapping, now we can clear it
cvtSkin->boneLimit = 0;
auto clear_and_shrink = [](auto& vec) {vec.clear(); vec.shrink_to_fit(); };
clear_and_shrink(cvtSkin->boneIndexRemap);
clear_and_shrink(cvtSkin->boneGroupIndices);
clear_and_shrink(cvtSkin->boneGroups);
}
return cvt;
}
RwGeometry RwGeometry::convertToPI_X360()
{
RwGeometry* geo = this;
RwGeometry cvt;
cvt.flags = 0;
cvt.numTris = 0;
cvt.numVerts = 0;
cvt.numMorphs = 1;
cvt.texSets.resize(1);
cvt.spherePos = geo->spherePos;
cvt.sphereRadius = geo->sphereRadius;
cvt.hasVertices = 0;
cvt.hasNormals = 0;
cvt.materialList = geo->materialList;
cvt.extensions = geo->extensions;
RwExtNativeData* nat = (RwExtNativeData*)geo->extensions.find(0x510);
assert(nat);
MemFile mf(nat->data.data());
auto platform = byteswap32(mf.readUint32()); assert(platform == 9);
auto headSize = byteswap32(mf.readUint32()); assert(headSize == 0x68);
auto unk01 = byteswap32(mf.readUint32());
auto unk02 = byteswap32(mf.readUint32()); assert(unk02 == 1);
auto unk03 = byteswap32(mf.readUint32());
auto primitiveType = byteswap32(mf.readUint32()); assert(primitiveType == 6 || primitiveType == 4);
auto unk05 = byteswap32(mf.readUint32());
auto unk06 = byteswap32(mf.readUint32()); assert(unk06 == 0);
auto stride = byteswap32(mf.readUint32()); //assert(unk07 == 32);
auto unk08 = byteswap32(mf.readUint32());
auto unk09 = byteswap32(mf.readUint32()); assert(unk09 == 0);
auto unk10 = byteswap32(mf.readUint32()); assert(unk10 == 0);
auto unk11 = byteswap32(mf.readUint32()); assert(unk11 == 0);
auto unk12 = byteswap32(mf.readUint32()); assert(unk12 == 0);
auto unk13 = byteswap32(mf.readUint32()); assert(unk13 == 0);
auto unk14 = byteswap32(mf.readUint32());
auto numIndices = byteswap32(mf.readUint32());
auto numVertices = byteswap32(mf.readUint32());
auto numIndices2 = byteswap32(mf.readUint32()); assert(numIndices2 == numIndices);
auto unk18 = byteswap32(mf.readUint32()); assert(unk18 == 0);
auto unk19 = byteswap32(mf.readUint32()); assert(unk19 == 0);
auto unk20 = byteswap32(mf.readUint32()); //assert(unk20 == 0);
auto unk21 = byteswap32(mf.readUint32()); assert(unk21 == 0);
auto unk22 = byteswap32(mf.readUint32()); assert(unk22 == 0);
auto unk23 = byteswap32(mf.readUint32()); assert(unk23 == 0);
auto numVertices2 = byteswap32(mf.readUint32()); //assert(numVertices2 == numVertices);
auto unk25 = byteswap32(mf.readUint32()); assert(unk25 == 0);
auto numElements = byteswap32(mf.readUint32());
uint32_t expectedElements = (primitiveType == 6) ? (numIndices - 2) : (numIndices / 3);
assert(numElements == expectedElements);
cvt.numVerts = numVertices;
auto numAttribs = byteswap32(mf.readUint32());
struct Attribute {
uint16_t stream;
uint32_t offset;
uint32_t format;
uint16_t usage, aunk3;
};
std::vector<Attribute> attribs(numAttribs);
for (auto& atb : attribs) {
atb.stream = byteswap16(mf.readUint16());
atb.offset = byteswap16(mf.readUint16());
atb.format = byteswap32(mf.readUint32());
atb.usage = byteswap16(mf.readUint16());
atb.aunk3 = byteswap16(mf.readUint16());
if (atb.stream != 255) {
switch (atb.usage) {
case 0: // D3DDECLUSAGE_POSITION
cvt.flags |= RWGEOFLAG_POSITIONS;
cvt.hasVertices = 1;
cvt.verts.resize(numVertices);
break;
case 3: // D3DDECLUSAGE_NORMAL
cvt.flags |= RWGEOFLAG_NORMALS;
cvt.hasNormals = 1;
cvt.norms.resize(numVertices);
break;
case 5: // D3DDECLUSAGE_TEXCOORD
cvt.flags |= RWGEOFLAG_TEXTURED;
cvt.texSets[0].resize(numVertices);
break;
case 10: // D3DDECLUSAGE_COLOR
cvt.flags |= RWGEOFLAG_PRELIT;
cvt.colors.assign(numVertices, 0xFFFFFFFF);
break;
}
}
}
uint16_t* indexBuffer = (uint16_t*)mf._curptr;
for (uint16_t t = 0; t < numElements; t++) {
Triangle tri;
if (primitiveType == 4) { // triangle list
for (uint16_t c = 0; c < 3; c++)
tri.indices[c] = byteswap16(indexBuffer[3*t + c]);
std::swap(tri.indices[1], tri.indices[2]);
}
else if (primitiveType == 6) { // triangle strip
for (uint16_t c = 0; c < 3; c++)
tri.indices[c] = byteswap16(indexBuffer[t + c]);
if ((t & 1) == 0) std::swap(tri.indices[1], tri.indices[2]);
}
tri.materialId = 0;
cvt.tris.push_back(tri);
cvt.numTris++;
}
mf.seek(numIndices * 2, SEEK_CUR);
auto vUnk1 = byteswap32(mf.readUint32());
auto vUnk2 = byteswap32(mf.readUint32()); assert(vUnk2 == 0);
auto vStride = byteswap32(mf.readUint32()); assert(vStride == stride);
auto vUnk4 = byteswap32(mf.readUint32());
uint8_t* vertexBuffer = (uint8_t*)mf._curptr;
auto fetchAttrib = [](uint32_t format, uint8_t* ptr)->std::array<float, 4> {
float vec[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
switch (format & 63) {
case 6:
for (int c = 0; c < 4; c++)
vec[c] = (float)((uint8_t*)ptr)[c] / 255.0f;
break;
case 25:
if (format & 256)
for (int c = 0; c < 2; c++)
vec[c] = std::max((float)byteswap16(((int16_t*)ptr)[c]) / 32767.0f, -1.0f);
else
for (int c = 0; c < 2; c++)
vec[c] = (float)byteswap16(((uint16_t*)ptr)[c]) / 65535.0f;
break;
case 37:
for (int c = 0; c < 2; c++)
vec[c] = byteswapFlt(((float*)ptr)[c]);
break;
case 57:
for (int c = 0; c < 3; c++)
vec[c] = byteswapFlt(((float*)ptr)[c]);
break;
default:
assert("unknown X360 attribute format");
}
return { vec[0], vec[1], vec[2], vec[3] };
};
for (auto& attrib : attribs) {
if (attrib.stream == 255)
break;
for (size_t i = 0; i < numVertices; i++) {
uint8_t* apnt = vertexBuffer + i * vStride + attrib.offset;
int ftype = attrib.format & 63;
auto vec = fetchAttrib(attrib.format, apnt);
auto vecTuple = std::tie(vec[0], vec[1], vec[2], vec[3]);
if (attrib.usage == 0) { // D3DDECLUSAGE_POSITION
std::tie(cvt.verts[i].x, cvt.verts[i].y, cvt.verts[i].z, std::ignore) = vecTuple;
}
else if (attrib.usage == 3) { // D3DDECLUSAGE_NORMAL
std::tie(cvt.norms[i].x, cvt.norms[i].y, cvt.norms[i].z, std::ignore) = vecTuple;
}
else if (attrib.usage == 5) { // D3DDECLUSAGE_TEXCOORD
std::tie(cvt.texSets[0][i][0], cvt.texSets[0][i][1], std::ignore, std::ignore) = vecTuple;
}
else if (attrib.usage == 10) { // D3DDECLUSAGE_COLOR
uint32_t clr = 0;
for (int c = 0; c < 4; c++)
clr |= (int)(std::clamp(vec[c], 0.0f, 1.0f) * 255.0f) << (c*8);
auto swapRB = [](auto x) {return ((x & 0xFF) << 16) | ((x & 0xFF0000) >> 16) | (x & 0xFF00FF00); };
cvt.colors[i] = swapRB(byteswap32(clr));
}
}
}
/*
printf("------\n");
for (size_t i = 0; i < attribs.size()-1; i++) {
auto& attrib = attribs[i];
printf("%08X %08X (%02i) %04X %04X : ", attrib.offset, attrib.format, attrib.format & 63, attrib.usage, attrib.aunk3);
size_t len = std::min(attribs[i + 1].offset - attribs[i].offset, vStride);
uint8_t* apnt = vertexBuffer + attrib.offset;
for (size_t b = 0; b < len; b++) {
printf(" %02X", apnt[b]);
}
printf("\n");
}
*/
return cvt;
}
void RwTexture::deserialize(File * file)
{
rwCheckHeader(file, 1);
filtering = file->readUint8();
uint8_t addr = file->readUint8();
uAddr = addr & 15; // TODO: Check if uv or vu
vAddr = addr >> 4;
uint16_t rest = file->readUint16();
usesMips = rest & 1;
name = file->readString(rwCheckHeader(file, 2)).c_str();
alphaName = file->readString(rwCheckHeader(file, 2)).c_str();
extensions.read(file, this);
}
void RwTexture::serialize(File * file)
{
HeaderWriter head1, head2;
head1.begin(file, 6);
{
head2.begin(file, 1);
{
file->writeUint8(filtering);
file->writeUint8(uAddr | (vAddr << 4));
file->writeUint16(usesMips ? 1 : 0);
}
head2.end(file);