forked from fynv/usd2glb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
2661 lines (2260 loc) · 77.8 KB
/
main.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
#define NOMINMAX
#include <cstdio>
#include <tinyusdz.hh>
#include <usdShade.hh>
#include <usdSkel.hh>
#include <usda-writer.hh>
#include "value-pprint.hh"
#include "prim-pprint.hh"
#include "value-pprint.hh"
#define TINYGLTF_IMPLEMENTATION
#include <tiny_gltf.h>
//#define STB_IMAGE_IMPLEMENTATION
//#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <glm.hpp>
#include <gtc/quaternion.hpp>
#include <gtx/matrix_decompose.hpp>
#include <vector>
#include <queue>
#include <unordered_map>
#include <filesystem>
#include <crc64.h>
#include <tydra/scene-access.hh>
#include "Image.h"
namespace Mid
{
struct Material
{
std::string name;
bool double_sided = false;
bool useSpecularWorkflow = false;
glm::vec3 diffuse_color = glm::vec3(1.0f, 1.0f, 1.0f);
std::string diffuse_tex = "";
std::string diffuse_varname = "";
glm::vec3 emissive_color = glm::vec3(0.0f, 0.0f, 0.0f);
std::string emissive_tex = "";
glm::vec3 specular_color = glm::vec3(1.0f, 1.0f, 1.0f);
std::string specular_tex = "";
float metallic = 0.0f;
std::string metallic_tex = "";
float roughness = 0.5f;
std::string roughness_tex = "";
float opacity = 1.0f;
std::string opacity_tex = "";
std::string uvset = "";
int idx_diffuse_alpha = -1;
int idx_emissive = -1;
int idx_metallic_roughness = -1;
int idx_specular_glossiness = -1;
};
}
inline glm::mat4 mat_convert(const tinyusdz::value::matrix4d& mat)
{
glm::mat4 mat_row = *(glm::dmat4*)(&mat);
return glm::transpose(mat_row);
}
#if 1
#ifdef MAKE_A_DLL
#define USD2GLB_EXPORTS
#ifdef USD2GLB_EXPORTS
#define USD2GLB_API extern "C" __declspec(dllexport)
#else
#define USD2GLB_API extern "C" __declspec(dllimport)
#endif
#else
#define USD2GLB_API
#endif
USD2GLB_API int usd2glb(const char* usdPathInput, const char* glbPathOutput)
{
std::string path_model = std::filesystem::path(usdPathInput).parent_path().u8string();
std::string warn;
std::string err;
tinyusdz::Stage stage;
tinyusdz::USDLoadOptions options;
options.max_image_width = options.max_image_height = 4096;
options.load_assets = false;
bool ret = tinyusdz::LoadUSDFromFile(usdPathInput, &stage, &warn, &err, options);
if (!ret)
{
printf("%s\n", warn.c_str());
printf("%s\n", err.c_str());
return -1;
}
// tinyusdz::usda::SaveAsUSDA("output.usda", stage, &warn, &err);
double time_codes_per_sec = stage.metas().timeCodesPerSecond.get_value();
auto upAxis = stage.metas().upAxis.get_value();
glm::quat axis_rot = glm::identity<glm::quat>();
if (upAxis == tinyusdz::Axis::X)
{
glm::mat4 rot = { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f };
axis_rot = rot;
}
else if (upAxis == tinyusdz::Axis::Z)
{
glm::mat4 rot = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f };
axis_rot = rot;
}
tinyusdz::Prim* root_prim = &stage.root_prims()[0];
tinygltf::Model m_out;
m_out.scenes.resize(1);
tinygltf::Scene& scene_out = m_out.scenes[0];
scene_out.name = "Scene";
m_out.asset.version = "2.0";
m_out.asset.generator = "tinygltf";
m_out.buffers.resize(1);
tinygltf::Buffer& buf_out = m_out.buffers[0];
size_t offset = 0;
size_t length = 0;
size_t view_id = 0;
size_t acc_id = 0;
std::vector<Mid::Material> material_lst;
std::unordered_map<std::string, int> material_map;
struct Prim
{
tinyusdz::Prim* prim;
int id_node_base = -1;
std::string base_path;
int idx_material = -1;
std::string skel_path;
};
std::queue<Prim> queue_prim;
bool specular_used = false;
queue_prim.push({ root_prim, -1, "" });
while (!queue_prim.empty())
{
Prim prim = queue_prim.front();
queue_prim.pop();
std::string path = prim.base_path + "/" + prim.prim->element_path().full_path_name();
if (prim.prim->data().type_id() == tinyusdz::value::TYPE_ID_MATERIAL)
{
Mid::Material material_mid;
auto* material_in = prim.prim->data().as<tinyusdz::Material>();
material_mid.name = material_in->name;
const std::vector<tinyusdz::Path>& connections = material_in->surface.get_connections();
auto ppath = connections[0].get_parent_path();
nonstd::expected<const tinyusdz::Prim*, std::string> pshader0 = stage.GetPrimAtPath(ppath);
const tinyusdz::Prim* prim = pshader0.value();
auto* shader0 = prim->data().as<tinyusdz::Shader>();
auto* surface = shader0->value.as<tinyusdz::UsdPreviewSurface>();
int useSpecularWorkflow;
surface->useSpecularWorkflow.get_value().get_scalar(&useSpecularWorkflow);
material_mid.useSpecularWorkflow = useSpecularWorkflow != 0;
specular_used = specular_used || material_mid.useSpecularWorkflow;
{
auto diffuse = surface->diffuseColor;
auto diffuse_connection = diffuse.get_connection();
if (diffuse_connection.has_value())
{
std::string path = diffuse_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
if (shader1->value.type_id() == tinyusdz::value::TYPE_ID_IMAGING_UVTEXTURE)
{
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.diffuse_tex = file.GetAssetPath();
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
const tinyusdz::Shader* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
if (uvset->varname.is_connection() == true)
{
nonstd::optional<tinyusdz::Path> varname_connectionOpt = uvset->varname.get_connection();
if (varname_connectionOpt.has_value())
{
tinyusdz::Path varname_connection = varname_connectionOpt.value();
std::string path_varname = varname_connection.prim_part();
std::string prop = varname_connection.prop_part();
const tinyusdz::Prim* prim_varname = stage.GetPrimAtPath(tinyusdz::Path(path_varname, "")).value();
auto* material_inB = prim_varname->data().as<tinyusdz::Material>();
if (material_inB)
{
auto propPairIt = material_inB->props.find(prop);
if (propPairIt != std::end(material_inB->props))
{
tinyusdz::Property property = propPairIt->second;
if (property.is_attribute())
{
tinyusdz::Attribute attribute = property.get_attribute();
tinyusdz::value::token propToken = attribute.get_value<tinyusdz::value::token>().value();
material_mid.uvset = propToken.str();
}
}
}
}
}
else
{
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
}
}
else if (shader1->value.type_id() == tinyusdz::value::TYPE_ID_IMAGING_PRIMVAR_READER_FLOAT3)
{
auto* reader = shader1->value.as<tinyusdz::UsdPrimvarReader_float3>();
tinyusdz::value::token varname;
reader->varname.get_value().value().get_scalar(&varname);
material_mid.diffuse_varname = varname.str();
}
material_mid.diffuse_color = { 1.0f, 1.0f, 1.0f };
}
else
{
tinyusdz::value::color3f col;
diffuse.get_value().get_scalar(&col);
material_mid.diffuse_color = { col[0], col[1], col[2] };
}
}
{
auto emissive = surface->emissiveColor;
auto emissive_connection = emissive.get_connection();
if (emissive_connection.has_value())
{
std::string path = emissive_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.emissive_tex = file.GetAssetPath();
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
auto* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
material_mid.emissive_color = { 1.0f, 1.0f, 1.0f };
}
else
{
tinyusdz::value::color3f col;
emissive.get_value().get_scalar(&col);
material_mid.emissive_color = { col[0], col[1], col[2] };
}
}
if (material_mid.useSpecularWorkflow)
{
auto specular = surface->specularColor;
auto specular_connection = specular.get_connection();
if (specular_connection.has_value())
{
std::string path = specular_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.specular_tex = file.GetAssetPath();
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
auto* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
material_mid.specular_color = { 1.0f, 1.0f, 1.0f };
}
else
{
tinyusdz::value::color3f col;
specular.get_value().get_scalar(&col);
material_mid.specular_color = { col[0], col[1], col[2] };
}
}
else
{
auto metallic = surface->metallic;
auto metallic_connection = metallic.get_connection();
if (metallic_connection.has_value())
{
std::string path = metallic_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.metallic_tex = file.GetAssetPath();
material_mid.metallic = 1.0f;
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
auto* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
}
else
{
metallic.get_value().get_scalar(&material_mid.metallic);
}
}
{
auto roughness = surface->roughness;
auto roughness_connection = roughness.get_connection();
if (roughness_connection.has_value())
{
std::string path = roughness_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.roughness_tex = file.GetAssetPath();
material_mid.roughness = 1.0f;
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
auto* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
}
else
{
roughness.get_value().get_scalar(&material_mid.roughness);
}
}
{
auto opacity = surface->opacity;
auto opacity_connection = opacity.get_connection();
if (opacity_connection.has_value())
{
std::string path = opacity_connection.value().prim_part();
const tinyusdz::Prim* pshader1 = stage.GetPrimAtPath(tinyusdz::Path(path, "")).value();
auto* shader1 = pshader1->data().as<tinyusdz::Shader>();
auto* tex = shader1->value.as<tinyusdz::UsdUVTexture>();
tinyusdz::value::AssetPath file;
tex->file.get_value().value().get_scalar(&file);
material_mid.opacity_tex = file.GetAssetPath();
material_mid.opacity = 1.0f;
auto uv_connection = tex->st.get_connection();
if (uv_connection.has_value())
{
std::string path_uv = uv_connection.value().prim_part();
const tinyusdz::Prim* pshader2 = stage.GetPrimAtPath(tinyusdz::Path(path_uv, "")).value();
auto* shader2 = pshader2->data().as<tinyusdz::Shader>();
auto* uvset = shader2->value.as<tinyusdz::UsdPrimvarReader_float2>();
tinyusdz::value::token token_uv;
uvset->varname.get_value().value().get_scalar(&token_uv);
material_mid.uvset = token_uv.str();
}
}
else
{
opacity.get_value().get_scalar(&material_mid.opacity);
}
}
int idx = (int)material_lst.size();
material_lst.push_back(material_mid);
material_map[path] = idx;
}
if (prim.prim->data().type_id() != tinyusdz::value::TYPE_ID_MATERIAL
&& prim.prim->data().type_id() != tinyusdz::value::TYPE_ID_GEOM_MESH)
{
size_t num_children = prim.prim->children().size();
for (size_t i = 0; i < num_children; i++)
{
queue_prim.push({ &prim.prim->children()[i], -1, path });
}
}
}
if (specular_used)
{
m_out.extensionsUsed.push_back("KHR_materials_pbrSpecularGlossiness");
}
std::unordered_map<std::string, int> joint_map;
std::unordered_map<int, std::string> node_skin_map;
std::unordered_map<std::string, int> skin_map;
struct MorphIdx
{
int node_idx;
int morph_idx;
};
std::unordered_map<std::string, std::vector<MorphIdx>> morph_map;
std::unordered_map<int, int> target_counts;
queue_prim.push({ root_prim, -1, "" });
while (!queue_prim.empty())
{
Prim prim = queue_prim.front();
queue_prim.pop();
std::string path = prim.base_path + "/" + prim.prim->element_path().full_path_name();
if (prim.prim->data().type_id() == tinyusdz::value::TYPE_ID_GEOM_XFORM)
{
auto* node_in = prim.prim->data().as<tinyusdz::Xform>();
if (node_in->materialBinding.has_value())
{
std::string material_path = node_in->materialBinding.value().targetPath.full_path_name();
prim.idx_material = material_map[material_path];
}
int node_id = (int)m_out.nodes.size();
tinygltf::Node node_out;
node_out.name = node_in->name;
tinyusdz::value::matrix4d matrix;
node_in->EvaluateXformOps(0.0, tinyusdz::value::TimeSampleInterpolationType::Linear, &matrix, nullptr, nullptr);
glm::mat4 mat = mat_convert(matrix);
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 persp;
glm::decompose(mat, scale, rotation, translation, skew, persp);
node_out.translation = { translation.x, translation.y, translation.z };
node_out.rotation = { rotation.x, rotation.y, rotation.z, rotation.w };
node_out.scale = { scale.x, scale.y, scale.z };
m_out.nodes.push_back(node_out);
if (prim.id_node_base >= 0)
{
m_out.nodes[prim.id_node_base].children.push_back(node_id);
}
else
{
rotation = axis_rot * rotation;
node_out.rotation = { rotation.x, rotation.y, rotation.z, rotation.w };
scene_out.nodes.push_back(node_id);
}
prim.id_node_base = node_id;
}
else if (prim.prim->data().type_id() == tinyusdz::value::TYPE_ID_SKEL_ROOT)
{
auto* node_in = prim.prim->data().as<tinyusdz::SkelRoot>();
int node_id = (int)m_out.nodes.size();
{
auto iter = node_in->props.find("skel:skeleton");
if (iter != node_in->props.end())
{
prim.skel_path = iter->second.get_relationship().targetPath.full_path_name();
}
}
tinygltf::Node node_out;
node_out.name = node_in->name;
for (size_t i = 0; i < node_in->xformOps.size(); i++)
{
auto& op = node_in->xformOps[i];
if (op.op_type == tinyusdz::XformOp::OpType::Transform)
{
auto* matrix = op.get_scalar().value().as<tinyusdz::value::matrix4d>();
glm::mat4 mat = mat_convert(*matrix);
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 persp;
glm::decompose(mat, scale, rotation, translation, skew, persp);
rotation = axis_rot * rotation;
node_out.translation = { translation.x, translation.y, translation.z };
node_out.rotation = { rotation.x, rotation.y, rotation.z, rotation.w };
node_out.scale = { scale.x, scale.y, scale.z };
m_out.nodes.push_back(node_out);
scene_out.nodes.push_back(node_id);
prim.id_node_base = node_id;
break;
}
}
}
else if (prim.prim->data().type_id() == tinyusdz::value::TYPE_ID_GEOM_MESH)
{
auto* mesh_in = prim.prim->data().as<tinyusdz::GeomMesh>();
bool leftHand = false;
if (mesh_in->orientation.get_value() == tinyusdz::Orientation::LeftHanded)
{
leftHand = true;
}
if (mesh_in->materialBinding.has_value())
{
std::string material_path = mesh_in->materialBinding.value().targetPath.full_path_name();
prim.idx_material = material_map[material_path];
}
int node_id = (int)m_out.nodes.size();
int mesh_id = (int)m_out.meshes.size();
tinygltf::Node node_out;
node_out.name = mesh_in->name;
node_out.mesh = mesh_id;
m_out.nodes.push_back(node_out);
if (prim.id_node_base >= 0)
{
m_out.nodes[prim.id_node_base].children.push_back(node_id);
}
else
{
node_out.rotation = { axis_rot.x, axis_rot.y, axis_rot.z, axis_rot.w };
scene_out.nodes.push_back(node_id);
}
prim.id_node_base = node_id;
tinygltf::Mesh mesh_out;
mesh_out.name = node_out.name;
mesh_out.primitives.resize(1);
auto& prim_out = mesh_out.primitives[0];
std::vector<tinyusdz::value::point3f> points_in;
std::vector<tinyusdz::value::normal3f> norms_in;
std::vector<std::vector<tinyusdz::value::vector3f>> offsets_in;
std::vector<std::vector<tinyusdz::value::vector3f>> norm_offsets_in;
std::vector<bool> target_sparse;
std::vector<std::vector<bool>> non_zeros_in;
std::vector<glm::u8vec4> conv_ji_in;
std::vector<glm::vec4> conv_jw_in;
std::vector<int> faceVertexIndices;
std::vector<int> faceVertexCounts;
std::vector<glm::ivec3> faces;
bool uv_indp_indices = false;
std::vector<tinyusdz::value::float2> uv_in;
std::vector<int> uv_indices_in;
int idx_material = prim.idx_material;
if (idx_material == -1)
{
idx_material = (int)material_lst.size();
Mid::Material material_mid;
auto iter = mesh_in->props.find("primvars:displayColor");
if (iter != mesh_in->props.end())
{
auto col = iter->second.get_attribute().get_value<std::vector<tinyusdz::value::float3>>().value()[0];
material_mid.diffuse_color = { col[0], col[1], col[2] };
}
material_lst.push_back(material_mid);
prim.idx_material = idx_material;
}
else
{
Mid::Material material_mid = material_lst[idx_material];
auto iter = mesh_in->props.find("primvars:"+ material_mid.diffuse_varname);
if (iter != mesh_in->props.end())
{
auto col = iter->second.get_attribute().get_value<std::vector<tinyusdz::value::float3>>().value()[0];
material_mid.diffuse_color = { col[0], col[1], col[2] };
idx_material = (int)material_lst.size();
material_lst.push_back(material_mid);
prim.idx_material = idx_material;
}
}
Mid::Material& material_mid = material_lst[idx_material];
material_mid.double_sided = mesh_in->doubleSided.get_value();
prim_out.material = idx_material;
mesh_in->points.get_value().value().get_scalar(&points_in);
tinyusdz::Extent extent;
mesh_in->extent.get_value().value().get_scalar(&extent);
if (mesh_in->normals.get_value().has_value())
{
mesh_in->normals.get_value().value().get_scalar(&norms_in);
}
mesh_in->faceVertexIndices.get_value().value().get_scalar(&faceVertexIndices);
mesh_in->faceVertexCounts.get_value().value().get_scalar(&faceVertexCounts);
{
std::string var_name_uvset = std::string("primvars:") + material_mid.uvset;
auto iter = mesh_in->props.find(var_name_uvset);
if (iter != mesh_in->props.end())
{
uv_in = iter->second.get_attribute().get_value<std::vector<tinyusdz::value::float2>>().value();
auto interpo = iter->second.get_attribute().metas().interpolation.value();
uv_indp_indices = interpo == tinyusdz::Interpolation::FaceVarying;
std::string var_name_uv_indices = std::string("primvars:") + material_mid.uvset + ":indices";
auto iter2 = mesh_in->props.find(var_name_uv_indices);
if (iter2 != mesh_in->props.end())
{
uv_indices_in = iter2->second.get_attribute().get_value<std::vector<int>>().value();
}
}
}
{
auto iter_ji = mesh_in->props.find("primvars:skel:jointIndices");
auto iter_jw = mesh_in->props.find("primvars:skel:jointWeights");
if (iter_ji != mesh_in->props.end() && iter_jw != mesh_in->props.end())
{
if (mesh_in->skeleton.has_value())
{
prim.skel_path = mesh_in->skeleton.value().targetPath.full_path_name();
}
node_skin_map[node_id] = prim.skel_path;
unsigned elem_size = iter_ji->second.get_attribute().metas().elementSize.value();
bool constant_joints = iter_ji->second.get_attribute().metas().interpolation.value() == tinyusdz::Interpolation::Constant;
auto ji = iter_ji->second.get_attribute().get_value<std::vector<int>>().value();
auto jw = iter_jw->second.get_attribute().get_value<std::vector<float>>().value();
size_t count = ji.size() / elem_size;
if (constant_joints)
{
count = points_in.size();
conv_ji_in.resize(count, { 0,0,0,0 });
conv_jw_in.resize(count, { 0.0f, 0.0f, 0.0f, 0.0f });
for (size_t i = 0; i < count; i++)
{
unsigned elems = 4;
if (elem_size < elems) elems = elem_size;
for (unsigned j = 0; j < elems; j++)
{
conv_ji_in[i][j] = (uint8_t)ji[j];
conv_jw_in[i][j] = jw[j];
}
}
}
else
{
conv_ji_in.resize(count, { 0,0,0,0 });
conv_jw_in.resize(count, { 0.0f, 0.0f, 0.0f, 0.0f });
for (size_t i = 0; i < count; i++)
{
unsigned elems = 4;
if (elem_size < elems) elems = elem_size;
for (unsigned j = 0; j < elems; j++)
{
size_t idx = elem_size * i + j;
conv_ji_in[i][j] = (uint8_t)ji[idx];
conv_jw_in[i][j] = jw[idx];
}
}
}
}
}
{
auto iter = mesh_in->props.find("skel:blendShapeTargets");
if (iter != mesh_in->props.end())
{
auto paths = iter->second.get_relationship().targetPathVector;
auto iter2 = mesh_in->props.find("skel:blendShapes");
auto names = iter2->second.get_attribute().get_value<std::vector<tinyusdz::Token>>().value();
size_t num_morphs = paths.size();
offsets_in.resize(num_morphs);
norm_offsets_in.resize(num_morphs);
target_sparse.resize(num_morphs, false);
non_zeros_in.resize(num_morphs);
target_counts[node_id] = (int)num_morphs;
for (size_t i = 0; i < num_morphs; i++)
{
std::string name = names[i].str();
morph_map[name].push_back({ node_id, (int)i });
const tinyusdz::Prim* primbs = stage.GetPrimAtPath(paths[i]).value();
auto* bs = primbs->data().as<tinyusdz::BlendShape>();
std::vector<tinyusdz::value::vector3f> offsets = bs->offsets.get_value().value();
offsets_in[i].resize(points_in.size());
std::vector<tinyusdz::value::vector3f> normOffsets;
if (norms_in.size() > 0)
{
normOffsets = bs->normalOffsets.get_value().value();
norm_offsets_in[i].resize(norms_in.size());
}
non_zeros_in[i].resize(points_in.size(), false);
if (bs->pointIndices.get_value().has_value())
{
target_sparse[i] = true;
auto pointIndices = bs->pointIndices.get_value().value();
size_t num_points = pointIndices.size();
for (size_t j = 0; j < num_points; j++)
{
int idx = pointIndices[j];
offsets_in[i][idx] = offsets[j];
if (normOffsets.size() > 0)
{
norm_offsets_in[i][idx] = normOffsets[j];
}
non_zeros_in[i][idx] = true;
}
}
else
{
target_sparse[i] = false;
for (size_t j = 0; j < points_in.size(); j++)
{
offsets_in[i][j] = offsets[j];
if (normOffsets.size() > 0)
{
norm_offsets_in[i][j] = normOffsets[j];
}
non_zeros_in[i][j] = true;
}
}
}
}
}
if (uv_indp_indices)
{
struct PointIn
{
int ind_pnt;
tinyusdz::value::float2 uv;
};
std::vector<tinyusdz::value::point3f> points_out;
std::vector<tinyusdz::value::normal3f> norms_out;
std::vector<std::vector<tinyusdz::value::vector3f>> offsets_out;
std::vector<std::vector<tinyusdz::value::vector3f>> norm_offsets_out;
std::vector<std::vector<bool>> non_zeros_out;
std::vector<glm::u8vec4> conv_ji_out;
std::vector<glm::vec4> conv_jw_out;
std::vector<tinyusdz::value::float2> uv_out;
std::unordered_map<uint64_t, int> points_map;
std::vector<int> faceVertexIndices_out(faceVertexIndices.size());
size_t num_targets = offsets_in.size();
if (num_targets > 0)
{
offsets_out.resize(num_targets);
norm_offsets_out.resize(num_targets);
non_zeros_out.resize(num_targets);
}
for (size_t i = 0; i < faceVertexIndices.size(); i++)
{
PointIn pnt;
pnt.ind_pnt = faceVertexIndices[i];
if (uv_indices_in.size() > 0)
{
int idx_uv = uv_indices_in[i];
pnt.uv = uv_in[idx_uv];
}
else
{
pnt.uv = uv_in[i];
}
uint64_t hash = crc64(0, (unsigned char*)&pnt, sizeof(pnt));
auto iter = points_map.find(hash);
if (iter != points_map.end())
{
faceVertexIndices_out[i] = iter->second;
}
else
{
int idx_out = (int)points_out.size();
points_out.push_back(points_in[pnt.ind_pnt]);
if (norms_in.size() > 0)
{
norms_out.push_back(norms_in[pnt.ind_pnt]);
}
if (num_targets > 0)
{
for (size_t j = 0; j < num_targets; j++)
{
offsets_out[j].push_back(offsets_in[j][pnt.ind_pnt]);
if (norm_offsets_in[j].size() > 0)
{
norm_offsets_out[j].push_back(norm_offsets_in[j][pnt.ind_pnt]);
}
non_zeros_out[j].push_back(non_zeros_in[j][pnt.ind_pnt]);
}
}
if (conv_ji_in.size() > 0)
{
conv_ji_out.push_back(conv_ji_in[pnt.ind_pnt]);
conv_jw_out.push_back(conv_jw_in[pnt.ind_pnt]);
}
uv_out.push_back(pnt.uv);
faceVertexIndices_out[i] = idx_out;
}
}
size_t idx_ind = 0;
for (size_t i = 0; i < faceVertexCounts.size(); i++)
{
int count = faceVertexCounts[i];
if (count == 3)
{
glm::ivec3 face;
if (leftHand)
{
face.z = faceVertexIndices_out[idx_ind]; idx_ind++;
face.y = faceVertexIndices_out[idx_ind]; idx_ind++;
face.x = faceVertexIndices_out[idx_ind]; idx_ind++;
}
else
{
face.x = faceVertexIndices_out[idx_ind]; idx_ind++;
face.y = faceVertexIndices_out[idx_ind]; idx_ind++;
face.z = faceVertexIndices_out[idx_ind]; idx_ind++;
}
faces.push_back(face);
}
else if (count == 4)
{
glm::ivec3 face1;
if (leftHand)
{
face1.z = faceVertexIndices_out[idx_ind]; idx_ind++;
face1.y = faceVertexIndices_out[idx_ind]; idx_ind++;
face1.x = faceVertexIndices_out[idx_ind]; idx_ind++;
}
else
{
face1.x = faceVertexIndices_out[idx_ind]; idx_ind++;
face1.y = faceVertexIndices_out[idx_ind]; idx_ind++;
face1.z = faceVertexIndices_out[idx_ind]; idx_ind++;
}
faces.push_back(face1);
glm::ivec3 face2;
face2.x = face1.z;
face2.y = faceVertexIndices_out[idx_ind]; idx_ind++;
face2.z = face1.x;
faces.push_back(face2);
}
}
offset = buf_out.data.size();
length = points_out.size() * sizeof(glm::vec3);
buf_out.data.resize(offset + length);
memcpy(buf_out.data.data() + offset, points_out.data(), length);
view_id = m_out.bufferViews.size();
{
tinygltf::BufferView view;
view.buffer = 0;
view.byteOffset = offset;
view.byteLength = length;
view.target = TINYGLTF_TARGET_ARRAY_BUFFER;
m_out.bufferViews.push_back(view);
}
acc_id = m_out.accessors.size();
{
tinygltf::Accessor acc;
acc.bufferView = view_id;
acc.byteOffset = 0;
acc.type = TINYGLTF_TYPE_VEC3;
acc.componentType = TINYGLTF_COMPONENT_TYPE_FLOAT;
acc.count = points_out.size();
acc.minValues = { extent.lower[0], extent.lower[1], extent.lower[2] };
acc.maxValues = { extent.upper[0], extent.upper[1], extent.upper[2] };
m_out.accessors.push_back(acc);
}
prim_out.attributes["POSITION"] = acc_id;
if (norms_out.size() > 0)
{
offset = buf_out.data.size();
length = norms_out.size() * sizeof(glm::vec3);
buf_out.data.resize(offset + length);
memcpy(buf_out.data.data() + offset, norms_out.data(), length);
view_id = m_out.bufferViews.size();
{
tinygltf::BufferView view;
view.buffer = 0;
view.byteOffset = offset;
view.byteLength = length;
view.target = TINYGLTF_TARGET_ARRAY_BUFFER;
m_out.bufferViews.push_back(view);
}
acc_id = m_out.accessors.size();
{
tinygltf::Accessor acc;
acc.bufferView = view_id;
acc.byteOffset = 0;
acc.type = TINYGLTF_TYPE_VEC3;
acc.componentType = TINYGLTF_COMPONENT_TYPE_FLOAT;
acc.count = norms_out.size();
m_out.accessors.push_back(acc);
}
prim_out.attributes["NORMAL"] = acc_id;
}
offset = buf_out.data.size();
length = faces.size() * sizeof(glm::ivec3);
buf_out.data.resize(offset + length);
memcpy(buf_out.data.data() + offset, faces.data(), length);