-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
modeldrawable.cpp
1971 lines (1657 loc) · 56.1 KB
/
modeldrawable.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
/** @file modeldrawable.cpp Drawable specialized for 3D models.
*
* @authors Copyright (c) 2014-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* LGPL: http://www.gnu.org/licenses/lgpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "de/ModelDrawable"
#include "de/HeightMap"
#include "de/ImageFile"
#include <de/Animation>
#include <de/App>
#include <de/ByteArrayFile>
#include <de/Folder>
#include <de/GLBuffer>
#include <de/GLProgram>
#include <de/GLState>
#include <de/GLUniform>
#include <de/Matrix>
#include <de/NativePath>
#include <de/TextureBank>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/Importer.hpp>
#include <assimp/LogStream.hpp>
#include <assimp/DefaultLogger.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <array>
namespace de {
namespace internal {
/// Adapter between de::File and Assimp.
class ImpIOStream : public Assimp::IOStream
{
public:
ImpIOStream(ByteArrayFile const &file) : _file(file), _pos(0)
{}
size_t Read(void *pvBuffer, size_t pSize, size_t pCount)
{
size_t const num = pSize * pCount;
_file.get(_pos, reinterpret_cast<IByteArray::Byte *>(pvBuffer), num);
_pos += num;
return pCount;
}
size_t Write(void const *, size_t, size_t)
{
throw Error("ImpIOStream::Write", "Writing not allowed");
}
aiReturn Seek(size_t pOffset, aiOrigin pOrigin)
{
switch (pOrigin)
{
case aiOrigin_SET:
_pos = pOffset;
break;
case aiOrigin_CUR:
_pos += pOffset;
break;
case aiOrigin_END:
_pos = _file.size() - pOffset;
break;
default:
break;
}
return aiReturn_SUCCESS;
}
size_t Tell() const
{
return _pos;
}
size_t FileSize() const
{
return _file.size();
}
void Flush() {}
private:
ByteArrayFile const &_file;
size_t _pos;
};
/**
* Adapter between FS2 and Assimp. Each ModelDrawable instance has its own
* instance of this class.
*/
struct ImpIOSystem : public Assimp::IOSystem
{
/// Reference for resolving relative paths. This is the folder of the
/// model currently being imported.
String referencePath;
ImpIOSystem() {}
~ImpIOSystem() {}
char getOsSeparator() const { return '/'; }
Path resolvePath(char const *fn) const
{
Path path(fn);
if (path.isAbsolute()) return path;
return referencePath / path;
}
bool Exists(char const *pFile) const
{
return App::rootFolder().has(resolvePath(pFile));
}
Assimp::IOStream *Open(char const *pFile, char const *)
{
Path const path = resolvePath(pFile);
return new ImpIOStream(App::rootFolder().locate<ByteArrayFile const>(path));
}
void Close(Assimp::IOStream *pFile)
{
delete pFile;
}
};
struct ImpLogger : public Assimp::LogStream
{
void write(char const *message)
{
LOG_GL_VERBOSE("[ai] %s") << message;
}
static void registerLogger()
{
if (registered) return;
registered = true;
Assimp::DefaultLogger::get()->attachStream(
new ImpLogger,
Assimp::Logger::Info |
Assimp::Logger::Warn |
Assimp::Logger::Err);
}
static bool registered;
};
bool ImpLogger::registered = false;
struct DefaultImageLoader : public ModelDrawable::IImageLoader
{
Image loadImage(String const &path)
{
Image img = App::rootFolder().locate<ImageFile>(path).image();
if (img.depth() == 24)
{
// Model texture atlases need to have an alpha channel.
DENG2_ASSERT(img.canConvertToQImage());
return Image(img.toQImage().convertToFormat(QImage::Format_ARGB32));
}
return img;
}
};
static DefaultImageLoader defaultImageLoader;
} // namespace internal
using namespace internal;
static int const MAX_BONES = 64;
static int const MAX_BONES_PER_VERTEX = 4;
static int const MAX_TEXTURES = 4;
struct ModelVertex
{
Vector3f pos;
Vector4f color;
Vector4f boneIds;
Vector4f boneWeights;
Vector3f normal;
Vector3f tangent;
Vector3f bitangent;
Vector2f texCoord;
Vector4f texBounds[4];
LIBGUI_DECLARE_VERTEX_FORMAT(12)
};
AttribSpec const ModelVertex::_spec[12] = {
{ AttribSpec::Position, 3, GL_FLOAT, false, sizeof(ModelVertex), 0 },
{ AttribSpec::Color, 4, GL_FLOAT, false, sizeof(ModelVertex), 3 * sizeof(float) },
{ AttribSpec::BoneIDs, 4, GL_FLOAT, false, sizeof(ModelVertex), 7 * sizeof(float) },
{ AttribSpec::BoneWeights, 4, GL_FLOAT, false, sizeof(ModelVertex), 11 * sizeof(float) },
{ AttribSpec::Normal, 3, GL_FLOAT, false, sizeof(ModelVertex), 15 * sizeof(float) },
{ AttribSpec::Tangent, 3, GL_FLOAT, false, sizeof(ModelVertex), 18 * sizeof(float) },
{ AttribSpec::Bitangent, 3, GL_FLOAT, false, sizeof(ModelVertex), 21 * sizeof(float) },
{ AttribSpec::TexCoord0, 2, GL_FLOAT, false, sizeof(ModelVertex), 24 * sizeof(float) },
{ AttribSpec::TexBounds0, 4, GL_FLOAT, false, sizeof(ModelVertex), 26 * sizeof(float) },
{ AttribSpec::TexBounds1, 4, GL_FLOAT, false, sizeof(ModelVertex), 30 * sizeof(float) },
{ AttribSpec::TexBounds2, 4, GL_FLOAT, false, sizeof(ModelVertex), 34 * sizeof(float) },
{ AttribSpec::TexBounds3, 4, GL_FLOAT, false, sizeof(ModelVertex), 38 * sizeof(float) },
};
LIBGUI_VERTEX_FORMAT_SPEC(ModelVertex, 42 * sizeof(float))
static Matrix4f convertMatrix(aiMatrix4x4 const &aiMat)
{
return Matrix4f(&aiMat.a1).transpose();
}
static ddouble secondsToTicks(ddouble seconds, aiAnimation const &anim)
{
ddouble const ticksPerSec = anim.mTicksPerSecond? anim.mTicksPerSecond : 25.0;
return seconds * ticksPerSec;
}
static ddouble ticksToSeconds(ddouble ticks, aiAnimation const &anim)
{
return ticks / secondsToTicks(1.0, anim);
}
/// Bone used for vertices that have no bones.
static String const DUMMY_BONE_NAME = "__deng_dummy-bone__";
DENG2_PIMPL(ModelDrawable)
{
typedef GLBufferT<ModelVertex> VBuf;
typedef QHash<String, int> AnimLookup;
static TextureMap textureMapType(aiTextureType type)
{
switch (type)
{
case aiTextureType_DIFFUSE: return Diffuse;
case aiTextureType_NORMALS: return Normals;
case aiTextureType_HEIGHT: return Height;
case aiTextureType_SPECULAR: return Specular;
case aiTextureType_EMISSIVE: return Emissive;
default:
DENG2_ASSERT(!"Unsupported texture type");
return Diffuse;
}
}
static aiTextureType impTextureType(TextureMap map)
{
switch (map)
{
case Diffuse: return aiTextureType_DIFFUSE;
case Normals: return aiTextureType_NORMALS;
case Height: return aiTextureType_HEIGHT;
case Specular: return aiTextureType_SPECULAR;
case Emissive: return aiTextureType_EMISSIVE;
default:
break;
}
return aiTextureType_UNKNOWN;
}
struct VertexBone
{
duint16 ids[MAX_BONES_PER_VERTEX];
dfloat weights[MAX_BONES_PER_VERTEX];
VertexBone()
{
zap(ids);
zap(weights);
}
};
struct BoneData
{
Matrix4f offset;
};
Asset modelAsset;
String sourcePath;
ImpIOSystem *importerIoSystem; // not owned
Assimp::Importer importer;
aiScene const *scene { nullptr };
Vector3f minPoint; ///< Bounds in default pose.
Vector3f maxPoint;
Matrix4f globalInverse;
QVector<VertexBone> vertexBones; // indexed by vertex
QHash<String, duint16> boneNameToIndex;
QHash<String, aiNode const *> nodeNameToPtr;
QVector<BoneData> bones; // indexed by bone index
AnimLookup animNameToIndex;
QVector<Rangeui> meshIndexRanges;
/**
* Management of texture maps.
*/
struct GLData
{
/**
* Each material has its own VBO with a particular, fixed set of texture
* coordinates.
*/
struct Material
{
struct MeshTextures
{
Id::Type texIds[MAX_TEXTURES];
QHash<TextureMap, String> customPaths;
MeshTextures() { zap(texIds); }
};
QVector<MeshTextures> meshTextures; // indexed by mesh index
std::unique_ptr<VBuf> buffer;
};
/**
* Source information for a texture used in one or more of the meshes.
* Depends on the ModelDrawable's IImageLoader.
*/
struct TextureSource : public TextureBank::ImageSource
{
GLData *d;
TextureSource(String const &path, GLData *glData)
: ImageSource(Path(path))
, d(glData) {}
Image load() const
{
return d->imageLoader->loadImage(sourcePath().toString());
}
};
Id::Type defaultTexIds[MAX_TEXTURES]; ///< Used if no other texture is provided.
TextureMap textureOrder[MAX_TEXTURES]; ///< Order of textures for vertex buffer texcoords.
IImageLoader *imageLoader { &defaultImageLoader };
TextureBank textureBank;
QList<Material *> materials; // owned
bool needMakeBuffer { false };
String sourcePath; ///< Location of the model file (imported with Assimp).
aiScene const *scene { nullptr };
GLData()
{
// We use file paths as identifiers.
textureBank.setSeparator('/');
textureOrder[0] = Diffuse;
textureOrder[1] = textureOrder[2] = textureOrder[3] = Unknown;
zap(defaultTexIds);
}
~GLData()
{
qDeleteAll(materials);
}
void initMaterials()
{
deinitMaterials();
addMaterial(); // default is at index zero
}
void deinitMaterials()
{
qDeleteAll(materials);
materials.clear();
}
duint addMaterial()
{
DENG2_ASSERT(scene != nullptr);
// Each material has its own GLBuffer.
needMakeBuffer = true;
Material *material = new Material;
for (duint i = 0; i < scene->mNumMeshes; ++i)
{
material->meshTextures << Material::MeshTextures();
}
materials << material;
return materials.size() - 1;
}
void glInit(String modelSourcePath)
{
sourcePath = modelSourcePath;
// Materials.
initTextures();
}
void glDeinit()
{
releaseTexturesFromAtlas();
//deinitMaterials();
//scene = nullptr;
}
void releaseTexture(Id const &id)
{
if (!id) return; // We don't own this, don't release.
Path texPath = textureBank.sourcePathForAtlasId(id);
DENG2_ASSERT(!texPath.isEmpty());
LOGDEV_GL_VERBOSE("Releasing model texture '%s' path: \"%s\"")
<< id.asText() << texPath;
textureBank.unload(texPath);
}
void releaseTexturesFromAtlas()
{
textureBank.unloadAll(Bank::ImmediatelyInCurrentThread);
for (Material *mat : materials)
{
for (auto &mesh : mat->meshTextures)
{
zap(mesh.texIds);
}
}
textureBank.clear();
}
void fallBackToDefaultTexture(Material::MeshTextures &mesh,
TextureMap map) const
{
if (!mesh.texIds[map])
{
mesh.texIds[map] = defaultTexIds[map];
}
}
/**
* Load all the textures of the model, for all materials. The textures
* are allocated into the atlas provided to the model.
*
* Only a single copy of each texture image is kept in the atlas even
* if the same image is beig used in many meshes.
*/
void initTextures()
{
for (duint matIdx = 0; matIdx < duint(materials.size()); ++matIdx)
{
for (duint i = 0; i < scene->mNumMeshes; ++i)
{
MeshId const mesh(i, matIdx);
auto &textures = materials[matIdx]->meshTextures[i];
// Load all known types of textures, falling back to defaults.
loadTextureImage(mesh, aiTextureType_DIFFUSE);
fallBackToDefaultTexture(textures, Diffuse);
loadTextureImage(mesh, aiTextureType_NORMALS);
if (!textures.texIds[Normals])
{
// Try a height field instead. This will be converted to a normal map.
loadTextureImage(mesh, aiTextureType_HEIGHT);
}
fallBackToDefaultTexture(textures, Normals);
loadTextureImage(mesh, aiTextureType_SPECULAR);
fallBackToDefaultTexture(textures, Specular);
loadTextureImage(mesh, aiTextureType_EMISSIVE);
fallBackToDefaultTexture(textures, Emissive);
}
}
// All textures loaded.
textureBank.atlas()->commit();
}
/**
* Attempts to load a texture image specified in the material. Also checks if
* an overridden custom path is provided, though.
*
* @param mesh Identifies the mesh whose texture is being loaded.
* @param type AssImp texture type.
*/
void loadTextureImage(MeshId const &mesh, aiTextureType type)
{
DENG2_ASSERT(imageLoader != 0);
aiMesh const &sceneMesh = *scene->mMeshes[mesh.index];
aiMaterial const &sceneMaterial = *scene->mMaterials[sceneMesh.mMaterialIndex];
auto const &meshTextures = materials.at(mesh.material)->meshTextures[mesh.index];
TextureMap const map = textureMapType(type);
try
{
// Custom override path?
if (meshTextures.customPaths.contains(map))
{
LOG_GL_VERBOSE("Loading custom path \"%s\"") << meshTextures.customPaths[map];
return setTexture(mesh, map, meshTextures.customPaths[map]);
}
}
catch (Error const &er)
{
LOG_GL_WARNING("Failed to load user-defined %s texture for "
"mesh %i (material %i): %s")
<< textureMapToText(textureMapType(type))
<< mesh.index << mesh.material
<< er.asText();
}
// Load the texture based on the information specified in the model's materials.
aiString texPath;
for (duint s = 0; s < sceneMaterial.GetTextureCount(type); ++s)
{
try
{
if (sceneMaterial.GetTexture(type, s, &texPath) == AI_SUCCESS)
{
setTexture(mesh, map, sourcePath.fileNamePath() / NativePath(texPath.C_Str()));
break;
}
}
catch (Error const &er)
{
LOG_GL_WARNING("Failed to load %s texture for mesh %i "
"(material %i) based on info from model file: %s")
<< textureMapToText(textureMapType(type))
<< mesh.index << mesh.material << er.asText();
}
}
}
void setTexture(MeshId const &mesh, TextureMap map, String contentPath)
{
if (!scene) return;
if (map == Unknown) return; // Ignore unmapped textures.
if (mesh.material >= duint(materials.size())) return;
if (mesh.index >= scene->mNumMeshes) return;
DENG2_ASSERT(textureBank.atlas());
Material &material = *materials[mesh.material];
auto &meshTextures = material.meshTextures[mesh.index];
Id::Type &destId = (map == Height? meshTextures.texIds[Normals] :
meshTextures.texIds[map]);
/// @todo Release a previously loaded texture, if it isn't used
/// in any material. -jk
if (map == Height)
{
// Convert the height map into a normal map.
contentPath = contentPath.concatenatePath("HeightMap.toNormals");
}
Path const path(contentPath);
// If this image is unknown, add it now to the bank.
if (!textureBank.has(path))
{
textureBank.add(path, new TextureSource(contentPath, this));
}
LOGDEV_GL_VERBOSE("material: %i mesh: %i file: \"%s\"")
<< mesh.material
<< mesh.index
<< textureMapToText(map)
<< contentPath;
destId = textureBank.texture(path);
// The buffer needs to be updated with the new texture bounds.
needMakeBuffer = true;
}
void setTextureMapping(Mapping mapsToUse)
{
for (int i = 0; i < MAX_TEXTURES; ++i)
{
textureOrder[i] = (i < mapsToUse.size()? mapsToUse.at(i) : Unknown);
// Height is an alias for normals.
if (textureOrder[i] == Height) textureOrder[i] = Normals;
}
needMakeBuffer = true;
}
/**
* Sets a custom texture that will be loaded when the model is glInited.
*
* @param matId Material.
* @param tex Texture map.
* @param path Image file path.
*/
void setCustomTexturePath(MeshId const &mesh, TextureMap map, String const &path)
{
DENG2_ASSERT(!textureBank.atlas()); // in-use textures cannot be replaced on the fly
DENG2_ASSERT(mesh.index < scene->mNumMeshes);
DENG2_ASSERT(mesh.material < duint(materials.size()));
materials[mesh.material]->meshTextures[mesh.index].customPaths.insert(map, path);
}
};
GLData glData;
Passes defaultPasses;
GLProgram *program { nullptr }; ///< Default program (overridden by pass shaders).
mutable GLUniform uBoneMatrices { "uBoneMatrices", GLUniform::Mat4Array, MAX_BONES };
Impl(Public *i) : Base(i)
{
// Use FS2 for file access.
importer.SetIOHandler(importerIoSystem = new ImpIOSystem);
// Get most kinds of log output.
ImpLogger::registerLogger();
}
~Impl()
{
glDeinit();
}
void import(File const &file)
{
LOG_GL_MSG("Loading model from %s") << file.description();
#if defined (DENG_HAVE_CUSTOMIZED_ASSIMP)
{
/*
* MD5: Multiple animation sequences are supported via multiple .md5anim files.
* Autodetect if these exist and make a list of their names.
*/
String anims;
if (file.extension() == ".md5mesh")
{
String const baseName = file.name().fileNameWithoutExtension() + "_";
file.parent()->forContents([&anims, &baseName] (String fileName, File &)
{
if (fileName.startsWith(baseName) &&
fileName.fileNameExtension() == ".md5anim")
{
if (!anims.isEmpty()) anims += ";";
anims += fileName.substr(baseName.size()).fileNameWithoutExtension();
}
return LoopContinue;
});
}
importer.SetPropertyString(AI_CONFIG_IMPORT_MD5_ANIM_SEQUENCE_NAMES, anims.toStdString());
}
#endif
scene = glData.scene = nullptr;
sourcePath = file.path();
importerIoSystem->referencePath = sourcePath.fileNamePath();
// Read the model file and apply suitable postprocessing to clean up the data.
if (!importer.ReadFile(sourcePath.toUtf8(),
aiProcess_CalcTangentSpace |
aiProcess_GenSmoothNormals |
aiProcess_JoinIdenticalVertices |
aiProcess_Triangulate |
aiProcess_GenUVCoords |
aiProcess_FlipUVs |
aiProcess_SortByPType))
{
throw LoadError("ModelDrawable::import", String("Failed to load model from %1: %2")
.arg(file.description()).arg(importer.GetErrorString()));
}
scene = glData.scene = importer.GetScene();
initBones();
globalInverse = convertMatrix(scene->mRootNode->mTransformation).inverse();
maxPoint = Vector3f(1.0e-9f, 1.0e-9f, 1.0e-9f);
minPoint = Vector3f(1.0e9f, 1.0e9f, 1.0e9f);
// Determine the total bounding box.
for (duint i = 0; i < scene->mNumMeshes; ++i)
{
aiMesh const &mesh = *scene->mMeshes[i];
for (duint i = 0; i < mesh.mNumVertices; ++i)
{
addToBounds(Vector3f(&mesh.mVertices[i].x));
}
}
// Print some information.
LOG_GL_VERBOSE("Bone count: %i\n"
"Animation count: %i")
<< boneCount()
<< scene->mNumAnimations;
// Animations.
animNameToIndex.clear();
for (duint i = 0; i < scene->mNumAnimations; ++i)
{
LOG_GL_VERBOSE("Animation #%i name:%s tps:%f")
<< i << scene->mAnimations[i]->mName.C_Str()
<< scene->mAnimations[i]->mTicksPerSecond;
String const name = scene->mAnimations[i]->mName.C_Str();
if (!name.isEmpty())
{
animNameToIndex.insert(name, i);
}
}
// Create a lookup for node names.
nodeNameToPtr.clear();
nodeNameToPtr.insert("", scene->mRootNode);
buildNodeLookup(*scene->mRootNode);
glData.initMaterials();
// Default rendering passes to use if none specified.
Pass pass;
pass.meshes.resize(scene->mNumMeshes);
pass.meshes.fill(true);
defaultPasses << pass;
}
void buildNodeLookup(aiNode const &node)
{
String const name = node.mName.C_Str();
#ifdef DENG2_DEBUG
qDebug() << "Node:" << name;
#endif
if (!name.isEmpty())
{
nodeNameToPtr.insert(name, &node);
}
for (duint i = 0; i < node.mNumChildren; ++i)
{
buildNodeLookup(*node.mChildren[i]);
}
}
/// Release all loaded model data.
void clear()
{
glDeinit();
sourcePath.clear();
defaultPasses.clear();
importer.FreeScene();
scene = glData.scene = nullptr;
}
void glInit()
{
DENG2_ASSERT_IN_MAIN_THREAD();
// Has a scene been imported successfully?
if (!scene) return;
if (modelAsset.isReady())
{
// Already good to go.
return;
}
// Last minute notification in case some additional setup is needed.
DENG2_FOR_PUBLIC_AUDIENCE2(AboutToGLInit, i)
{
i->modelAboutToGLInit(self());
}
glData.glInit(sourcePath);
// Initialize all meshes in the scene into a single GL buffer.
makeBuffer();
// Ready to go!
modelAsset.setState(Ready);
}
void glDeinit()
{
glData.glDeinit();
clearBones();
modelAsset.setState(NotReady);
}
void addToBounds(Vector3f const &point)
{
minPoint = minPoint.min(point);
maxPoint = maxPoint.max(point);
}
int findMaterial(String const &name) const
{
if (!scene) return -1;
for (duint i = 0; i < scene->mNumMaterials; ++i)
{
aiMaterial const &material = *scene->mMaterials[i];
aiString matName;
if (material.Get(AI_MATKEY_NAME, matName) == AI_SUCCESS)
{
if (name == matName.C_Str()) return i;
}
}
return -1;
}
//- Bone & Mesh Setup -------------------------------------------------------------------
void clearBones()
{
vertexBones.clear();
bones.clear();
boneNameToIndex.clear();
}
int boneCount() const
{
return bones.size();
}
int addBone(String const &name)
{
int idx = boneCount();
bones << BoneData();
boneNameToIndex[name] = idx;
return idx;
}
int findBone(String const &name) const
{
if (boneNameToIndex.contains(name))
{
return boneNameToIndex[name];
}
return -1;
}
int addOrFindBone(String const &name)
{
int i = findBone(name);
if (i >= 0)
{
return i;
}
return addBone(name);
}
void addVertexWeight(duint vertexIndex, duint16 boneIndex, dfloat weight)
{
VertexBone &vb = vertexBones[vertexIndex];
for (int i = 0; i < MAX_BONES_PER_VERTEX; ++i)
{
if (vb.weights[i] == 0.f)
{
// Here's a free one.
vb.ids[i] = boneIndex;
vb.weights[i] = weight;
return;
}
}
LOG_GL_WARNING("\"%s\": too many weights for vertex %i (only 4 supported), bone index: %i")
<< sourcePath << vertexIndex << boneIndex;
DENG2_ASSERT(!"Too many bone weights for a vertex");
}
/**
* Initializes the per-vertex bone weight information, and indexes the bones
* of the mesh in a sequential order.
*
* @param mesh Source mesh.
* @param vertexBase Index of the first vertex of the mesh.
*/
void initMeshBones(aiMesh const &mesh, duint vertexBase)
{
vertexBones.resize(vertexBase + mesh.mNumVertices);
if (mesh.HasBones())
{
// Mark the per-vertex bone weights.
for (duint i = 0; i < mesh.mNumBones; ++i)
{
aiBone const &bone = *mesh.mBones[i];
duint const boneIndex = addOrFindBone(bone.mName.C_Str());
bones[boneIndex].offset = convertMatrix(bone.mOffsetMatrix);
for (duint w = 0; w < bone.mNumWeights; ++w)
{
addVertexWeight(vertexBase + bone.mWeights[w].mVertexId,
boneIndex, bone.mWeights[w].mWeight);
}
}
}
else
{
// No bones; make one dummy bone so we can render it the same way.
duint const boneIndex = addOrFindBone(DUMMY_BONE_NAME);
bones[boneIndex].offset = Matrix4f();
// All vertices fully affected by this bone.
for (duint i = 0; i < mesh.mNumVertices; ++i)
{
addVertexWeight(vertexBase + i, boneIndex, 1.f);
}
}
}
/**
* Initializes all bones in the scene.
*/
void initBones()
{
clearBones();
int base = 0;
for (duint i = 0; i < scene->mNumMeshes; ++i)
{
aiMesh const &mesh = *scene->mMeshes[i];
LOGDEV_GL_VERBOSE("Initializing %i bones for mesh #%i %s")
<< mesh.mNumBones << i << mesh.mName.C_Str();
initMeshBones(mesh, base);
base += mesh.mNumVertices;
}
}
void makeBuffer()
{
glData.needMakeBuffer = false;
for (GLData::Material *material : glData.materials)
{
makeBuffer(*material);
}
}
/**
* Allocates and fills in the GL buffer containing vertex information.
*
* @param material Material whose vertex buffer to create.
*/
void makeBuffer(GLData::Material &material)
{
VBuf::Vertices verts;
VBuf::Indices indx;
aiVector3D const zero(0, 0, 0);
aiColor4D const white(1, 1, 1, 1);
int base = 0;
meshIndexRanges.clear();
meshIndexRanges.resize(scene->mNumMeshes);
// All of the scene's meshes are combined into one GL buffer.
for (duint m = 0; m < scene->mNumMeshes; ++m)
{
aiMesh const &mesh = *scene->mMeshes[m];
// Load vertices into the buffer.
for (duint i = 0; i < mesh.mNumVertices; ++i)
{
aiVector3D const *pos = &mesh.mVertices[i];
aiColor4D const *color = (mesh.HasVertexColors(0)? &mesh.mColors[0][i] : &white);
aiVector3D const *normal = (mesh.HasNormals()? &mesh.mNormals[i] : &zero);
aiVector3D const *texCoord = (mesh.HasTextureCoords(0)? &mesh.mTextureCoords[0][i] : &zero);
aiVector3D const *tangent = (mesh.HasTangentsAndBitangents()? &mesh.mTangents[i] : &zero);
aiVector3D const *bitang = (mesh.HasTangentsAndBitangents()? &mesh.mBitangents[i] : &zero);
VBuf::Type v;
v.pos = Vector3f(pos->x, pos->y, pos->z);
v.color = Vector4f(color->r, color->g, color->b, color->a);
v.normal = Vector3f(normal ->x, normal ->y, normal ->z);
v.tangent = Vector3f(tangent->x, tangent->y, tangent->z);
v.bitangent = Vector3f(bitang ->x, bitang ->y, bitang ->z);