-
Notifications
You must be signed in to change notification settings - Fork 3
/
EditorInterface.cpp
8370 lines (7965 loc) · 319 KB
/
EditorInterface.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 "EditorInterface.h"
#include "KEnvironment.h"
#include "imgui/imgui.h"
#include "imguiimpl.h"
#include <SDL2/SDL.h>
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <commdlg.h>
#include "rwrenderer.h"
#include "CKDictionary.h"
#include "CKNode.h"
#include "CKGraphical.h"
#include "CKLogic.h"
#include "CKComponent.h"
#include "CKGroup.h"
#include "CKHook.h"
#include <shlobj_core.h>
#include <stb_image_write.h>
#include "rwext.h"
#include <stack>
#include "imgui/ImGuizmo.h"
#include "GameLauncher.h"
#include "Shape.h"
#include "CKService.h"
#include <INIReader.h>
#include "rw.h"
#include "WavDocument.h"
#include "CKCinematicNode.h"
#include "KLocalObject.h"
#include "CKLocalObjectSubs.h"
#include <io.h>
#include "GuiUtils.h"
#include "LocaleEditor.h"
#include "Duplicator.h"
#include <nlohmann/json.hpp>
#include <charconv>
#include <fmt/format.h>
#include <shellapi.h>
#include "imgui/imnodes.h"
#include "CKManager.h"
#include "GameClasses/CKGameX1.h"
#include "GameClasses/CKGameX2.h"
#include "GameClasses/CKGameOG.h"
#include "Encyclopedia.h"
using namespace GuiUtils;
namespace {
const int maxGameSupportingAdvancedBeaconEditing = KEnvironment::KVERSION_XXL1;
template<typename C> std::unique_ptr<RwClump> LoadDFF(const C* filename)
{
std::unique_ptr<RwClump> clump = std::make_unique<RwClump>();
IOFile dff(filename, "rb");
auto rwverBackup = HeaderWriter::rwver; // TODO FIXME hack
rwCheckHeader(&dff, 0x10);
clump->deserialize(&dff);
dff.close();
HeaderWriter::rwver = rwverBackup;
return clump;
}
const char* GetPathFilename(const char* path)
{
const char* ptr = path;
const char* fnd = path;
while (*ptr) {
if (*ptr == '\\' || *ptr == '/')
fnd = ptr + 1;
ptr++;
}
return fnd;
}
std::string GetPathFilenameNoExt(const char* path)
{
const char* fe = GetPathFilename(path);
const char* end = strrchr(fe, '.');
if (end)
return std::string(fe, end);
return std::string(fe);
}
void InvertTextures(KEnvironment &kenv)
{
auto f = [](KObjectList &objlist) {
CTextureDictionary *dict = (CTextureDictionary*)objlist.getClassType<CTextureDictionary>().objects[0];
for (auto &tex : dict->piDict.textures) {
if (uint32_t *pal = tex.images[0].palette.data())
for (size_t i = 0; i < (size_t)(1u << tex.images[0].bpp); i++)
pal[i] ^= 0xFFFFFF;
}
};
f(kenv.levelObjects);
for (KObjectList &ol : kenv.sectorObjects)
f(ol);
}
bool IsNodeInvisible(CKSceneNode *node, bool isXXL2) {
return isXXL2 ? ((node->unk1 & 4) && !(node->unk1 & 0x10)) : (node->unk1 & 2);
}
void DrawSceneNode(CKSceneNode *node, const Matrix &transform, Renderer *gfx, ProGeoCache &geocache, ProTexDict *texdict, CCloneManager *clm, bool showTextures, bool showInvisibles, bool showClones, std::map<CSGBranch*, int> &nodeCloneIndexMap, bool isXXL2)
{
for (; node; node = node->next.get()) {
Matrix nodeTransform = node->transform;
nodeTransform.m[0][3] = nodeTransform.m[1][3] = nodeTransform.m[2][3] = 0.0f;
nodeTransform.m[3][3] = 1.0f;
Matrix globalTransform = nodeTransform * transform;
if (showInvisibles || !IsNodeInvisible(node, isXXL2)) {
if (node->isSubclassOf<CClone>() || node->isSubclassOf<CAnimatedClone>()) {
if (showClones) {
//auto it = std::find_if(clm->_clones.begin(), clm->_clones.end(), [node](const kobjref<CSGBranch> &ref) {return ref.get() == node; });
//assert(it != clm->_clones.end());
//size_t clindex = it - clm->_clones.begin();
int clindex = nodeCloneIndexMap.at((CSGBranch*)node);
gfx->setTransformMatrix(globalTransform);
for (uint32_t part : clm->_team.dongs[clindex].bongs)
if (part != 0xFFFFFFFF) {
RwGeometry *rwgeo = clm->_teamDict._bings[part]._clump.atomic.geometry.get();
geocache.getPro(rwgeo, texdict)->draw(showTextures);
}
}
}
else if (node->isSubclassOf<CNode>()) {
gfx->setTransformMatrix(globalTransform);
for (CKAnyGeometry *kgeo = node->cast<CNode>()->geometry.get(); kgeo; kgeo = kgeo->nextGeo.get()) {
CKAnyGeometry *rgeo = kgeo->duplicateGeo ? kgeo->duplicateGeo.get() : kgeo;
if (auto& rwminiclp = rgeo->clump)
if (RwGeometry *rwgeo = rwminiclp->atomic.geometry.get())
if((rwgeo->flags & RwGeometry::RWGEOFLAG_NATIVE) == 0)
geocache.getPro(rwgeo, texdict)->draw(showTextures);
}
}
if (node->isSubclassOf<CSGBranch>())
DrawSceneNode(node->cast<CSGBranch>()->child.get(), globalTransform, gfx, geocache, texdict, clm, showTextures, showInvisibles, showClones, nodeCloneIndexMap, isXXL2);
if (CAnyAnimatedNode *anyanimnode = node->dyncast<CAnyAnimatedNode>())
DrawSceneNode(anyanimnode->branchs.get(), globalTransform, gfx, geocache, texdict, clm, showTextures, showInvisibles, showClones, nodeCloneIndexMap, isXXL2);
}
}
}
Vector3 getRay(const Camera &cam, Window *window) {
const float zNear = 0.1f;
Vector3 xvec = cam.direction.normal().cross(Vector3(0, 1, 0)).normal();
Vector3 yvec = cam.direction.normal().cross(xvec).normal();
float ys = tan(0.45f) * zNear;
yvec *= ys;
xvec *= ys * window->getWidth() / window->getHeight();
yvec *= (1 - window->getMouseY() * 2.0f / window->getHeight());
xvec *= (1 - window->getMouseX() * 2.0f / window->getWidth());
return cam.direction.normal() * zNear - xvec - yvec;
}
bool rayIntersectsSphere(const Vector3 &rayStart, const Vector3 &_rayDir, const Vector3 &spherePos, float sphereRadius) {
Vector3 rayDir = _rayDir.normal();
Vector3 rs2sp = spherePos - rayStart;
float sphereRadiusSq = sphereRadius * sphereRadius;
if (rs2sp.sqlen3() <= sphereRadiusSq)
return true;
float dot = rayDir.dot(rs2sp);
if (dot < 0.0f)
return false;
Vector3 shortPoint = rayStart + rayDir * dot;
float shortDistSq = (spherePos - shortPoint).sqlen3();
return shortDistSq <= sphereRadiusSq;
}
std::pair<bool, Vector3> getRaySphereIntersection(const Vector3 &rayStart, const Vector3 &_rayDir, const Vector3 &spherePos, float sphereRadius) {
Vector3 rayDir = _rayDir.normal();
Vector3 rs2sp = spherePos - rayStart;
float sphereRadiusSq = sphereRadius * sphereRadius;
if (rs2sp.sqlen3() <= sphereRadiusSq)
return std::make_pair(true, rayStart);
float dot = rayDir.dot(rs2sp);
if (dot < 0.0f)
return std::make_pair(false, Vector3());
Vector3 shortPoint = rayStart + rayDir * dot;
float shortDistSq = (spherePos - shortPoint).sqlen3();
if (shortDistSq > sphereRadiusSq)
return std::make_pair(false, Vector3());
Vector3 ix = shortPoint - rayDir * sqrt(sphereRadiusSq - shortDistSq);
return std::make_pair(true, ix);
}
std::pair<bool, Vector3> getRayTriangleIntersection(const Vector3 &rayStart, const Vector3 &_rayDir, const Vector3 &p1, const Vector3 &p2, const Vector3 &p3) {
Vector3 rayDir = _rayDir.normal();
Vector3 v2 = p2 - p1, v3 = p3 - p1;
Vector3 trinorm = v2.cross(v3).normal(); // order?
if (trinorm == Vector3(0, 0, 0))
return std::make_pair(false, trinorm);
float rayDir_dot_trinorm = rayDir.dot(trinorm);
if (rayDir_dot_trinorm < 0.0f)
return std::make_pair(false, Vector3(0, 0, 0));
float p = p1.dot(trinorm);
float alpha = (p - rayStart.dot(trinorm)) / rayDir_dot_trinorm;
if (alpha < 0.0f)
return std::make_pair(false, Vector3(0,0,0));
Vector3 sex = rayStart + rayDir * alpha;
Vector3 c = sex - p1;
float d = v2.sqlen3() * v3.sqlen3() - v2.dot(v3) * v2.dot(v3);
//assert(d != 0.0f);
float a = (c.dot(v2) * v3.sqlen3() - c.dot(v3) * v2.dot(v3)) / d;
float b = (c.dot(v3) * v2.sqlen3() - c.dot(v2) * v3.dot(v2)) / d;
if (a >= 0.0f && b >= 0.0f && (a + b) <= 1.0f)
return std::make_pair(true, sex);
else
return std::make_pair(false, Vector3(0, 0, 0));
}
bool isPointInAABB(const Vector3 &point, const Vector3 &highCorner, const Vector3 &lowCorner) {
for (int i = 0; i < 3; i++)
if (point.coord[i] < lowCorner.coord[i] || point.coord[i] > highCorner.coord[i])
return false;
return true;
}
std::pair<bool, Vector3> getRayAABBIntersection(const Vector3 &rayStart, const Vector3 &_rayDir, const Vector3 &highCorner, const Vector3 &lowCorner) {
if (isPointInAABB(rayStart, highCorner, lowCorner))
return std::make_pair(true, rayStart);
Vector3 rayDir = _rayDir.normal();
for (int i = 0; i < 3; i++) {
if (rayDir.coord[i] != 0.0f) {
int j = (i + 1) % 3, k = (i + 2) % 3;
for (const std::pair<const Vector3 &, float>& pe : { std::make_pair(highCorner,1.0f), std::make_pair(lowCorner,-1.0f) }) {
if (rayDir.coord[i] * pe.second > 0)
continue;
float t = (pe.first.coord[i] - rayStart.coord[i]) / rayDir.coord[i];
Vector3 candidate = rayStart + rayDir * t;
if (candidate.coord[j] >= lowCorner.coord[j] && candidate.coord[k] >= lowCorner.coord[k] &&
candidate.coord[j] <= highCorner.coord[j] && candidate.coord[k] <= highCorner.coord[k])
return std::make_pair(true, candidate);
}
}
}
return std::make_pair(false, Vector3(0,0,0));
}
void GimmeTheRocketRomans(KEnvironment &kenv) {
using namespace GameX1;
std::map<CKHkBasicEnemy*, CKHkRocketRoman*> hkmap;
for (CKObject *obj : kenv.levelObjects.getClassType<CKHkBasicEnemy>().objects) {
CKHkBasicEnemy *hbe = obj->cast<CKHkBasicEnemy>();
CKHkRocketRoman *hrr = kenv.createObject<CKHkRocketRoman>(-1);
hkmap[hbe] = hrr;
for (auto &ref : hbe->boundingShapes)
ref->object = hrr;
hbe->beBoundNode->object = hrr;
hbe->life->hook = hrr;
// copy
*static_cast<CKHkBasicEnemy*>(hrr) = *hbe;
// Rocket-specific values
CKAACylinder *rrsphere = kenv.createObject<CKAACylinder>(-1);
rrsphere->transform = kenv.levelObjects.getFirst<CSGSectorRoot>()->transform;
rrsphere->radius = 2.0f;
rrsphere->cylinderHeight = 2.0f;
rrsphere->cylinderRadius = 2.0f;
assert(hrr->romanAnimatedClone == hrr->romanAnimatedClone2 && hrr->romanAnimatedClone3 == hrr->node && hrr->node == hrr->romanAnimatedClone);
hrr->romanAnimatedClone2->insertChild(rrsphere);
//hrr->rrCylinderNode = rrsphere;
hrr->rrCylinderNode = hrr->boundingShapes[3]->cast<CKAACylinder>();
hrr->boundingShapes[3] = rrsphere;
CKSoundDictionaryID *sdid = kenv.createObject<CKSoundDictionaryID>(-1);
sdid->soundEntries.resize(32); // add 32 default (empty) sounds
int sndid = 0;
for (auto& se : sdid->soundEntries) {
se.active = true;
se.id = sndid++;
se.flags = 16;
se.obj = hrr->node.get();
}
hrr->rrSoundDictID = sdid;
hrr->rrParticleNode = kenv.levelObjects.getFirst<CKCrateCpnt>()->particleNode.get();
CAnimationDictionary* animDict = kenv.createAndInitObject<CAnimationDictionary>();
hrr->rrAnimDict = animDict;
animDict->numAnims = 4;
animDict->animIndices.resize(animDict->numAnims);
for (int i = 0; i < animDict->numAnims; ++i)
animDict->animIndices[i] = hrr->beAnimDict->animIndices[i];
}
for (CKObject *obj : kenv.levelObjects.getClassType<CKHkBasicEnemy>().objects) {
CKHkBasicEnemy *hbe = obj->cast<CKHkBasicEnemy>();
CKHkRocketRoman *hrr = hkmap[hbe];
if(hbe->next.get())
hrr->next = hkmap[(CKHkBasicEnemy*)hbe->next.get()];
hbe->next.reset();
}
CKSrvCollision *col = kenv.levelObjects.getFirst<CKSrvCollision>();
for (auto &ref : col->objs2)
if (ref->getClassFullID() == CKHkBasicEnemy::FULL_ID)
ref = hkmap[ref->cast<CKHkBasicEnemy>()];
for (CKObject *obj : kenv.levelObjects.getClassType<CKGrpSquadEnemy>().objects) {
CKGrpSquadEnemy *gse = obj->cast<CKGrpSquadEnemy>();
for (auto &pe : gse->pools) {
if (pe.cpnt->getClassFullID() == CKBasicEnemyCpnt::FULL_ID) {
CKBasicEnemyCpnt *becpnt = pe.cpnt->cast<CKBasicEnemyCpnt>();
CKRocketRomanCpnt *rrcpnt = kenv.createObject<CKRocketRomanCpnt>(-1);
*(CKBasicEnemyCpnt*)rrcpnt = *becpnt;
//....
rrcpnt->rrCylinderRadius = 1.0f;
rrcpnt->rrCylinderHeight = 1.0f;
rrcpnt->rrUnk3 = Vector3(1.0f, 1.0f, 1.0f);
rrcpnt->rrUnk4 = 0;
rrcpnt->rrFireDistance = 3.0f;
rrcpnt->rrUnk6 = 0;
rrcpnt->rrFlySpeed = 5.0f;
rrcpnt->rrRomanAimFactor = 10.0f;
rrcpnt->rrUnk9 = kenv.levelObjects.getClassType(2, 28).objects[0]; // Asterix Hook
//
pe.cpnt = rrcpnt;
kenv.removeObject(becpnt);
}
}
}
for (CKObject *obj : kenv.levelObjects.getClassType<CKGrpPoolSquad>().objects) {
CKGrpPoolSquad *pool = obj->cast<CKGrpPoolSquad>();
if (pool->childHook.get())
if(pool->childHook->getClassFullID() == CKHkBasicEnemy::FULL_ID)
pool->childHook = hkmap[pool->childHook->cast<CKHkBasicEnemy>()];
}
for (auto &ent : hkmap) {
if (ent.first)
kenv.removeObject(ent.first);
}
//col->objs.clear();
//col->objs2.clear();
//col->bings.clear();
//col->unk1 = 0;
//col->unk2 = 0;
kenv.levelObjects.getClassType<CKHkRocketRoman>().info = kenv.levelObjects.getClassType<CKHkBasicEnemy>().info;
kenv.levelObjects.getClassType<CKHkBasicEnemy>().info = 0;
kenv.levelObjects.getClassType<CKRocketRomanCpnt>().info = kenv.levelObjects.getClassType<CKBasicEnemyCpnt>().info;
kenv.levelObjects.getClassType<CKBasicEnemyCpnt>().info = 0;
}
bool audioInitDone = false;
SDL_AudioDeviceID audiodevid;
int audioLastFreq = 0;
void InitSnd(int freq, bool byteSwapped) {
if (audioInitDone && audioLastFreq == freq) {
SDL_ClearQueuedAudio(audiodevid);
return;
}
if (audioInitDone) {
SDL_ClearQueuedAudio(audiodevid);
SDL_CloseAudioDevice(audiodevid);
}
SDL_AudioSpec spec, have;
memset(&spec, 0, sizeof(spec));
spec.freq = freq;
spec.format = byteSwapped ? AUDIO_S16MSB : AUDIO_S16LSB;
spec.channels = 1;
spec.samples = 4096;
audiodevid = SDL_OpenAudioDevice(NULL, 0, &spec, &have, 0);
assert(audiodevid);
SDL_PauseAudioDevice(audiodevid, 0);
audioInitDone = true;
audioLastFreq = freq;
}
void PlaySnd(KEnvironment &kenv, RwSound &snd) {
InitSnd(snd.info.dings[0].sampleRate, kenv.platform == KEnvironment::PLATFORM_X360 || kenv.platform == KEnvironment::PLATFORM_PS3);
SDL_QueueAudio(audiodevid, snd.data.data.data(), snd.data.data.size());
}
RwClump CreateClumpFromGeo(std::shared_ptr<RwGeometry> rwgeo, RwExtHAnim *hanim = nullptr) {
RwClump clump;
RwFrame frame;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++)
frame.matrix[i][j] = (i == j) ? 1.0f : 0.0f;
frame.index = 0xFFFFFFFF;
frame.flags = 0;
clump.frameList.frames.push_back(frame);
clump.frameList.extensions.emplace_back();
clump.geoList.geometries.push_back(rwgeo);
RwAtomic& atom = clump.atomics.emplace_back();
atom.frameIndex = 0;
atom.geoIndex = 0;
atom.flags = 5;
atom.unused = 0;
if (hanim) {
frame.index = 0;
clump.frameList.frames.push_back(frame);
RwsExtHolder freh;
auto haclone = hanim->clone();
((RwExtHAnim*)haclone.get())->nodeId = hanim->bones[0].nodeId;
freh.exts.push_back(std::move(haclone));
clump.frameList.extensions.push_back(std::move(freh));
std::stack<uint32_t> parBoneStack;
parBoneStack.push(0);
uint32_t parBone = 0;
std::vector<std::pair<uint32_t, uint32_t>> bones;
for (uint32_t i = 1; i < hanim->bones.size(); i++) {
auto &hb = hanim->bones[i];
assert(hb.nodeIndex == i);
bones.push_back(std::make_pair(hb.nodeId, parBone));
if (hb.flags & 2)
parBoneStack.push(parBone);
parBone = i;
if (hb.flags & 1) {
parBone = parBoneStack.top();
parBoneStack.pop();
}
}
for (auto &bn : bones) {
frame.index = bn.second + 1;
clump.frameList.frames.push_back(frame);
auto bha = std::make_unique<RwExtHAnim>();
bha->version = 0x100;
bha->nodeId = bn.first;
RwsExtHolder reh;
reh.exts.push_back(std::move(bha));
clump.frameList.extensions.push_back(std::move(reh));
}
}
return clump;
}
RwGeometry createEmptyGeo() {
RwGeometry geo;
geo.flags = RwGeometry::RWGEOFLAG_POSITIONS;
geo.numVerts = 3;
geo.numTris = 1;
geo.numMorphs = 1;
RwGeometry::Triangle tri;
tri.indices = { 0,1,2 };
tri.materialId = 0;
geo.tris = { std::move(tri) };
geo.spherePos = Vector3(0, 0, 0);
geo.sphereRadius = 0;
geo.hasVertices = 1;
geo.hasNormals = 0;
geo.verts = { Vector3(0,0,0), Vector3(0,0,0), Vector3(0,0,0) };
geo.materialList.slots = { 0xFFFFFFFF };
RwMaterial mat;
mat.flags = 0;
mat.color = 0xFFFFFFFF;
mat.unused = 0;
mat.isTextured = 0;
mat.ambient = mat.specular = mat.diffuse = 1.0f;
geo.materialList.materials = { std::move(mat) };
return geo;
}
ImVec4 getPFCellColor(uint8_t val) {
ImVec4 color(1, 0, 1, 1);
switch (val) {
case 0: color = ImVec4(0, 1, 1, 1); break; // enemy
case 1: color = ImVec4(1, 1, 1, 1); break; // partner + enemy
case 4: color = ImVec4(1, 1, 0, 1); break; // partner
case 7: color = ImVec4(1, 0, 0, 1); break; // wall
}
return color;
}
void ImportGroundOBJ(KEnvironment &kenv, const std::filesystem::path& filename, int sector) {
KObjectList& objlist = (sector == -1) ? kenv.levelObjects : kenv.sectorObjects[sector];
CKMeshKluster* kluster = objlist.getFirst<CKMeshKluster>();
CKSector* ksector = kenv.levelObjects.getClassType<CKSector>().objects[sector + 1]->cast<CKSector>();
std::map<std::string, CGround*> groundMap;
for (auto& gnd : kluster->grounds) {
if (!gnd->isSubclassOf<CDynamicGround>()) {
groundMap[kenv.getObjectName(gnd.get())] = gnd.get();
}
}
FILE *wobj;
fsfopen_s(&wobj, filename, "rt");
if (!wobj) return;
char line[512]; char* context = nullptr; const char* const spaces = " \t\r\n";
std::vector<Vector3> positions;
std::vector<CGround::Triangle> triangles; // change int16 to int32 ??
std::vector<std::array<int, 4>> walls;
std::set<int> floorIndices; // in if vertex index used in some ground floor, not in if only used in walls
CGround* currentGround = nullptr;
std::string nextGroundName;
auto flushTriangles = [&positions, &triangles, &kenv, §or, ¤tGround, kluster, ksector, &nextGroundName, &walls, &floorIndices]() {
if (!triangles.empty()) {
CGround* gnd = currentGround;
if (!gnd) {
gnd = kenv.createObject<CGround>(sector);
kluster->grounds.emplace_back(gnd);
kenv.setObjectName(gnd, std::move(nextGroundName));
gnd->x2sectorObj = ksector;
}
gnd->vertices.clear();
gnd->triangles.clear();
gnd->aabb = {};
gnd->finiteWalls.clear();
gnd->infiniteWalls.clear();
std::map<int, int> idxmap;
uint16_t nextIndex = 0;
for (auto &tri : triangles) {
CGround::Triangle cvtri;
for (int c = 0; c < 3; c++) {
int objIndex = tri.indices[c];
int cvIndex;
const Vector3 &objPos = positions[objIndex];
auto pmit = idxmap.find(objIndex);
if (pmit == idxmap.end()) {
idxmap[objIndex] = nextIndex;
gnd->vertices.push_back(objPos);
cvIndex = nextIndex++;
}
else {
cvIndex = pmit->second;
}
cvtri.indices[c] = cvIndex;
}
gnd->triangles.push_back(std::move(cvtri));
}
for (auto& wall : walls) {
auto sorted = wall;
size_t cnt = std::count_if(sorted.begin(), sorted.end(), [&floorIndices](int x) {return floorIndices.count(x); });
if (cnt == 2) {
// sorting after the inclusion of index in floorIndices first, and those that aren't
std::sort(sorted.begin(), sorted.end(), [&floorIndices](int a, int b) {return floorIndices.count(a) > floorIndices.count(b); });
}
else {
// sorting after the height of the vertices, first the bottom of the wall which becomes the base, then the top
std::sort(sorted.begin(), sorted.end(), [&positions](int a, int b) {return positions[a].y < positions[b].y; });
}
// after sorting, sorted[0] and sorted[1] are the base of the wall, sorted[2] and sorted[3] are the top/bottom of wall
int oriindex0 = std::find(wall.begin(), wall.end(), sorted[0]) - wall.begin();
int oriindex1 = std::find(wall.begin(), wall.end(), sorted[1]) - wall.begin();
// swap to keep order and front/backface
if (((oriindex1 - oriindex0) & 3) == 3) {
std::swap(sorted[0], sorted[1]);
}
// swap so that sorted[0] and [2] are base and top/bottom corresponding to each other, on same XZ
float swap_no_dist = (positions[sorted[2]] - positions[sorted[0]]).len2xz() + (positions[sorted[3]] - positions[sorted[1]]).len2xz();
float swap_yes_dist = (positions[sorted[3]] - positions[sorted[0]]).len2xz() + (positions[sorted[2]] - positions[sorted[1]]).len2xz();
if (swap_yes_dist < swap_no_dist) {
std::swap(sorted[2], sorted[3]);
}
CGround::FiniteWall finWall;
for (int c = 0; c < 2; c++) {
int objIndex = sorted[c];
int cvIndex;
const Vector3& objPos = positions[objIndex];
auto pmit = idxmap.find(objIndex);
if (pmit == idxmap.end()) {
idxmap[objIndex] = nextIndex;
gnd->vertices.push_back(objPos);
cvIndex = nextIndex++;
}
else {
cvIndex = pmit->second;
}
finWall.baseIndices[c] = cvIndex;
}
finWall.heights[0] = positions[sorted[2]].y - positions[sorted[0]].y;
finWall.heights[1] = positions[sorted[3]].y - positions[sorted[1]].y;
// flip wall except for walls with negative heights
if (!(finWall.heights[0] < 0.0f && finWall.heights[1] < 0.0f)) {
std::swap(finWall.baseIndices[0], finWall.baseIndices[1]);
std::swap(finWall.heights[0], finWall.heights[1]);
}
gnd->finiteWalls.push_back(std::move(finWall));
}
gnd->aabb = AABoundingBox(gnd->vertices[0]);
for (Vector3 &vec : gnd->vertices) {
gnd->aabb.mergePoint(vec);
}
AABoundingBox safeaabb = gnd->aabb;
safeaabb.highCorner.y += 10.0f;
safeaabb.lowCorner.y -= 5.0f;
kluster->aabb.merge(safeaabb);
ksector->boundaries.merge(safeaabb);
// Compute negative height extension (param3)
float minheight = gnd->aabb.lowCorner.y;
for (auto& wall : gnd->finiteWalls) {
float h0 = gnd->vertices[wall.baseIndices[0]].y + wall.heights[0];
float h1 = gnd->vertices[wall.baseIndices[1]].y + wall.heights[1];
minheight = std::min({ minheight, h0, h1 });
}
gnd->param3 = minheight - gnd->aabb.lowCorner.y;
}
currentGround = nullptr;
triangles.clear();
walls.clear();
floorIndices.clear();
};
while (!feof(wobj)) {
fgets(line, 511, wobj);
std::string word = strtok_s(line, spaces, &context);
if (word == "o") {
flushTriangles();
std::string name = strtok_s(NULL, spaces, &context);
auto it = groundMap.find(name);
if (it != groundMap.end())
currentGround = it->second;
else
nextGroundName = std::move(name);
}
else if (word == "v") {
Vector3 vec;
for (float &coord : vec) {
coord = std::strtof(strtok_s(NULL, spaces, &context), nullptr);
}
positions.push_back(vec);
}
else if (word == "f") {
std::vector<uint16_t> face;
while (char *arg = strtok_s(NULL, spaces, &context)) {
int index = 1;
sscanf_s(arg, "%i", &index);
if (index < 0) index += positions.size();
else index -= 1;
face.push_back(index);
}
bool isWall = false;
if (face.size() == 4) {
Vector3 v1 = positions[face[0]] - positions[face[2]];
Vector3 v2 = positions[face[1]] - positions[face[3]];
Vector3 norm = v1.cross(v2).normal();
if (std::abs(norm.dot(Vector3(0, 1, 0))) < 0.001f) {
// It's a wall!
walls.push_back({ face[0], face[1], face[2], face[3] });
isWall = true;
}
}
if (!isWall) {
// It's a ground!
for (size_t i = 2; i < face.size(); i++) {
CGround::Triangle tri;
tri.indices = { face[0], face[i - 1], face[i] };
triangles.push_back(std::move(tri));
}
for (auto& index : face) {
floorIndices.insert(index);
}
}
}
}
flushTriangles();
fclose(wobj);
}
void IGObjectNameInput(const char* label, CKObject* obj, KEnvironment& kenv) {
std::string* pstr = nullptr;
auto it = kenv.globalObjNames.dict.find(obj);
if (it != kenv.globalObjNames.dict.end())
pstr = &it->second.name;
else {
it = kenv.levelObjNames.dict.find(obj);
if (it != kenv.levelObjNames.dict.end())
pstr = &it->second.name;
else {
for (auto& str : kenv.sectorObjNames) {
it = str.dict.find(obj);
if (it != str.dict.end())
pstr = &it->second.name;
}
}
}
if (pstr) {
ImGui::InputText(label, pstr->data(), pstr->capacity() + 1, ImGuiInputTextFlags_CallbackResize, IGStdStringInputCallback, pstr);
}
else {
char test[2] = { 0,0 };
void* user[2] = { obj, &kenv };
ImGui::InputText(label, test, 1, ImGuiInputTextFlags_CallbackResize,
[](ImGuiInputTextCallbackData* data) -> int {
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
void** user = (void**)data->UserData;
CKObject* obj = (CKObject*)user[0];
KEnvironment* kenv = (KEnvironment*)user[1];
auto& info = kenv->makeObjInfo(obj);
info.name.resize(data->BufTextLen);
data->Buf = info.name.data();
}
return 0;
}, user);
}
}
void IGStringInput(const char* label, std::string& str) {
ImGui::InputText(label, str.data(), str.capacity() + 1, ImGuiInputTextFlags_CallbackResize, IGStdStringInputCallback, &str);
}
void IGLink(const char* text, const wchar_t* url, Window* window = nullptr) {
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 box = ImGui::CalcTextSize(text);
uint32_t color = 0xFFFA870F;
if (ImGui::InvisibleButton(text, box)) {
ShellExecuteW(window ? (HWND)window->getNativeWindow() : nullptr, NULL, url, NULL, NULL, SW_SHOWNORMAL);
}
if (ImGui::IsItemHovered()) {
color = 0xFFFFC74F;
ImGui::SetTooltip("%S", url);
}
float ly = pos.y + box.y;
ImDrawList* drawList = ImGui::GetWindowDrawList();
drawList->AddText(pos, color, text);
drawList->AddLine(ImVec2(pos.x, ly), ImVec2(pos.x + box.x, ly), color);
};
static const char* beaconX1Names[] = {
// 0x00
"*", "*", "*", "Wooden Crate", "Metal Crate", "Simple", "Helmet", "Golden Helmet",
// 0x08
"Potion", "Shield", "Ham", "x3 Multiplier", "x10 Multiplier", "Laurel", "Boar", "Water flow",
// 0x10
"Merchant", "*", "*", "*", "*", "Save point", "Respawn point", "Hero respawn pos",
// 0x18
"?", "?", "X2 Potion", "X2 Helmet", "X2 x3 Multiplier", "X2 x10 Multiplier", "X2 Ham", "X2 Shield",
// 0x20
"X2 Golden Helmet", "X2 Diamond Helmet", "?", "?", "?", "?", "X2 Enemy spawn", "X2 Marker",
// 0x28
"?", "?", "X2 Food Basket", "?", "?", "Ar Egg", "Ar Burried Surprise", "?",
// 0x30
"?", "?", "?", "?", "?", "?", "?", "?",
// 0x38
"?", "?", "?", "?", "?", "Ar Eggbag", "?", "?",
// 0x40
"OG Helmet", "OG Golden Helmet", "OG Glue", "OG Powder", "OG x3 Multiplier", "OG x10 Multiplier", "OG Ham", "OG Shield",
// 0x48
"OG Potion", "OG Bird Cage", "?", "?", "?", "?", "?", "?",
};
static const char* beaconX1RomasterNames[] = {
// 0x00
"*", "*", "*", "Wooden Crate", "Metal Crate", "?", "Helmet", "Golden Helmet",
// 0x08
"Potion", "Shield", "Ham", "x3 Multiplier", "x10 Multiplier", "Laurel", "Boar", "Water flow",
// 0x10
"Merchant", "Retro Coin", "Remaster Coin", "*", "*", "Save point", "Respawn point", "Hero respawn pos",
// 0x18
"?", "?", "Freeze Crate 1", "Freeze Crate 3", "Freeze Crate 5",
};
static auto getBeaconName = [](KEnvironment& kenv, int handlerId) -> const char* {
if (kenv.version <= kenv.KVERSION_XXL1 && kenv.isRemaster && handlerId < std::extent<decltype(beaconX1RomasterNames)>::value)
return beaconX1RomasterNames[handlerId];
if (handlerId < std::extent<decltype(beaconX1Names)>::value)
return beaconX1Names[handlerId];
return "!";
};
void ChangeNodeGeometry(KEnvironment& kenv, CNode* geonode, RwGeometry** rwgeos, size_t numRwgeos) {
// Remove current geometry
// TODO: Proper handling of duplicate geometries
CKAnyGeometry* kgeo = geonode->geometry.get();
CLightSet* lightSetBackup = kgeo ? kgeo->lightSet.get() : nullptr;
geonode->geometry.reset();
while (kgeo) {
if (CMaterial* mat = kgeo->material.get()) {
kgeo->material.reset();
if (mat->getRefCount() == 0)
kenv.removeObject(mat);
}
CKAnyGeometry* next = kgeo->nextGeo.get();
kenv.removeObject(kgeo);
kgeo = next;
}
// Create new geometry
CKAnyGeometry* prevgeo = nullptr;
for (size_t g = 0; g < numRwgeos; ++g) {
RwGeometry* rwgeotot = rwgeos[g];
auto splitgeos = rwgeotot->splitByMaterial();
for (auto& rwgeo : splitgeos) {
if (rwgeo->tris.empty())
continue;
rwgeo->flags &= ~0x60;
rwgeo->materialList.materials[0].color = 0xFFFFFFFF;
// Create BinMeshPLG extension for RwGeo
auto bmplg = std::make_unique<RwExtBinMesh>();
bmplg->flags = 0;
bmplg->totalIndices = rwgeo->numTris * 3;
bmplg->meshes.emplace_back();
RwExtBinMesh::Mesh& bmesh = bmplg->meshes.front();
bmesh.material = 0;
for (const auto& tri : rwgeo->tris) {
bmesh.indices.push_back(tri.indices[0]);
bmesh.indices.push_back(tri.indices[2]);
bmesh.indices.push_back(tri.indices[1]);
}
rwgeo->extensions.exts.push_back(std::move(bmplg));
// Create MatFX extension for RwAtomic
std::unique_ptr<RwExtUnknown> fxaext = nullptr;
if (rwgeo->materialList.materials[0].extensions.find(0x120)) {
fxaext = std::make_unique<RwExtUnknown>();
fxaext->_type = 0x120;
fxaext->_length = 4;
fxaext->_ptr = malloc(4);
uint32_t one = 1;
memcpy(fxaext->_ptr, &one, 4);
}
int sector = kenv.getObjectSector(geonode);
CKAnyGeometry* newgeo;
if (geonode->isSubclassOf<CAnimatedNode>())
newgeo = kenv.createObject<CKSkinGeometry>(sector);
else
newgeo = kenv.createObject<CKGeometry>(sector);
kenv.setObjectName(newgeo, "XE Geometry");
if (prevgeo) prevgeo->nextGeo = kobjref<CKAnyGeometry>(newgeo);
else geonode->geometry.reset(newgeo);
prevgeo = newgeo;
newgeo->flags = 1;
newgeo->flags2 = 0;
newgeo->clump = std::make_shared<RwMiniClump>();
newgeo->clump->atomic.flags = 5;
newgeo->clump->atomic.unused = 0;
newgeo->clump->atomic.geometry = std::move(rwgeo);
if (fxaext)
newgeo->clump->atomic.extensions.exts.push_back(std::move(fxaext));
// Create material for XXL2+
if (kenv.version >= kenv.KVERSION_XXL2) {
CMaterial* mat = kenv.createObject<CMaterial>(sector);
kenv.setObjectName(mat, "XE Material");
mat->geometry = newgeo;
mat->flags = 0x10;
newgeo->material = mat;
newgeo->lightSet = lightSetBackup;
}
}
}
}
void InitImNodes() {
static bool ImNodesInitialized = false;
if (!ImNodesInitialized) {
ImNodes::CreateContext();
ImNodes::GetIO().AltMouseButton = ImGuiMouseButton_Right;
ImNodes::GetIO().EmulateThreeButtonMouse.Modifier = &ImGui::GetIO().KeyAlt;
ImNodes::GetIO().LinkDetachWithModifierClick.Modifier = &ImGui::GetIO().KeyCtrl;
ImNodesInitialized = true;
}
}
bool IGU32Color(const char* name, uint32_t& color) {
ImVec4 cf = ImGui::ColorConvertU32ToFloat4(color);
if (ImGui::ColorEdit4(name, &cf.x)) {
color = ImGui::ColorConvertFloat4ToU32(cf);
return true;
}
return false;
}
void AnimDictEditor(EditorInterface& ui, CAnimationDictionary* animDict, bool showHeader = true) {
CAnimationManager* animMgr = ui.kenv.levelObjects.getFirst<CAnimationManager>();
ImGui::PushID(animDict);
ImGui::Indent();
if (!showHeader || ImGui::CollapsingHeader("Animation Dictionary")) {
ImGui::BeginChild("AnimDictEdit", ImVec2(0, 250.0f), true);
ImGui::Columns(animDict->numSets); // TODO: correct order for Arthur sets
for (size_t i = 0; i < animDict->animIndices.size(); ++i) {
ImGui::PushID(i);
ImGui::AlignTextToFramePadding();
uint32_t animFullIndex = animDict->animIndices[i];
uint32_t animSector = animFullIndex >> 24;
uint32_t animIndex = animFullIndex & 0xFFFFFF;
CSectorAnimation* secAnim = (animFullIndex == -1) ? nullptr : (ui.kenv.version < KEnvironment::KVERSION_ARTHUR) ? &animMgr->commonAnims : animMgr->arSectors[animSector].get();
if ((i % animDict->numSets) == 0) {
ImGui::Text("%2i:", (uint32_t)i / animDict->numSets);
ImGui::SameLine();
}
ImGui::BeginDisabled(animFullIndex == -1);
if (ImGui::ArrowButton("Play", ImGuiDir_Right)) {
ui.selectedAnimationIndex = animIndex;
ui.selectedAnimationSector = animSector;
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Show in Anim viewer");
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button("A")) {
auto anmpath = GuiUtils::OpenDialogBox(ui.g_window, "Renderware Animation (*.anm)\0*.ANM\0\0", "anm");
if (!anmpath.empty()) {
IOFile file = IOFile(anmpath.c_str(), "rb");
RwAnimAnimation rwAnim;
auto rwVerBackup = HeaderWriter::rwver; // TODO: Remove hack
rwCheckHeader(&file, 0x1B);
rwAnim.deserialize(&file);
HeaderWriter::rwver = rwVerBackup;
int32_t newIndex = animMgr->addAnimation(rwAnim, animDict->arSector);
animDict->animIndices[i] = newIndex;
}
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Import from .ANM (unique)");
ImGui::SameLine();
ImGui::BeginDisabled(animFullIndex == -1);
if (ImGui::Button("I")) {
auto anmpath = GuiUtils::OpenDialogBox(ui.g_window, "Renderware Animation (*.anm)\0*.ANM\0\0", "anm");
if (!anmpath.empty()) {
IOFile file = IOFile(anmpath.c_str(), "rb");
RwAnimAnimation& rwAnim = secAnim->anims[animIndex].rwAnim;
rwAnim = {};
auto rwVerBackup = HeaderWriter::rwver; // TODO: Remove hack
rwCheckHeader(&file, 0x1B);
rwAnim.deserialize(&file);
HeaderWriter::rwver = rwVerBackup;
}
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Import from .ANM (shared)");
ImGui::SameLine();
if (ImGui::Button("E")) {
auto anmpath = GuiUtils::SaveDialogBox(ui.g_window, "Renderware Animation (*.anm)\0*.ANM\0\0", "anm");
if (!anmpath.empty()) {
IOFile file = IOFile(anmpath.c_str(), "wb");
RwAnimAnimation& rwAnim = secAnim->anims[animIndex].rwAnim;
rwAnim.serialize(&file);
}
}
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Export to .ANM");
ImGui::SameLine();
if (animFullIndex != -1)
ImGui::Text("Sec %2u, Index %3u", animSector, animIndex);
else
ImGui::TextUnformatted("None");
ImGui::EndDisabled();
ImGui::PopID();
ImGui::NextColumn();
}
ImGui::Columns(1);
if (ImGui::Button("New slot")) {
for (uint32_t i = 0; i < animDict->numSets; ++i) {
animDict->animIndices.emplace_back(-1);
}
animDict->numAnims += 1;
}
ImGui::EndChild();
}
ImGui::Unindent();
ImGui::PopID();
}
bool PropFlagsEditor(unsigned int& flagsValue, const nlohmann::json& flagsInfo) {
bool modified = false;
for (auto& [key, jsobj] : flagsInfo.items()) {
auto sep = key.find('-');
int bitStartIndex = 0, bitEndIndex = 0;
if (sep == key.npos) {
bitStartIndex = bitEndIndex = std::stoi(key);
}
else {
std::from_chars(key.data(), key.data() + sep, bitStartIndex);
std::from_chars(key.data() + sep + 1, key.data() + key.size(), bitEndIndex);
}
unsigned int mask = ((1 << (bitEndIndex - bitStartIndex + 1)) - 1) << bitStartIndex;
if (jsobj.is_string()) {
const auto& name = jsobj.get_ref<const std::string&>();
if (bitStartIndex == bitEndIndex) {
modified |= ImGui::CheckboxFlags(name.c_str(), &flagsValue, 1 << bitStartIndex);
}
else {
unsigned int v = (flagsValue & mask) >> bitStartIndex;
ImGui::SetNextItemWidth(48.0f);
bool b = ImGui::InputScalar(name.c_str(), ImGuiDataType_U32, &v);
if (b) {
modified = true;
flagsValue = (flagsValue & ~mask) | ((v << bitStartIndex) & mask);
}
}
}
else if (jsobj.is_object()) {
unsigned int v = (flagsValue & mask) >> bitStartIndex;
const auto& name = jsobj.at("name").get_ref<const std::string&>();
std::string preview = std::to_string(v);
if (auto it = jsobj.find(preview); it != jsobj.end())
preview = it->get_ref<const std::string&>();
bool b = false;
if (ImGui::BeginCombo(name.c_str(), preview.c_str())) {
b |= ImGui::InputScalar("Value", ImGuiDataType_U32, &v);
for (auto& [ek, ev] : jsobj.items()) {
if (ek != "name") {