forked from KhronosGroup/COLLADA2GLTF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
COLLADA2GLTFWriter.cpp
1860 lines (1634 loc) · 90 KB
/
COLLADA2GLTFWriter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012, Motorola Mobility, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Motorola Mobility, Inc. nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// reminder; to run recursively against all dae files: find . -name '*.dae' -exec dae2json {} \;
#include "COLLADA2GLTFWriter.h"
#include "GLTFOpenCOLLADAUtils.h"
#include "GLTFExtraDataHandler.h"
#include "COLLADASaxFWLLoader.h"
#include "COLLADAFWFileInfo.h"
#include "GLTF-Open3DGC.h"
#include "profiles/webgl-1.0/GLTFWebGL_1_0_Profile.h"
#include "GitSHA1.h"
#include <algorithm>
#include "commonProfileShaders.h"
#include "helpers/encodingHelpers.h"
#include "COLLADAFWFileInfo.h"
#include "Math/COLLADABUMathPrerequisites.h"
#include "COLLADAFWAnimationList.h"
#if __cplusplus <= 199711L
using namespace std::tr1;
#endif
using namespace std;
using namespace COLLADAFW;
using namespace COLLADABU;
using namespace COLLADASaxFWL;
namespace
{
const double radianPerDegree = Math::PI / 180.0;
}
namespace GLTF
{
/*
*/
COLLADA2GLTFWriter::COLLADA2GLTFWriter(shared_ptr<GLTFAsset> asset) :
_asset(asset),
_visualScene(0){
}
/*
*/
COLLADA2GLTFWriter::~COLLADA2GLTFWriter() {
}
/*
*/
void COLLADA2GLTFWriter::reportError(const std::string& method, const std::string& message) {
printf("ERROR: method:%s message:%s\n", method.c_str(), message.c_str());
}
/*
*/
bool COLLADA2GLTFWriter::write() {
this->_extraDataHandler = new ExtraDataHandler();
//To comply with macro to access config
GLTFAsset *asset = this->_asset.get();
asset->setExtras(this->_extraDataHandler->allExtras());
asset->prepareForProfile(shared_ptr <GLTFWebGL_1_0_Profile>(new GLTFWebGL_1_0_Profile()));
COLLADAFW::Root root(&this->_loader, this);
this->_loader.registerExtraDataCallbackHandler(this->_extraDataHandler);
const std::string& fileData = asset->getInputFileData();
if (fileData.empty())
{
// We don't have any data so read the file
if (!root.loadDocument(asset->getInputFilePath())) {
delete _extraDataHandler;
return false;
}
}
else
{
// We have the data in memory so use it
if (!root.loadDocument(asset->getInputFilePath(), fileData.data(), (int)fileData.size())) {
delete _extraDataHandler;
return false;
}
}
asset->write();
// Cleanup IDs and Technique cache in case we have another conversion
GLTFUtils::resetIDCount();
clearCommonProfileTechniqueCache();
delete _extraDataHandler;
return true;
}
//--------------------------------------------------------------------
void COLLADA2GLTFWriter::cancel(const std::string& errorMessage) {
printf("CONVERTION ABORTED: message:%s\n", errorMessage.c_str());
}
//--------------------------------------------------------------------
void COLLADA2GLTFWriter::start() {
}
//--------------------------------------------------------------------
void COLLADA2GLTFWriter::finish() {
}
//--------------------------------------------------------------------
bool COLLADA2GLTFWriter::writeGlobalAsset(const COLLADAFW::FileInfo* globalAsset) {
GLTFAsset* asset = this->_asset.get();
shared_ptr<JSONObject> assetObject = asset->root()->createObjectIfNeeded(kAsset);
std::string version = "collada2gltf@" + std::string(g_GIT_SHA1);
const COLLADAFW::FileInfo::ValuePairPointerArray& valuePairs = globalAsset->getValuePairArray();
for (size_t i = 0, count = valuePairs.getCount(); i < count; ++i)
{
const COLLADAFW::FileInfo::ValuePair* valuePair = valuePairs[i];
const COLLADAFW::String& key = valuePair->first;
const COLLADAFW::String& value = valuePair->second;
const char *sketchUp = "Google SketchUp";
if ((key == "authoring_tool") && value.length() > 0) {
if (value.find(sketchUp) != string::npos) {
//isolate x.y (version) that is the latest token from a string that is possibily x.y.z
size_t end = value.find_last_of(" ", value.length() - 1);
if (end != string::npos) {
std::string version = value.substr(end);
size_t major = version.find(".", 0);
if (major != string::npos) {
size_t minor = version.find(".", major + 1);
if (minor != string::npos) {
version = version.substr(0, minor);
double sketchUpVersion = atof(version.c_str());
if (sketchUpVersion < 7.1) {
asset->converterConfig()->config()->setBool("invertTransparency", true);
this->_asset->log("WARNING: Fixing transparency - by inverting it - as we convert an asset generated from SketchUp version:%s \n", version.c_str());
}
}
}
}
}
}
}
assetObject->setString("generator", version);
assetObject->setBool(kPremultipliedAlpha, CONFIG_BOOL(asset, kPremultipliedAlpha));
assetObject->setValue(kProfile, asset->profile()->id());
assetObject->setString(kVersion, glTFVersion);
_metersPerUnit = globalAsset->getUnit().getLinearUnitMeter();
if (globalAsset->getUpAxisType() == COLLADAFW::FileInfo::X_UP ||
globalAsset->getUpAxisType() == COLLADAFW::FileInfo::Z_UP)
{
COLLADABU::Math::Matrix4 matrix = COLLADABU::Math::Matrix4::IDENTITY;
if (globalAsset->getUpAxisType() == COLLADAFW::FileInfo::X_UP)
{
// Rotate -90 deg around Z
matrix.setElement(0, 0, 0.0f);
matrix.setElement(0, 1, -1.0f);
matrix.setElement(1, 0, 1.0f);
matrix.setElement(1, 1, 0.0f);
}
else // Z_UP
{
// Rotate 90 deg around X
matrix.setElement(1, 1, 0.0f);
matrix.setElement(1, 2, 1.0f);
matrix.setElement(2, 1, -1.0f);
matrix.setElement(2, 2, 0.0f);
}
_rootTransform = std::shared_ptr<GLTF::JSONObject>(new GLTF::JSONObject());
_rootTransform->setString(kName, "Y_UP_Transform");
_rootTransform->setValue("matrix", serializeOpenCOLLADAMatrix4(matrix));
shared_ptr <GLTF::JSONArray> childrenArray(new GLTF::JSONArray());
_rootTransform->setValue(kChildren, childrenArray);
}
asset->setDistanceScale(globalAsset->getUnit().getLinearUnitMeter());
return true;
}
//--------------------------------------------------------------------
float COLLADA2GLTFWriter::getTransparency(const COLLADAFW::EffectCommon* effectCommon) {
static bool loggedOnce = false;
GLTFAsset* asset = this->_asset.get();
//super naive for now, also need to check sketchup work-around
if (effectCommon->getOpacity().isTexture()) {
return 1;
}
COLLADAFW::EffectCommon::OpaqueMode opaqueMode;
float transparency = 1.0;
opaqueMode = effectCommon->getOpaqueMode();
ColorOrTexture transparent = effectCommon->getTransparent();
double transparentAlpha = (transparent.getType() == ColorOrTexture::COLOR) ? transparent.getColor().getAlpha() : 1.0;
switch (opaqueMode) {
case COLLADAFW::EffectCommon::OpaqueMode::RGB_ZERO:
case COLLADAFW::EffectCommon::OpaqueMode::A_ZERO:
transparency = static_cast<float>(1.0 - transparentAlpha * effectCommon->getTransparency().getFloatValue());
if (!loggedOnce) {
this->_asset->log("WARNING: unsupported opaque mode:%s fallback to A_ONE\n", opaqueModeToString(opaqueMode).c_str());
loggedOnce = true;
}
break;
case COLLADAFW::EffectCommon::OpaqueMode::RGB_ONE:
transparency = static_cast<float>(transparentAlpha * effectCommon->getTransparency().getFloatValue());
if (!loggedOnce) {
this->_asset->log("WARNING: unsupported opaque mode:%s fallback to A_ONE\n", opaqueModeToString(opaqueMode).c_str());
loggedOnce = true;
}
break;
case COLLADAFW::EffectCommon::OpaqueMode::A_ONE:
transparency = static_cast<float>(transparentAlpha * effectCommon->getTransparency().getFloatValue());
break;
case COLLADAFW::EffectCommon::OpaqueMode::UNSPECIFIED_OPAQUE:
default:
transparency = static_cast<float>(effectCommon->getOpacity().getColor().getAlpha());
break;
}
return CONFIG_BOOL(asset, "invertTransparency") ? 1 - transparency : transparency;
}
float COLLADA2GLTFWriter::isOpaque(const COLLADAFW::EffectCommon* effectCommon) {
return getTransparency(effectCommon) >= 1;
}
void COLLADA2GLTFWriter::registerObjectWithOriginalUID(std::string originalId, shared_ptr <JSONObject> obj, shared_ptr <JSONObject> objLib) {
if (this->_asset->_originalIDToTrackedObject.count(originalId) == 0) {
if (!objLib->contains(originalId)) {
objLib->setValue(originalId, obj);
this->_asset->_originalIDToTrackedObject[originalId] = obj;
}
else {
this->_asset->log("WARNING:Object with id:%s is already tracked, failed attempt to add object\n", originalId.c_str());
}
}
else {
this->_asset->log("WARNING:Object with id:%s is already tracked, failed attempt to add object\n", originalId.c_str());
}
}
void COLLADA2GLTFWriter::_storeMaterialBindingArray(const std::string& prefix,
const std::string& nodeUID,
const std::string& meshUID,
MaterialBindingArray &materialBindings) {
if (this->_asset->containsValueForUniqueId(meshUID) == false) {
return;
}
shared_ptr <GLTFMesh> mesh = static_pointer_cast<GLTFMesh>(this->_asset->getValueForUniqueId(meshUID));
this->_asset->setOriginalId(meshUID, mesh->getID());
MaterialBindingsForNodeUID& mb = this->_asset->materialBindingsForNodeUID();
shared_ptr <MaterialBindingsForMeshUID> materialBindingsMap;
if (mb.count(nodeUID) == 0) {
materialBindingsMap = shared_ptr<MaterialBindingsForMeshUID>(new MaterialBindingsForMeshUID());
mb[nodeUID] = materialBindingsMap;
}
else {
materialBindingsMap = mb[nodeUID];
}
//apply prefix on MeshUID
std::string prefixedMeshUID = prefix + meshUID;
shared_ptr <MaterialBindingsPrimitiveMap> materialBindingsPrimitiveMap;
if (materialBindingsMap->count(prefixedMeshUID) == 0) {
materialBindingsPrimitiveMap = shared_ptr<MaterialBindingsPrimitiveMap>(new MaterialBindingsPrimitiveMap());
(*materialBindingsMap)[prefixedMeshUID] = materialBindingsPrimitiveMap;
}
else {
materialBindingsPrimitiveMap = (*materialBindingsMap)[prefixedMeshUID];
}
GLTF::JSONValueVector primitives = mesh->getPrimitives()->values();
for (size_t j = 0; j < primitives.size(); j++) {
shared_ptr <GLTF::GLTFPrimitive> primitive = static_pointer_cast<GLTFPrimitive>(primitives[j]);
//FIXME: consider optimizing this with a hashtable, would be better if it was coming that way from OpenCOLLADA
int materialBindingIndex = -1;
for (size_t k = 0; k < materialBindings.getCount(); k++) {
if (materialBindings[k].getMaterialId() == primitive->getMaterialObjectID()) {
materialBindingIndex = (int)k;
}
}
if (materialBindingIndex != -1) {
shared_ptr <COLLADAFW::MaterialBinding> materialBinding(new COLLADAFW::MaterialBinding(materialBindings[materialBindingIndex]));
(*materialBindingsPrimitiveMap)[primitive->getMaterialObjectID()] = materialBinding;
}
}
// Cache existing mappings for later re-use
MaterialBindingSetsForMeshUID& mbForMeshUID = this->_asset->materialBindingSetsForMeshUID();
MaterialBindingSet& materialBindingSet = mbForMeshUID[prefixedMeshUID];
for(size_t k = 0; k < materialBindings.getCount(); k++) {
materialBindingSet.insert(materialBindings[k].getReferencedMaterial());
}
return;
}
bool bufferEquals(float* first, float* second, int size, double epsilon) {
for (int i = 0; i < size; i++) {
if (fabs(first[i] - second[i]) > epsilon) {
return false;
}
}
return true;
}
COLLADABU::Math::Matrix4 getTransformationMatrix(const Transformation* transform) {
switch (transform->getTransformationType()) {
case Transformation::ROTATE: {
Rotate* rotate = (Rotate*)transform;
COLLADABU::Math::Vector3 axis = rotate->getRotationAxis();
axis.normalise();
double angle = rotate->getRotationAngle();
return COLLADABU::Math::Matrix4(COLLADABU::Math::Quaternion(COLLADABU::Math::Utils::degToRad(angle), axis));
}
case Transformation::TRANSLATE: {
Translate* translate = (Translate*)transform;
const COLLADABU::Math::Vector3& translation = translate->getTranslation();
COLLADABU::Math::Matrix4 translationMatrix;
translationMatrix.makeTrans(translation);
return translationMatrix;
}
case Transformation::SCALE: {
Scale* scale = (Scale*)transform;
const COLLADABU::Math::Vector3& scaleVector = scale->getScale();
COLLADABU::Math::Matrix4 scaleMatrix;
scaleMatrix.makeScale(scaleVector);
return scaleMatrix;
}
case Transformation::MATRIX: {
return ((Matrix*)transform)->getMatrix();
}
}
return COLLADABU::Math::Matrix4::IDENTITY;
}
COLLADABU::Math::Matrix4 getFlattenedTransform(vector<const Transformation*> transforms) {
COLLADABU::Math::Matrix4 matrix = COLLADABU::Math::Matrix4::IDENTITY;
for (const Transformation* transform : transforms) {
switch (transform->getTransformationType()) {
case Transformation::ROTATE: {
Rotate* rotate = (Rotate*)transform;
COLLADABU::Math::Vector3 axis = rotate->getRotationAxis();
axis.normalise();
double angle = rotate->getRotationAngle();
matrix = matrix * COLLADABU::Math::Matrix4(COLLADABU::Math::Quaternion(COLLADABU::Math::Utils::degToRad(angle), axis));
break;
}
case Transformation::TRANSLATE: {
Translate* translate = (Translate*)transform;
const COLLADABU::Math::Vector3& translation = translate->getTranslation();
COLLADABU::Math::Matrix4 translationMatrix;
translationMatrix.makeTrans(translation);
matrix = matrix * translationMatrix;
break;
}
case Transformation::SCALE: {
Scale* scale = (Scale*)transform;
const COLLADABU::Math::Vector3& scaleVector = scale->getScale();
COLLADABU::Math::Matrix4 scaleMatrix;
scaleMatrix.makeScale(scaleVector);
matrix = matrix * scaleMatrix;
break;
}
case Transformation::MATRIX: {
Matrix* transformMatrix = (Matrix*)transform;
matrix = matrix * transformMatrix->getMatrix();
break;
}
case Transformation::LOOKAT: {
Lookat* lookAt = (Lookat*)transform;
buildLookAtMatrix(lookAt, matrix);
break;
}
}
}
return matrix;
}
map<COLLADAFW::Transformation::TransformationType, float*> decomposeTransformationMatrix(COLLADABU::Math::Matrix4 matrix, vector<const Transformation*> transforms) {
map<COLLADAFW::Transformation::TransformationType, float*> decomposition;
float* scale = new float[3];
float* translation = new float[3];
float* rotation = new float[4];
GLTF::decomposeMatrix(matrix, translation, rotation, scale);
if (scale[0] == 0.0 && scale[1] == 0.0 && scale[2] == 0.0)
{
// Matrix decompose failed because of a uniform scaling of 0 in the transformations.
// We've lost the rotation information. We'll have to manually extract the rotations.
Math::Quaternion rotationQuat = Math::Quaternion::IDENTITY;
for (const Transformation* transform : transforms)
{
if (transform->getTransformationType() == Transformation::ROTATE)
{
Rotate* rotate = (Rotate*)transform;
Math::Vector3 axis = rotate->getRotationAxis();
axis.normalise();
double angle = rotate->getRotationAngle();
rotationQuat = rotationQuat * Math::Quaternion(Math::Utils::degToRad(angle), axis);
}
}
Math::Real angle;
Math::Vector3 axis;
rotationQuat.toAngleAxis(angle, axis);
rotation[0] = (float)axis.x;
rotation[1] = (float)axis.y;
rotation[2] = (float)axis.z;
rotation[3] = (float)angle;
}
decomposition[COLLADAFW::Transformation::TransformationType::SCALE] = scale;
decomposition[COLLADAFW::Transformation::TransformationType::TRANSLATE] = translation;
decomposition[COLLADAFW::Transformation::TransformationType::ROTATE] = rotation;
return decomposition;
}
bool COLLADA2GLTFWriter::writeNode(const COLLADAFW::Node* node, shared_ptr <GLTF::JSONObject> nodeObject, string nodeOriginalId) {
GLTFAsset *asset = this->_asset.get();
const NodePointerArray& nodes = node->getChildNodes();
std::string uniqueUID = node->getUniqueId().toAscii();
nodeObject->setString(kName, node->getName());
this->_asset->_uniqueIDToOpenCOLLADAObject[uniqueUID] = shared_ptr <COLLADAFW::Object>(node->clone());
this->_asset->setOriginalId(uniqueUID, nodeOriginalId);
this->_asset->setValueForUniqueId(uniqueUID, nodeObject);
if (node->getType() == COLLADAFW::Node::JOINT) {
const string& sid = node->getSid();
nodeObject->setString(kJointName, sid);
}
const InstanceCameraPointerArray& instanceCameras = node->getInstanceCameras();
size_t camerasCount = instanceCameras.getCount();
if (camerasCount > 0) {
InstanceCamera* instanceCamera = instanceCameras[0];
shared_ptr<GLTF::JSONObject> cameraObject(new GLTF::JSONObject());
std::string id = instanceCamera->getInstanciatedObjectId().toAscii();
std::string cameraId = this->_asset->getOriginalId(id);
nodeObject->setString(kCamera, cameraId);
}
const InstanceControllerPointerArray& instanceControllers = node->getInstanceControllers();
unsigned int count = (unsigned int)instanceControllers.getCount();
if (count > 0) {
shared_ptr<JSONObject> skins = this->_asset->root()->createObjectIfNeeded(kSkins);
for (unsigned int i = 0; i < count; i++) {
InstanceController* instanceController = instanceControllers[i];
MaterialBindingArray &materialBindings = instanceController->getMaterialBindings();
COLLADAFW::UniqueId uniqueId = instanceController->getInstanciatedObjectId();
if (asset->containsValueForUniqueId(uniqueId.toAscii())) {
shared_ptr<JSONString> skinControllerDataUID = static_pointer_cast<JSONString>(asset->getValueForUniqueId(uniqueId.toAscii()));
shared_ptr<GLTFSkin> skin = static_pointer_cast<GLTFSkin>(skins->getObject(skinControllerDataUID->getString()));
UniqueId meshUniqueId(skin->getSourceUID());
_storeMaterialBindingArray("skin-meshes-",
node->getUniqueId().toAscii(),
meshUniqueId.toAscii(),
materialBindings);
shared_ptr<JSONArray> skeletons(new JSONArray());
for (size_t k = 0; k < instanceController->skeletons().size(); k++) {
std::string skeleton = instanceController->skeletons()[k].getFragment();
skeletons->appendValue(shared_ptr<JSONString>(new JSONString(skeleton)));
}
nodeObject->setValue("skeletons", skeletons);
nodeObject->setString(kSkin, skin->getId());
}
}
}
// save mesh
const InstanceGeometryPointerArray& instanceGeometries = node->getInstanceGeometries();
count = (unsigned int)instanceGeometries.getCount();
if (count > 0) {
for (unsigned int i = 0; i < count; i++) {
InstanceGeometry* instanceGeometry = instanceGeometries[i];
COLLADAFW::UniqueId uniqueId = instanceGeometry->getInstanciatedObjectId();
std::string meshUID = uniqueId.toAscii();
MaterialBindingArray& materialBindings = instanceGeometry->getMaterialBindings();
if (materialBindings.getCount() > 0) {
MaterialBinding materialBinding = materialBindings[0];
COLLADAFW::UniqueId materialId = materialBinding.getReferencedMaterial();
// Check if this geometry has already been bound to another node with a different material
bool alreadyBound = false;
auto nodeBindings = this->_asset->materialBindingSetsForMeshUID().find("meshes-" + uniqueId.toAscii());
if (nodeBindings != this->_asset->materialBindingSetsForMeshUID().end()) {
MaterialBindingSet& bindingSet = nodeBindings->second;
bool materialUsed = bindingSet.find(materialId) != bindingSet.end();
alreadyBound = !materialUsed; // ie, it was bound, but to a different material
}
if (alreadyBound) {
// This is an instance of a material
shared_ptr<GLTFMesh> mesh = static_pointer_cast<GLTFMesh>(this->_asset->getValueForUniqueId(uniqueId.toAscii()));
// Create a unique instance of the mesh so that it can bind to different materials
while (asset->containsValueForUniqueId(meshUID)) {
uniqueId = COLLADAFW::UniqueId(uniqueId.getClassId(), uniqueId.getObjectId() + 1, uniqueId.getFileId());
meshUID = mesh->getID() + "-" + std::to_string(uniqueId.getObjectId() + 1);
}
shared_ptr<GLTFMesh> meshInstance = mesh->clone();
meshInstance->setID(meshUID);
meshInstance->setName(meshUID);
asset->root()->createObjectIfNeeded(kMeshes)->setValue(meshUID, meshInstance);
asset->setValueForUniqueId(meshUID, meshInstance);
}
}
if (meshUID != "") {
_storeMaterialBindingArray("meshes-",
node->getUniqueId().toAscii(),
meshUID,
materialBindings);
}
}
}
shared_ptr <GLTF::JSONArray> childrenArray(new GLTF::JSONArray());
nodeObject->setValue(kChildren, childrenArray);
count = (unsigned int)nodes.getCount();
for (unsigned int i = 0; i < count; i++) {
std::string childOriginalID = nodes[i]->getOriginalId();
if (childOriginalID.length() == 0) {
childOriginalID = uniqueIdWithType(kNode, nodes[i]->getUniqueId());
}
childrenArray->appendValue(shared_ptr <GLTF::JSONString>(new GLTF::JSONString(childOriginalID)));
}
const InstanceNodePointerArray& instanceNodes = node->getInstanceNodes();
count = (unsigned int)instanceNodes.getCount();
for (unsigned int i = 0; i < count; i++) {
InstanceNode* instanceNode = instanceNodes[i];
std::string id = instanceNode->getInstanciatedObjectId().toAscii();
shared_ptr<JSONArray> parents;
if (this->_asset->_uniqueIDToParentsOfInstanceNode.count(id) == 0) {
parents = shared_ptr<JSONArray>(new JSONArray());
this->_asset->_uniqueIDToParentsOfInstanceNode[id] = parents;
}
else {
parents = this->_asset->_uniqueIDToParentsOfInstanceNode[id];
}
parents->appendValue(shared_ptr<JSONString>(new JSONString(node->getUniqueId().toAscii())));
if (this->_asset->containsValueForUniqueId(id)) {
std::string instanceNodeOriginalId = this->_asset->getOriginalId(id);
childrenArray->appendValue(shared_ptr <GLTF::JSONString>(new GLTF::JSONString(instanceNodeOriginalId)));
}
}
shared_ptr <GLTF::JSONArray> lightsInNode(new GLTF::JSONArray());
const InstanceLightPointerArray& instanceLights = node->getInstanceLights();
count = (unsigned int)instanceLights.getCount();
//For a given light, keep track of all the nodes holding it
if (count) {
shared_ptr<JSONObject> extension = this->_asset->root()->createObjectIfNeeded(kExtensions);
shared_ptr<JSONObject> khrMaterialsCommon = extension->createObjectIfNeeded("KHR_materials_common");
shared_ptr<JSONObject> lights = khrMaterialsCommon->createObjectIfNeeded(kLights);
for (unsigned int i = 0; i < count; i++) {
InstanceLight* instanceLight = instanceLights[i];
std::string id = instanceLight->getInstanciatedObjectId().toAscii();
shared_ptr<JSONObject> light = static_pointer_cast<JSONObject>(this->_asset->getValueForUniqueId(id));
if (light) {
std::string lightUID = this->_asset->getOriginalId(id);
shared_ptr<JSONArray> listOfNodesPerLight;
if (this->_asset->_uniqueIDOfLightToNodes.count(id) == 0) {
listOfNodesPerLight = shared_ptr<JSONArray>(new JSONArray());
this->_asset->_uniqueIDOfLightToNodes[lightUID] = listOfNodesPerLight;
}
else {
listOfNodesPerLight = this->_asset->_uniqueIDOfLightToNodes[lightUID];
}
listOfNodesPerLight->appendValue(JSONSTRING(nodeOriginalId));
lightsInNode->appendValue(shared_ptr <JSONString>(new JSONString(lightUID)));
lights->setValue(lightUID, light);
}
}
//We just want a single light per node
//https://github.com/KhronosGroup/glTF/issues/13
//lightKhrMaterialsCommon->setValue("lights", lightsInNode);
if (lightsInNode->values().size() > 0 && CONFIG_BOOL(asset, "useKhrMaterialsCommon")) {
shared_ptr<JSONObject> lightExtension = nodeObject->createObjectIfNeeded(kExtensions);
shared_ptr<JSONObject> lightKhrMaterialsCommon = lightExtension->createObjectIfNeeded("KHR_materials_common");
lightKhrMaterialsCommon->setValue(kLight, lightsInNode->values()[0]);
if (count > 1) {
//FR: AFAIK no authoring tool export multiple light per node, but we'll warn if that's the case
//To fix this, dummy sub nodes should be created.
static bool printedOnce = false;
if (printedOnce) {
this->_asset->log("WARNING: some unhandled lights because some nodes carry more than a single light\n");
printedOnce = false;
}
}
}
}
return true;
}
// Flattening [UNFINISHED CODE]
//conditions for flattening
// -> same material
// option to merge of not non-opaque geometry
// -> check per primitive that sources / semantic layout matches
// [meshAttributes]
// -> for all meshes
// -> collect all kind of semantic
// -> for all meshes
// -> get all meshAttributes
// -> transforms & write vtx attributes
bool COLLADA2GLTFWriter::processSceneFlatteningInfo(SceneFlatteningInfo* sceneFlatteningInfo) {
/*
MeshFlatteningInfoVector allMeshes = sceneFlatteningInfo->allMeshes;
//First collect all kind of meshAttributes available
size_t count = allMeshes.size();
for (size_t i = 0 ; i < count ; i++) {
shared_ptr <MeshFlatteningInfo> meshInfo = allMeshes[i];
MeshVectorSharedPtr *meshes = this->_uniqueIDToMeshes[meshInfo->getUID()];
// shared_ptr <MeshAttributeVector> meshAttributes = mesh->meshAttributes();
}
*/
return true;
}
bool COLLADA2GLTFWriter::writeVisualScene(const COLLADAFW::VisualScene* visualScene) {
//FIXME: only one visual scene assumed/handled
shared_ptr <GLTF::JSONObject> scenesObject(new GLTF::JSONObject());
shared_ptr <GLTF::JSONObject> sceneObject(new GLTF::JSONObject());
shared_ptr <GLTF::JSONObject> nodesObject = this->_asset->root()->createObjectIfNeeded(kNodes);
const NodePointerArray& nodePointerArray = visualScene->getRootNodes();
size_t nodeCount = nodePointerArray.getCount();
this->_asset->root()->setValue(kScenes, scenesObject);
this->_asset->root()->setString(kScene, "defaultScene");
scenesObject->setValue("defaultScene", sceneObject); //FIXME: should use this id -> visualScene->getOriginalId()
//first pass to output children name of our root node
shared_ptr <GLTF::JSONArray> childrenArray;
if (_rootTransform) {
// Add the root transform to the nodes
std::string yUpNodeID = uniqueIdWithType(kNode, this->_loader.getUniqueId(COLLADAFW::COLLADA_TYPE::NODE));
nodesObject->setValue(yUpNodeID, _rootTransform);
// Create a children array for the scene and add the root transform to it
shared_ptr <GLTF::JSONArray> sceneChildrenArray(new GLTF::JSONArray());
sceneObject->setValue(kNodes, sceneChildrenArray);
shared_ptr <GLTF::JSONString> rootIDValue(new GLTF::JSONString(yUpNodeID));
sceneChildrenArray->appendValue(static_pointer_cast <GLTF::JSONValue> (rootIDValue));
// Set childrenArray to the root transform's children array so all root nodes will become its children
childrenArray = std::static_pointer_cast<GLTF::JSONArray>(_rootTransform->getValue(kChildren));
}
else {
// No root transform so just add all root nodes to the scene's children array
childrenArray = std::shared_ptr<GLTF::JSONArray>(new GLTF::JSONArray());
sceneObject->setValue(kNodes, childrenArray);
}
for (size_t i = 0; i < nodeCount; i++) {
COLLADAFW::Node* childNode = nodePointerArray[i];
std::string nodeUID = childNode->getOriginalId();
if (nodeUID.length() == 0) {
nodeUID = uniqueIdWithType(kNode, nodePointerArray[i]->getUniqueId());
childNode->setOriginalId(nodeUID);
}
shared_ptr <GLTF::JSONString> nodeIDValue(new GLTF::JSONString(nodeUID));
childrenArray->appendValue(static_pointer_cast <GLTF::JSONValue> (nodeIDValue));
}
vector<const COLLADAFW::Node*> nodes;
for (size_t i = 0; i < nodeCount; i++) {
nodes.push_back(nodePointerArray[i]);
}
return writeNodes(nodes);
}
//--------------------------------------------------------------------
bool COLLADA2GLTFWriter::writeScene(const COLLADAFW::Scene* scene) {
return true;
}
//--------------------------------------------------------------------
bool COLLADA2GLTFWriter::writeLibraryNodes(const COLLADAFW::LibraryNodes* libraryNodes) {
vector<const COLLADAFW::Node*> nodes;
const NodePointerArray& nodeArray = libraryNodes->getNodes();
for (size_t i = 0; i < nodeArray.getCount(); i++) {
const COLLADAFW::Node* node = nodeArray[i];
std::string id = node->getUniqueId().toAscii();
if (this->_asset->_uniqueIDToParentsOfInstanceNode.count(id) > 0) {
shared_ptr<JSONArray> parents = this->_asset->_uniqueIDToParentsOfInstanceNode[id];
std::vector <shared_ptr <JSONValue> > values = parents->values();
for (size_t k = 0; k < values.size(); k++) {
shared_ptr<JSONString> value = static_pointer_cast<JSONString>(values[k]);
shared_ptr<JSONObject> parentNode = static_pointer_cast<JSONObject>(this->_asset->getValueForUniqueId(value->getString()));
if (parentNode) {
shared_ptr <JSONArray> children = parentNode->createArrayIfNeeded(kChildren);
children->appendValue(shared_ptr <JSONString>(new JSONString(node->getOriginalId())));
}
}
}
nodes.push_back(node);
}
return writeNodes(nodes);
}
void writeTransform(shared_ptr<GLTF::GLTFAsset> asset, shared_ptr<GLTF::JSONObject> nodeObject, COLLADABU::Math::Matrix4 matrix, vector<const Transformation*> transformations, bool useTRS) {
if (useTRS) {
map<COLLADAFW::Transformation::TransformationType, float*> decomposition = decomposeTransformationMatrix(matrix, transformations);
float* translation = decomposition[COLLADAFW::Transformation::TransformationType::TRANSLATE];
float* rotation = decomposition[COLLADAFW::Transformation::TransformationType::ROTATE];
float* scale = decomposition[COLLADAFW::Transformation::TransformationType::SCALE];
// Scale distance units if we need to
translation[0] *= (float)asset->getDistanceScale();
translation[1] *= (float)asset->getDistanceScale();
translation[2] *= (float)asset->getDistanceScale();
bool exportDefaultValues = CONFIG_BOOL(asset, "exportDefaultValues");
bool exportTranslation = !(!exportDefaultValues &&
((translation[0] == 0) && (translation[1] == 0) && (translation[2] == 0)));
if (exportTranslation)
nodeObject->setValue("translation", serializeVec3(translation[0], translation[1], translation[2]));
// Rotation is a quaternion [V, s]
nodeObject->setValue("rotation", serializeVec4(rotation[0], rotation[1], rotation[2], rotation[3]));
bool exportScale = !(!exportDefaultValues && ((scale[0] == 1) && (scale[1] == 1) && (scale[2] == 1)));
if (exportScale)
nodeObject->setValue("scale", serializeVec3(scale[0], scale[1], scale[2]));
}
else {
matrix.scaleTrans(asset->getDistanceScale());
bool exportMatrix = !((matrix == COLLADABU::Math::Matrix4::IDENTITY && (CONFIG_BOOL(asset, "exportDefaultValues") == false)));
if (exportMatrix) {
nodeObject->setValue("matrix", serializeOpenCOLLADAMatrix4(matrix));
}
}
}
bool COLLADA2GLTFWriter::writeNodes(vector<const COLLADAFW::Node*> nodes) {
shared_ptr<GLTF::JSONObject> nodesObject = this->_asset->root()->createObjectIfNeeded(kNodes);
vector<const Transformation*> nodeTransforms;
COLLADABU::Math::Matrix4 matrix;
for (const COLLADAFW::Node* node : nodes) {
std::string baseId = node->getOriginalId();
std::string id = baseId;
shared_ptr <GLTF::JSONObject> nodeObject(new GLTF::JSONObject());
TransformationPointerArray transformations = node->getTransformations();
bool needsRoot = true;
for (size_t i = 0; i < transformations.getCount(); i++) {
const Transformation* transformation = transformations[i];
UniqueId animationListId = transformation->getAnimationList();
if (animationListId.isValid()) {
this->_asset->_transformationForAnimationListId[animationListId] = transformation->clone();
// Split off any pre-existing transforms
if (nodeTransforms.size() > 0) {
matrix = getFlattenedTransform(nodeTransforms);
if (matrix != COLLADABU::Math::Matrix4::IDENTITY) {
shared_ptr<JSONArray> children = nodeObject->createArrayIfNeeded(kChildren);
nodeObject = shared_ptr<GLTF::JSONObject>(new GLTF::JSONObject());
if (!needsRoot) {
id = "_" + baseId + "_split_" + to_string((int)animationListId.getObjectId());
}
children->appendValue(shared_ptr<JSONString>(new JSONString(id)));
writeTransform(this->_asset, nodeObject, matrix, nodeTransforms, false);
nodesObject->setValue(id, nodeObject);
needsRoot = false;
}
}
// Make a new node to target for the animation
shared_ptr<JSONArray> children = nodeObject->createArrayIfNeeded(kChildren);
nodeObject = shared_ptr<GLTF::JSONObject>(new GLTF::JSONObject());
if (!needsRoot) {
id = "_" + baseId + "_target_" + to_string((int)animationListId.getObjectId());
}
else {
needsRoot = false;
}
this->_asset->_animationListIdForNodeId[id] = animationListId;
this->_asset->_nodeIdForAnimationListId[animationListId] = id;
children->appendValue(shared_ptr<JSONString>(new JSONString(id)));
matrix = getTransformationMatrix(transformation);
writeTransform(this->_asset, nodeObject, matrix, nodeTransforms, true);
nodesObject->setValue(id, nodeObject);
nodeTransforms.clear();
}
else {
// Flatten this transform into the node.
nodeTransforms.push_back(transformation->clone());
}
}
// Write out any remaining transforms
matrix = COLLADABU::Math::Matrix4::IDENTITY;
if (nodeTransforms.size() > 0) {
matrix = getFlattenedTransform(nodeTransforms);
if (matrix != COLLADABU::Math::Matrix4::IDENTITY) {
if (!needsRoot) {
shared_ptr<JSONArray> children = nodeObject->createArrayIfNeeded(kChildren);
nodeObject = shared_ptr<GLTF::JSONObject>(new GLTF::JSONObject());
id = "_" + baseId + "_split";
children->appendValue(shared_ptr<JSONString>(new JSONString(id)));
}
writeTransform(this->_asset, nodeObject, matrix, nodeTransforms, false);
}
nodeTransforms.clear();
}
nodesObject->setValue(id, nodeObject);
writeNode(node, nodeObject, id);
vector<const COLLADAFW::Node*> children;
NodePointerArray childNodes = node->getChildNodes();
if (childNodes.getCount() > 0) {
for (size_t i = 0; i < childNodes.getCount(); i++) {
COLLADAFW::Node* childNode = childNodes[i];
std::string nodeUID = childNode->getOriginalId();
if (nodeUID.length() == 0) {
nodeUID = uniqueIdWithType(kNode, childNode->getUniqueId());
childNode->setOriginalId(nodeUID);
}
children.push_back(childNode);
}
writeNodes(children);
}
}
return true;
}
//--------------------------------------------------------------------
bool COLLADA2GLTFWriter::writeGeometry(const COLLADAFW::Geometry* geometry) {
switch (geometry->getType()) {
case Geometry::GEO_TYPE_MESH:
{
const COLLADAFW::Mesh* mesh = (COLLADAFW::Mesh*)geometry;
std::string meshUID = geometry->getUniqueId().toAscii();
if (this->_asset->containsValueForUniqueId(meshUID) == false) {
shared_ptr<GLTFMesh> cvtMesh = convertOpenCOLLADAMesh((COLLADAFW::Mesh*)mesh, this->_asset.get());
if (cvtMesh != nullptr) {
this->_asset->root()->createObjectIfNeeded(kMeshes)->setValue(cvtMesh->getID(), cvtMesh);
this->_asset->setValueForUniqueId(meshUID, cvtMesh);
}
}
}
break;
case Geometry::GEO_TYPE_SPLINE:
case Geometry::GEO_TYPE_CONVEX_MESH:
// FIXME: handle convertion to mesh
case Geometry::GEO_TYPE_UNKNOWN:
//FIXME: handle error
default:
return false;
}
return true;
}
//--------------------------------------------------------------------
bool COLLADA2GLTFWriter::writeMaterial(const COLLADAFW::Material* material) {
const UniqueId& effectUID = material->getInstantiatedEffect();
std::string materialID = material->getUniqueId().toAscii();
this->_asset->_materialUIDToName[materialID] = material->getName();
this->_asset->_materialUIDToEffectUID[materialID] = effectUID;
return true;
}
//--------------------------------------------------------------------
unsigned int __GetGLWrapMode(COLLADAFW::Sampler::WrapMode wrapMode, GLTFProfile *profile) {
switch (wrapMode) {
case COLLADAFW::Sampler::WRAP_MODE_UNSPECIFIED:
case COLLADAFW::Sampler::WRAP_MODE_NONE:
case COLLADAFW::Sampler::WRAP_MODE_WRAP:
return profile->getGLenumForString("REPEAT");
case COLLADAFW::Sampler::WRAP_MODE_MIRROR:
return profile->getGLenumForString("MIRRORED_REPEAT");
case COLLADAFW::Sampler::WRAP_MODE_CLAMP:
return profile->getGLenumForString("CLAMP_TO_EDGE");
default:
break;
}
return profile->getGLenumForString("REPEAT");
}
static unsigned int __GetFilterMode(COLLADAFW::Sampler::SamplerFilter wrapMode, GLTFProfile *profile) {
switch (wrapMode) {
case COLLADAFW::Sampler::SAMPLER_FILTER_UNSPECIFIED:
case COLLADAFW::Sampler::SAMPLER_FILTER_NONE:
case COLLADAFW::Sampler::SAMPLER_FILTER_LINEAR:
return profile->getGLenumForString("LINEAR");
case COLLADAFW::Sampler::SAMPLER_FILTER_NEAREST:
return profile->getGLenumForString("NEAREST");
case COLLADAFW::Sampler::SAMPLER_FILTER_NEAREST_MIPMAP_NEAREST:
return profile->getGLenumForString("NEAREST_MIPMAP_NEAREST");
case COLLADAFW::Sampler::SAMPLER_FILTER_LINEAR_MIPMAP_NEAREST:
return profile->getGLenumForString("LINEAR_MIPMAP_NEAREST");
case COLLADAFW::Sampler::SAMPLER_FILTER_NEAREST_MIPMAP_LINEAR:
return profile->getGLenumForString("NEAREST_MIPMAP_LINEAR");
case COLLADAFW::Sampler::SAMPLER_FILTER_LINEAR_MIPMAP_LINEAR:
return profile->getGLenumForString("LINEAR_MIPMAP_LINEAR");
default:
break;
}
return profile->getGLenumForString("LINEAR");
}
std::string COLLADA2GLTFWriter::getSamplerUIDForParameters(unsigned int wrapS,
unsigned int wrapT,
unsigned int minFilter,
unsigned int maxFilter) {
std::string samplerHash = GLTFUtils::toString(wrapS) + GLTFUtils::toString(wrapT) + GLTFUtils::toString(minFilter) + GLTFUtils::toString(maxFilter);
bool addSampler = false;
size_t index = 0;
if (this->_asset->_samplerHashtoSamplerIndex.count(samplerHash) == 0) {
index = this->_asset->_samplerHashtoSamplerIndex.size();
this->_asset->_samplerHashtoSamplerIndex[samplerHash] = (unsigned int)index;
addSampler = true;
}
else {
index = this->_asset->_samplerHashtoSamplerIndex[samplerHash];
}
std::string samplerUID = "sampler_" + GLTFUtils::toString(index);
if (addSampler) {
shared_ptr <JSONObject> sampler2D(new JSONObject());
sampler2D->setUnsignedInt32("wrapS", wrapS);
sampler2D->setUnsignedInt32("wrapT", wrapT);
sampler2D->setUnsignedInt32("minFilter", minFilter);
sampler2D->setUnsignedInt32("magFilter", maxFilter);
shared_ptr <GLTF::JSONObject> samplers = this->_asset->root()->createObjectIfNeeded("samplers");
samplers->setValue(samplerUID, sampler2D);
}
return samplerUID;
}
void COLLADA2GLTFWriter::_installTextureSlot(Sampler* sampler,
const std::string& slotName,
const std::string& texcoord,
shared_ptr <GLTFAsset> asset,
shared_ptr<GLTFEffect> cvtEffect)
{
assert(sampler);
assert(asset);
assert(cvtEffect);
shared_ptr <JSONObject> values = cvtEffect->getValues();
shared_ptr <JSONObject> khrMaterialsCommonValues = cvtEffect->getKhrMaterialsCommonValues();