-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathfbx_importer.cpp
1433 lines (1241 loc) · 45.8 KB
/
fbx_importer.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 "fbx_importer.h"
#include "animation/animation.h"
#include "editor/asset_compiler.h"
#include "editor/studio_app.h"
#include "editor/world_editor.h"
#include "core/atomic.h"
#include "core/crt.h"
#include "engine/engine.h"
#include "engine/file_system.h"
#include "core/hash.h"
#include "core/job_system.h"
#include "core/log.h"
#include "core/math.h"
#include "core/os.h"
#include "core/path.h"
#include "core/stack_array.h"
#include "engine/prefab.h"
#include "core/profiler.h"
#include "engine/resource_manager.h"
#include "engine/world.h"
#include "meshoptimizer/meshoptimizer.h"
#include "mikktspace/mikktspace.h"
#include "openfbx/ofbx.h"
#include "physics/physics_resources.h"
#include "physics/physics_module.h"
#include "physics/physics_system.h"
#include "renderer/draw_stream.h"
#include "renderer/editor/model_importer.h"
#include "renderer/editor/model_meta.h"
#include "renderer/material.h"
#include "renderer/model.h"
#include "renderer/pipeline.h"
#include "renderer/render_module.h"
#include "renderer/renderer.h"
#include "renderer/shader.h"
namespace Lumix {
namespace {
struct FBXImportGeometry {
const ofbx::GeometryData* geom;
const ofbx::Mesh* mesh;
i32 bone_idx = -1;
};
struct GeomPartition {
const ofbx::GeometryData* geom;
u32 partition;
u32 material;
bool flip_handness;
bool operator==(const GeomPartition& rhs) const {
return geom == rhs.geom
&& partition == rhs.partition
&& material == rhs.material
&& flip_handness == rhs.flip_handness;
}
};
}
template<> struct HashFunc<GeomPartition> {
static u32 get(const GeomPartition& k) {
return k.partition ^ k.material ^ u32(u64(k.geom)) ^ u32(u64(k.geom) >> 32);
}
};
struct FBXImporter : ModelImporter {
struct Skin {
float weights[4];
i16 joints[4];
int count = 0;
};
struct VertexLayout {
i32 size = -1;
i32 normal_offset = -1;
i32 uv_offset = -1;
i32 tangent_offset = -1;
};
enum class Orientation {
Y_UP,
Z_UP,
Z_MINUS_UP,
X_MINUS_UP,
X_UP
};
FBXImporter(StudioApp& app, IAllocator& allocator)
: ModelImporter(app)
, m_allocator(allocator)
, m_scene(nullptr)
, m_fbx_meshes(m_allocator)
{}
~FBXImporter()
{
if (m_scene) m_scene->destroy();
if (m_impostor_shadow_shader) m_impostor_shadow_shader->decRefCount();
}
static StringView toStringView(ofbx::DataView data) {
return StringView(
(const char*)data.begin,
(const char*)data.end
);
}
static bool isConstCurve(const ofbx::AnimationCurve* curve) {
if (!curve) return true;
if (curve->getKeyCount() <= 1) return true;
const float* values = curve->getKeyValue();
if (curve->getKeyCount() == 2 && fabsf(values[1] - values[0]) < 1e-6) return true;
return false;
}
static Vec3 toLumixVec3(const ofbx::DVec3& v) { return {(float)v.x, (float)v.y, (float)v.z}; }
static Vec3 toLumixVec3(const ofbx::FVec3& v) { return {(float)v.x, (float)v.y, (float)v.z}; }
static Matrix toLumix(const ofbx::DMatrix& mtx) {
Matrix res;
for (int i = 0; i < 16; ++i) (&res.columns[0].x)[i] = (float)mtx.m[i];
return res;
}
static u32 packColor(const ofbx::Vec4& vec) {
const i8 xx = i8(clamp((vec.x * 0.5f + 0.5f) * 255, 0.f, 255.f) - 128);
const i8 yy = i8(clamp((vec.y * 0.5f + 0.5f) * 255, 0.f, 255.f) - 128);
const i8 zz = i8(clamp((vec.z * 0.5f + 0.5f) * 255, 0.f, 255.f) - 128);
const i8 ww = i8(clamp((vec.w * 0.5f + 0.5f) * 255, 0.f, 255.f) - 128);
union {
u32 ui32;
i8 arr[4];
} un;
un.arr[0] = xx;
un.arr[1] = yy;
un.arr[2] = zz;
un.arr[3] = ww;
return un.ui32;
}
static bool doesFlipHandness(const Matrix& mtx) {
Vec3 x(1, 0, 0);
Vec3 y(0, 1, 0);
Vec3 z = mtx.inverted().transformVector(cross(mtx.transformVector(x), mtx.transformVector(y)));
return z.z < 0;
}
static bool hasTangents(const ofbx::GeometryData& geom) {
if (geom.getTangents().values) return true;
if (geom.getUVs().values) return true;
return false;
}
static int getVertexSize(const ofbx::GeometryData& geom, bool is_skinned, const ModelMeta& meta) {
static const int POSITION_SIZE = sizeof(float) * 3;
static const int NORMAL_SIZE = sizeof(u8) * 4;
static const int TANGENT_SIZE = sizeof(u8) * 4;
static const int UV_SIZE = sizeof(float) * 2;
static const int COLOR_SIZE = sizeof(u8) * 4;
static const int AO_SIZE = sizeof(u8) * 4;
static const int BONE_INDICES_WEIGHTS_SIZE = sizeof(float) * 4 + sizeof(u16) * 4;
int size = POSITION_SIZE + NORMAL_SIZE;
if (geom.getUVs().values) size += UV_SIZE;
if (meta.bake_vertex_ao) size += AO_SIZE;
if (geom.getColors().values && meta.import_vertex_colors) size += meta.vertex_color_is_ao ? AO_SIZE : COLOR_SIZE;
if (hasTangents(geom)) size += TANGENT_SIZE;
if (is_skinned) size += BONE_INDICES_WEIGHTS_SIZE;
return size;
}
static bool areIndices16Bit(const ImportGeometry& mesh) {
int vertex_size = mesh.vertex_size;
return mesh.vertex_buffer.size() / vertex_size < (1 << 16);
}
// flat shading
static void computeNormals(OutputMemoryStream& unindexed_triangles, const VertexLayout& layout) {
PROFILE_FUNCTION();
const u32 vertex_size = layout.size;
const int vertex_count = int(unindexed_triangles.size() / vertex_size);
const u8* positions = unindexed_triangles.getMutableData();
u8* normals = unindexed_triangles.getMutableData() + layout.normal_offset;
for (int i = 0; i < vertex_count; i += 3) {
Vec3 v0; memcpy(&v0, positions + i * vertex_size, sizeof(v0));
Vec3 v1; memcpy(&v1, positions + (i + 1) * vertex_size, sizeof(v1));
Vec3 v2; memcpy(&v2, positions + (i + 2) * vertex_size, sizeof(v2));
Vec3 n = normalize(cross(v1 - v0, v2 - v0));
u32 npacked = packF4u(n);
memcpy(normals + i * vertex_size, &npacked, sizeof(npacked));
memcpy(normals + (i + 1) * vertex_size, &npacked, sizeof(npacked));
memcpy(normals + (i + 2) * vertex_size, &npacked, sizeof(npacked));
}
}
static void computeTangents(OutputMemoryStream& unindexed_triangles, const VertexLayout& layout, const Path& path) {
PROFILE_FUNCTION();
struct {
OutputMemoryStream* out;
int num_triangles;
int vertex_size;
const u8* positions;
const u8* normals;
const u8* uvs;
u8* tangents;
} data;
data.out = &unindexed_triangles;
data.num_triangles = int(unindexed_triangles.size() / layout.size / 3);
data.vertex_size = layout.size;
data.positions = unindexed_triangles.data();
data.normals = unindexed_triangles.data() + layout.normal_offset;
data.tangents = unindexed_triangles.getMutableData() + layout.tangent_offset;
data.uvs = unindexed_triangles.data() + layout.uv_offset;
SMikkTSpaceInterface iface = {};
iface.m_getNumFaces = [](const SMikkTSpaceContext * pContext) -> int {
auto* ptr = (decltype(data)*)pContext->m_pUserData;
return ptr->num_triangles;
};
iface.m_getNumVerticesOfFace = [](const SMikkTSpaceContext * pContext, const int face) -> int { return 3; };
iface.m_getPosition = [](const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert) {
auto* ptr = (decltype(data)*)pContext->m_pUserData;
const u8* data = ptr->positions + ptr->vertex_size * (iFace * 3 + iVert);
Vec3 p;
memcpy(&p, data, sizeof(p));
fvPosOut[0] = p.x;
fvPosOut[1] = p.y;
fvPosOut[2] = p.z;
};
iface.m_getNormal = [](const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert) {
auto* ptr = (decltype(data)*)pContext->m_pUserData;
const u8* data = ptr->normals + ptr->vertex_size * (iFace * 3 + iVert);
u32 packed;
memcpy(&packed, data, sizeof(packed));
const Vec3 normal = unpackF4u(packed);
fvNormOut[0] = normal.x;
fvNormOut[1] = normal.y;
fvNormOut[2] = normal.z;
};
iface.m_getTexCoord = [](const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert) {
auto* ptr = (decltype(data)*)pContext->m_pUserData;
const u8* data = ptr->uvs + ptr->vertex_size * (iFace * 3 + iVert);
Vec2 p;
memcpy(&p, data, sizeof(p));
fvTexcOut[0] = p.x;
fvTexcOut[1] = p.y;
};
iface.m_setTSpaceBasic = [](const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert) {
auto* ptr = (decltype(data)*)pContext->m_pUserData;
u8* data = ptr->tangents + ptr->vertex_size * (iFace * 3 + iVert);
Vec3 t;
t.x = fvTangent[0];
t.y = fvTangent[1];
t.z = fvTangent[2];
u32 packed = packF4u(t);
memcpy(data, &packed, sizeof(packed));
};
SMikkTSpaceContext ctx;
ctx.m_pUserData = &data;
ctx.m_pInterface = &iface;
tbool res = genTangSpaceDefault(&ctx);
if (!res) {
logError(path, ": failed to generate tangent space");
}
}
static void computeTangentsSimple(OutputMemoryStream& unindexed_triangles, const VertexLayout& layout) {
PROFILE_FUNCTION();
const u32 vertex_size = layout.size;
const int vertex_count = int(unindexed_triangles.size() / vertex_size);
const u8* positions = unindexed_triangles.data();
const u8* uvs = unindexed_triangles.data() + layout.uv_offset;
u8* tangents = unindexed_triangles.getMutableData() + layout.tangent_offset;
for (int i = 0; i < vertex_count; i += 3) {
Vec3 v0; memcpy(&v0, positions + i * vertex_size, sizeof(v0));
Vec3 v1; memcpy(&v1, positions + (i + 1) * vertex_size, sizeof(v1));
Vec3 v2; memcpy(&v2, positions + (i + 2) * vertex_size, sizeof(v2));
Vec2 uv0; memcpy(&uv0, uvs + i * vertex_size, sizeof(uv0));
Vec2 uv1; memcpy(&uv1, uvs + (i + 1) * vertex_size, sizeof(uv1));
Vec2 uv2; memcpy(&uv2, uvs + (i + 2) * vertex_size, sizeof(uv2));
const Vec3 dv10 = v1 - v0;
const Vec3 dv20 = v2 - v0;
const Vec2 duv10 = uv1 - uv0;
const Vec2 duv20 = uv2 - uv0;
const float dir = duv20.x * duv10.y - duv20.y * duv10.x < 0 ? -1.f : 1.f;
Vec3 tangent;
tangent.x = (dv20.x * duv10.y - dv10.x * duv20.y) * dir;
tangent.y = (dv20.y * duv10.y - dv10.y * duv20.y) * dir;
tangent.z = (dv20.z * duv10.y - dv10.z * duv20.y) * dir;
const float l = 1 / sqrtf(float(tangent.x * tangent.x + tangent.y * tangent.y + tangent.z * tangent.z));
tangent.x *= l;
tangent.y *= l;
tangent.z *= l;
u32 tangent_packed = packF4u(tangent);
memcpy(tangents + i * vertex_size, &tangent_packed, sizeof(tangent_packed));
memcpy(tangents + (i + 1) * vertex_size, &tangent_packed, sizeof(tangent_packed));
memcpy(tangents + (i + 2) * vertex_size, &tangent_packed, sizeof(tangent_packed));
}
}
static void remap(const OutputMemoryStream& unindexed_triangles, ImportGeometry& mesh) {
PROFILE_FUNCTION();
const u32 vertex_count = u32(unindexed_triangles.size() / mesh.vertex_size);
mesh.indices.resize(vertex_count);
u32 unique_vertex_count = (u32)meshopt_generateVertexRemap(mesh.indices.begin(), nullptr, vertex_count, unindexed_triangles.data(), vertex_count, mesh.vertex_size);
mesh.vertex_buffer.resize(unique_vertex_count * mesh.vertex_size);
u8* vb = mesh.vertex_buffer.getMutableData();
for (u32 i = 0; i < vertex_count; ++i) {
const u8* src = unindexed_triangles.data() + i * mesh.vertex_size;
u8* dst = vb + mesh.indices[i] * mesh.vertex_size;
memcpy(dst, src, mesh.vertex_size);
}
}
// convert from ofbx to runtime vertex data, compute missing info (normals, tangents, ao, ...)
void postprocess(const ModelMeta& meta, const Path& path) {
AtomicI32 geom_idx_getter = 0;
jobs::runOnWorkers([&](){
Array<Skin> skinning(m_allocator);
OutputMemoryStream unindexed_triangles(m_allocator);
Array<i32> tri_indices_tmp(m_allocator);
for (;;) {
i32 geom_idx = geom_idx_getter.inc();
if (geom_idx >= m_geometries.size()) break;
ImportGeometry& import_geom = m_geometries[geom_idx];
const FBXImportGeometry* fbx_geom = (const FBXImportGeometry*)import_geom.user_data;
const ofbx::GeometryData& geom = *fbx_geom->geom;
import_geom.vertex_size = getVertexSize(geom, import_geom.is_skinned, meta);
ofbx::GeometryPartition partition = geom.getPartition(import_geom.submesh == -1 ? 0 : import_geom.submesh);
if (partition.polygon_count == 0) continue;
import_geom.attributes.push({
.semantic = AttributeSemantic::POSITION,
.type = gpu::AttributeType::FLOAT,
.num_components = 3
});
import_geom.attributes.push({
.semantic = AttributeSemantic::NORMAL,
.type = gpu::AttributeType::I8,
.num_components = 4
});
if (geom.getUVs().values) {
import_geom.attributes.push({
.semantic = AttributeSemantic::TEXCOORD0,
.type = gpu::AttributeType::FLOAT,
.num_components = 2
});
}
if (meta.bake_vertex_ao) {
import_geom.attributes.push({
.semantic = AttributeSemantic::AO,
.type = gpu::AttributeType::U8,
.num_components = 4 // 1+3 because of padding
});
}
if (geom.getColors().values && meta.import_vertex_colors) {
if (meta.vertex_color_is_ao) {
import_geom.attributes.push({
.semantic = AttributeSemantic::AO,
.type = gpu::AttributeType::U8,
.num_components = 4 // 1+3 because of padding
});
}
else {
import_geom.attributes.push({
.semantic = AttributeSemantic::COLOR0,
.type = gpu::AttributeType::U8,
.num_components = 4
});
}
}
if (hasTangents(geom)) {
import_geom.attributes.push({
.semantic = AttributeSemantic::TANGENT,
.type = gpu::AttributeType::I8,
.num_components = 4
});
}
if (import_geom.is_skinned) {
import_geom.attributes.push({
.semantic = AttributeSemantic::JOINTS,
.type = gpu::AttributeType::U16,
.num_components = 4
});
import_geom.attributes.push({
.semantic = AttributeSemantic::WEIGHTS,
.type = gpu::AttributeType::FLOAT,
.num_components = 4
});
}
PROFILE_BLOCK("FBX convert vertex data")
profiler::pushInt("Triangle count", partition.triangles_count);
ofbx::Vec3Attributes normals = geom.getNormals();
ofbx::Vec3Attributes tangents = geom.getTangents();
ofbx::Vec4Attributes colors = meta.import_vertex_colors ? geom.getColors() : ofbx::Vec4Attributes{};
ofbx::Vec2Attributes uvs = geom.getUVs();
VertexLayout vertex_layout;
const bool compute_tangents = !tangents.values && uvs.values || meta.force_recompute_tangents;
vertex_layout.size = sizeof(Vec3); // position
vertex_layout.normal_offset = vertex_layout.size;
vertex_layout.size += sizeof(u32); // normals
vertex_layout.uv_offset = vertex_layout.size;
if (uvs.values) vertex_layout.size += sizeof(Vec2);
if (meta.bake_vertex_ao) vertex_layout.size += sizeof(u32);
if (colors.values && meta.import_vertex_colors) vertex_layout.size += sizeof(u32);
vertex_layout.tangent_offset = vertex_layout.size;
if (tangents.values || compute_tangents) vertex_layout.size += sizeof(u32);
if (import_geom.is_skinned) vertex_layout.size += sizeof(Vec4) + 4 * sizeof(u16);
if (import_geom.is_skinned) {
const FBXImportGeometry* g = (const FBXImportGeometry*)import_geom.user_data;
fillSkinInfo(skinning, g->bone_idx, fbx_geom->mesh);
triangulate(unindexed_triangles, import_geom, partition, geom, &skinning, meta, tri_indices_tmp);
}
else {
triangulate(unindexed_triangles, import_geom, partition, geom, nullptr, meta, tri_indices_tmp);
}
if (!normals.values || meta.force_recompute_normals) computeNormals(unindexed_triangles, vertex_layout);
if (compute_tangents) {
if (meta.use_mikktspace) {
computeTangents(unindexed_triangles, vertex_layout, path);
}
else {
computeTangentsSimple(unindexed_triangles, vertex_layout);
}
}
remap(unindexed_triangles, import_geom);
import_geom.index_size = areIndices16Bit(import_geom) ? 2 : 4;
if (import_geom.flip_handness) {
const u32 num_vertices = u32(import_geom.vertex_buffer.size() / import_geom.vertex_size);
u8* data = import_geom.vertex_buffer.getMutableData();
auto transform_vec = [&](u32 offset){
u32 packed;
memcpy(&packed, data + offset, sizeof(packed));
Vec3 v = unpackF4u(packed);
v.x *= -1;
packed = packF4u(v);
memcpy(data + offset, &packed, sizeof(packed));
};
for (u32 i = 0; i < num_vertices; ++i) {
Vec3 p;
memcpy(&p, data + i * import_geom.vertex_size, sizeof(p));
p.x *= -1;
memcpy(data + i * import_geom.vertex_size, &p, sizeof(p));
transform_vec(i * import_geom.vertex_size + vertex_layout.normal_offset);
transform_vec(i * import_geom.vertex_size + vertex_layout.tangent_offset);
}
for (i32 i = 0, n = import_geom.indices.size(); i < n; i += 3) {
swap(import_geom.indices[i], import_geom.indices[i + 1]);
}
}
}
});
postprocessCommon(meta, path);
}
void insertHierarchy(const ofbx::Object* node) {
if (!node) return;
if (m_bones.find([&](const Bone& bone){ return bone.id == u64(node); }) >= 0) return;
ofbx::Object* parent = node->getParent();
insertHierarchy(parent);
Bone& bone = m_bones.emplace(m_allocator);
bone.id = u64(node);
}
ofbx::DMatrix getBindPoseMatrix(const ofbx::Mesh* mesh, const ofbx::Object* node) const {
if (!mesh) return node->getGlobalTransform();
auto* skin = mesh->getSkin();
if (!skin) return node->getGlobalTransform();
for (int i = 0, c = skin->getClusterCount(); i < c; ++i) {
const ofbx::Cluster* cluster = skin->getCluster(i);
if (cluster->getLink() == node) {
return cluster->getTransformLinkMatrix();
}
}
return node->getGlobalTransform();
}
void gatherBones(bool force_skinned) {
PROFILE_FUNCTION();
for (const ImportMesh& mesh : m_meshes) {
const ofbx::Mesh* fbx_mesh = m_fbx_meshes[mesh.mesh_index];
const ofbx::Skin* skin = fbx_mesh->getSkin();
if (skin) {
for (int i = 0; i < skin->getClusterCount(); ++i) {
const ofbx::Cluster* cluster = skin->getCluster(i);
insertHierarchy(cluster->getLink());
}
}
if (force_skinned) {
insertHierarchy(fbx_mesh);
}
}
for (int i = 0, n = m_scene->getAnimationStackCount(); i < n; ++i) {
const ofbx::AnimationStack* stack = m_scene->getAnimationStack(i);
for (int j = 0; stack->getLayer(j); ++j) {
const ofbx::AnimationLayer* layer = stack->getLayer(j);
for (int k = 0; layer->getCurveNode(k); ++k) {
const ofbx::AnimationCurveNode* node = layer->getCurveNode(k);
if (node->getBone()) insertHierarchy(node->getBone());
}
}
}
m_bones.removeDuplicates();
for (Bone& bone : m_bones) {
const ofbx::Object* node = (const ofbx::Object*)bone.id;
bone.parent_id = node->getParent() ? u64(node->getParent()) : 0;
}
sortBones();
if (force_skinned) {
for (ImportGeometry& g : m_geometries) {
FBXImportGeometry* fbx_geom = (FBXImportGeometry*)g.user_data;
fbx_geom->bone_idx = m_bones.find([&](const Bone& bone){ return bone.id == u64(fbx_geom->mesh); });
}
}
for (Bone& bone : m_bones) {
const ofbx::Object* node = (const ofbx::Object*)bone.id;
const ofbx::Mesh* mesh = getAnyMeshFromBone(node, i32(&bone - m_bones.begin()));
Matrix tr = toLumix(getBindPoseMatrix(mesh, node));
tr.normalizeScale(); // TODO why?
tr.setTranslation(tr.getTranslation() * m_scene_scale);
bone.bind_pose_matrix = fixOrientation(tr);
bone.name = node->name;
}
}
LUMIX_FORCE_INLINE Quat fixOrientation(const Quat& v) const {
switch (m_orientation) {
case Orientation::Y_UP: return v;
case Orientation::Z_UP: return Quat(v.x, v.z, -v.y, v.w);
case Orientation::Z_MINUS_UP: return Quat(v.x, -v.z, v.y, v.w);
case Orientation::X_MINUS_UP: return Quat(v.y, -v.x, v.z, v.w);
case Orientation::X_UP: return Quat(-v.y, v.x, v.z, v.w);
}
ASSERT(false);
return Quat(v.x, v.y, v.z, v.w);
}
LUMIX_FORCE_INLINE Vec3 fixOrientation(const Vec3& v) const {
switch (m_orientation) {
case Orientation::Y_UP: return v;
case Orientation::Z_UP: return Vec3(v.x, v.z, -v.y);
case Orientation::Z_MINUS_UP: return Vec3(v.x, -v.z, v.y);
case Orientation::X_MINUS_UP: return Vec3(v.y, -v.x, v.z);
case Orientation::X_UP: return Vec3(-v.y, v.x, v.z);
}
ASSERT(false);
return v;
}
LUMIX_FORCE_INLINE Matrix fixOrientation(const Matrix& m) const {
switch (m_orientation) {
case Orientation::Y_UP: return m;
case Orientation::Z_UP:{
Matrix mtx = Matrix(
Vec4(1, 0, 0, 0),
Vec4(0, 0, -1, 0),
Vec4(0, 1, 0, 0),
Vec4(0, 0, 0, 1)
);
return mtx * m;
}
case Orientation::Z_MINUS_UP:
case Orientation::X_MINUS_UP:
case Orientation::X_UP:
ASSERT(false); // TODO
break;
}
ASSERT(false);
return m;
}
LUMIX_FORCE_INLINE u32 getPackedVec3(ofbx::Vec3 vec) const {
Vec3 v = toLumixVec3(vec);
return packF4u(v);
}
void fillSkinInfo(Array<Skin>& skinning, i32 force_bone_idx, const ofbx::Mesh* mesh) const {
const ofbx::Skin* fbx_skin = mesh->getSkin();
const ofbx::GeometryData& geom = mesh->getGeometryData();
skinning.resize(geom.getPositions().values_count);
memset(&skinning[0], 0, skinning.size() * sizeof(skinning[0]));
if (!fbx_skin) {
ASSERT(force_bone_idx >= 0);
for (Skin& skin : skinning) {
skin.count = 1;
skin.weights[0] = 1;
skin.weights[1] = skin.weights[2] = skin.weights[3] = 0;
skin.joints[0] = skin.joints[1] = skin.joints[2] = skin.joints[3] = force_bone_idx;
}
return;
}
for (int i = 0, c = fbx_skin->getClusterCount(); i < c; ++i) {
const ofbx::Cluster* cluster = fbx_skin->getCluster(i);
if (cluster->getIndicesCount() == 0) continue;
if (!cluster->getLink()) continue;
i32 joint = m_bones.find([&](const Bone& bone){ return bone.id == u64(cluster->getLink()); });
ASSERT(joint >= 0);
const int* cp_indices = cluster->getIndices();
const double* weights = cluster->getWeights();
for (int j = 0; j < cluster->getIndicesCount(); ++j) {
int idx = cp_indices[j];
float weight = (float)weights[j];
Skin& s = skinning[idx];
if (s.count < 4) {
s.weights[s.count] = weight;
s.joints[s.count] = joint;
++s.count;
}
else {
int min = 0;
for (int m = 1; m < 4; ++m) {
if (s.weights[m] < s.weights[min]) min = m;
}
if (s.weights[min] < weight) {
s.weights[min] = weight;
s.joints[min] = joint;
}
}
}
}
for (Skin& s : skinning) {
float sum = 0;
for (float w : s.weights) sum += w;
if (sum == 0) {
s.weights[0] = 1;
s.weights[1] = s.weights[2] = s.weights[3] = 0;
s.joints[0] = s.joints[1] = s.joints[2] = s.joints[3] = 0;
}
else {
for (float& w : s.weights) w /= sum;
}
}
}
void triangulate(OutputMemoryStream& unindexed_triangles
, ImportGeometry& mesh
, const ofbx::GeometryPartition& partition
, const ofbx::GeometryData& geom
, const Array<Skin>* skinning
, const ModelMeta& meta
, Array<i32>& tri_indices) const
{
PROFILE_FUNCTION();
ofbx::Vec3Attributes positions = geom.getPositions();
ofbx::Vec3Attributes normals = geom.getNormals();
ofbx::Vec3Attributes tangents = geom.getTangents();
ofbx::Vec4Attributes colors = meta.import_vertex_colors ? geom.getColors() : ofbx::Vec4Attributes{};
ofbx::Vec2Attributes uvs = geom.getUVs();
const bool compute_tangents = !tangents.values && uvs.values;
tri_indices.resize(partition.max_polygon_triangles * 3);
unindexed_triangles.clear();
unindexed_triangles.resize(mesh.vertex_size * 3 * partition.triangles_count);
u8* dst = unindexed_triangles.getMutableData();
// convert to interleaved vertex data of unindexed triangles
// tri[0].v[0].pos, tri[0].v[0].normal, ... tri[0].v[2].tangent, tri[1].v[0].pos, ...
auto write = [&](const auto& v){
memcpy(dst, &v, sizeof(v));
dst += sizeof(v);
};
for (i32 polygon_idx = 0; polygon_idx < partition.polygon_count; ++polygon_idx) {
const ofbx::GeometryPartition::Polygon& polygon = partition.polygons[polygon_idx];
u32 tri_count = ofbx::triangulate(geom, polygon, tri_indices.begin());
for (u32 i = 0; i < tri_count; ++i) {
ofbx::Vec3 cp = positions.get(tri_indices[i]);
write(toLumixVec3(cp));
if (normals.values) write(getPackedVec3(normals.get(tri_indices[i])));
else write(u32(0));
if (uvs.values) {
ofbx::Vec2 uv = uvs.get(tri_indices[i]);
write(Vec2(uv.x, 1 - uv.y));
}
if (meta.bake_vertex_ao) write(u32(0));
if (colors.values && meta.import_vertex_colors) {
ofbx::Vec4 color = colors.get(tri_indices[i]);
if (meta.vertex_color_is_ao) {
const u8 ao[4] = { u8(color.x * 255.f + 0.5f) };
memcpy(dst, ao, sizeof(ao));
dst += sizeof(ao);
} else {
write(packColor(color));
}
}
if (tangents.values) write(getPackedVec3(tangents.get(tri_indices[i])));
else if (compute_tangents) write(u32(0));
if (skinning) {
if (positions.indices) {
write((*skinning)[positions.indices[tri_indices[i]]].joints);
write((*skinning)[positions.indices[tri_indices[i]]].weights);
}
else {
write((*skinning)[tri_indices[i]].joints);
write((*skinning)[tri_indices[i]].weights);
}
}
}
}
}
void sortBones() {
const int count = m_bones.size();
u32 first_nonroot = 0;
for (i32 i = 0; i < count; ++i) {
if (m_bones[i].parent_id == 0) {
swap(m_bones[i], m_bones[first_nonroot]);
++first_nonroot;
}
}
for (i32 i = 0; i < count; ++i) {
for (int j = i + 1; j < count; ++j) {
if (m_bones[i].parent_id == m_bones[j].id) {
Bone bone = static_cast<Bone&&>(m_bones[j]);
m_bones.swapAndPop(j);
m_bones.insert(i, static_cast<Bone&&>(bone));
--i;
break;
}
}
}
}
const ofbx::Mesh* getAnyMeshFromBone(const ofbx::Object* node, i32 bone_idx) const {
for (const ImportGeometry& geom : m_geometries) {
FBXImportGeometry* fbx_geom = (FBXImportGeometry*)geom.user_data;
if (fbx_geom->bone_idx == bone_idx) {
return fbx_geom->mesh;
}
auto* skin = fbx_geom->mesh->getSkin();
if (!skin) continue;
for (int j = 0, c = skin->getClusterCount(); j < c; ++j) {
if (skin->getCluster(j)->getLink() == node) return fbx_geom->mesh;
}
}
return nullptr;
}
void gatherAnimations(StringView src) {
PROFILE_FUNCTION();
int anim_count = m_scene->getAnimationStackCount();
for (int i = 0; i < anim_count; ++i) {
ImportAnimation& anim = m_animations.emplace();
anim.index = m_animations.size() - 1;
const ofbx::AnimationStack* fbx_anim = (const ofbx::AnimationStack*)m_scene->getAnimationStack(i);
{
const ofbx::TakeInfo* take_info = m_scene->getTakeInfo(fbx_anim->name);
if (take_info) {
if (take_info->name.begin != take_info->name.end) {
anim.name = toStringView(take_info->name);
}
if (anim.name.empty() && take_info->filename.begin != take_info->filename.end) {
StringView tmp = toStringView(take_info->filename);
anim.name = Path::getBasename(tmp);
}
if (anim.name.empty()) anim.name = "anim";
}
else {
anim.name = "";
}
}
const ofbx::AnimationLayer* anim_layer = fbx_anim->getLayer(0);
{
anim.fps = m_scene->getSceneFrameRate();
const ofbx::TakeInfo* take_info = m_scene->getTakeInfo(fbx_anim->name);
if(!take_info && startsWith(fbx_anim->name, "AnimStack::")) {
take_info = m_scene->getTakeInfo(fbx_anim->name + 11);
}
if (take_info) {
anim.length = take_info->local_time_to - take_info->local_time_from;
}
else if(m_scene->getGlobalSettings()) {
anim.length = m_scene->getGlobalSettings()->TimeSpanStop;
}
else {
logError("Unsupported animation in ", src);
continue;
}
}
if (!anim_layer || !anim_layer->getCurveNode(0)) {
m_animations.pop();
continue;
}
bool data_found = false;
for (int k = 0; anim_layer->getCurveNode(k); ++k) {
const ofbx::AnimationCurveNode* node = anim_layer->getCurveNode(k);
if (node->getBoneLinkProperty() == "Lcl Translation" || node->getBoneLinkProperty() == "Lcl Rotation") {
if (!isConstCurve(node->getCurve(0)) || !isConstCurve(node->getCurve(1)) || !isConstCurve(node->getCurve(2))) {
data_found = true;
break;
}
}
}
if (!data_found) m_animations.pop();
}
if (m_animations.size() == 1) {
m_animations[0].name = "";
}
}
static i64 sampleToFBXTime(u32 sample, float fps) {
return ofbx::secondsToFbxTime(sample / fps);
}
static void convert(const ofbx::DMatrix& mtx, Vec3& pos, Quat& rot) {
Matrix m = toLumix(mtx);
m.normalizeScale();
rot = m.getRotation();
pos = m.getTranslation();
}
static float evalCurve(i64 time, const ofbx::AnimationCurve& curve) {
const i64* times = curve.getKeyTime();
const float* values = curve.getKeyValue();
const int count = curve.getKeyCount();
ASSERT(count > 0);
time = clamp(time, times[0], times[count - 1]);
for (int i = 0; i < count; ++i) {
if (time == times[i]) return values[i];
if (time < times[i]) {
ASSERT(i > 0);
ASSERT(time > times[i - 1]);
const float t = float((time - times[i - 1]) / double(times[i] - times[i - 1]));
return values[i - 1] * (1 - t) + values[i] * t;
}
}
ASSERT(false);
return 0.f;
};
static void fill(const ofbx::Object& bone, const ofbx::AnimationLayer& layer, Array<Key>& keys, u32 from_sample, u32 samples_count, float fps) {
const ofbx::AnimationCurveNode* translation_node = layer.getCurveNode(bone, "Lcl Translation");
const ofbx::AnimationCurveNode* rotation_node = layer.getCurveNode(bone, "Lcl Rotation");
if (!translation_node && !rotation_node) return;
keys.resize(samples_count);
auto fill_rot = [&](u32 idx, const ofbx::AnimationCurve* curve) {
if (!curve) {
const ofbx::DVec3 lcl_rot = bone.getLocalRotation();
for (Key& k : keys) {
(&k.rot.x)[idx] = float((&lcl_rot.x)[idx]);
}
return;
}
for (u32 f = 0; f < samples_count; ++f) {
Key& k = keys[f];
(&k.rot.x)[idx] = evalCurve(sampleToFBXTime(from_sample + f, fps), *curve);
}
};
auto fill_pos = [&](u32 idx, const ofbx::AnimationCurve* curve) {
if (!curve) {
const ofbx::DVec3 lcl_pos = bone.getLocalTranslation();
for (Key& k : keys) {
(&k.pos.x)[idx] = float((&lcl_pos.x)[idx]);
}
return;
}
for (u32 f = 0; f < samples_count; ++f) {
Key& k = keys[f];
(&k.pos.x)[idx] = evalCurve(sampleToFBXTime(from_sample + f, fps), *curve);
}
};
fill_rot(0, rotation_node ? rotation_node->getCurve(0) : nullptr);
fill_rot(1, rotation_node ? rotation_node->getCurve(1) : nullptr);
fill_rot(2, rotation_node ? rotation_node->getCurve(2) : nullptr);
fill_pos(0, translation_node ? translation_node->getCurve(0) : nullptr);
fill_pos(1, translation_node ? translation_node->getCurve(1) : nullptr);
fill_pos(2, translation_node ? translation_node->getCurve(2) : nullptr);
for (Key& key : keys) {
const ofbx::DMatrix mtx = bone.evalLocal({key.pos.x, key.pos.y, key.pos.z}, {key.rot.x, key.rot.y, key.rot.z});
convert(mtx, key.pos, key.rot);
}
}
const Bone* getParent(const Bone& bone) const {
if (bone.parent_id == 0) return nullptr;
for (const Bone& b : m_bones) {
if (b.id == bone.parent_id) return &b;
}
ASSERT(false);
return nullptr;
}
static float getScaleX(const ofbx::DMatrix& mtx) {
Vec3 v(float(mtx.m[0]), float(mtx.m[4]), float(mtx.m[8]));
return length(v);
}
void fillTracks(const ImportAnimation& anim
, Array<Array<Key>>& tracks
, u32 from_sample
, u32 num_samples) const override
{
tracks.clear();
tracks.reserve(m_bones.size());
const ofbx::AnimationStack* fbx_anim = (const ofbx::AnimationStack*)m_scene->getAnimationStack(anim.index);
const ofbx::AnimationLayer* layer = fbx_anim->getLayer(0);
for (const Bone& bone : m_bones) {
Array<Key>& keys = tracks.emplace(m_allocator);
fill(*(const ofbx::Object*)(bone.id), *layer, keys, from_sample, num_samples, anim.fps);
}
for (const Bone& bone : m_bones) {
const Bone* parent = getParent(bone);
float scale = m_scene_scale;
if (parent) {
// parent_scale - animated scale is not supported, but we can get rid of static scale if we ignore
// it in writeSkeleton() and use `parent_scale` in this function
const ofbx::Object* fbx_parent = (const ofbx::Object*)(parent->id);
const float parent_scale = (float)getScaleX(fbx_parent->getGlobalTransform());
scale *= parent_scale;
}
if (fabsf(scale - 1) < 1e-5f) continue;
Array<Key>& keys = tracks[u32(&bone - m_bones.begin())];
for (Key& k : keys) k.pos *= scale;
}
if (m_orientation != Orientation::Y_UP) {
for (Array<Key>& track : tracks) {
for (Key& key : track) {
key.pos = fixOrientation(key.pos);
key.rot = fixOrientation(key.rot);
}
}