update assimp to 5.2.3 Bugfix-Release

This commit is contained in:
AzaezelX 2022-04-26 11:56:24 -05:00
parent 3f796d2a06
commit f297476092
1150 changed files with 165834 additions and 112019 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,96 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
/** @file glTFWriter.h
* Declares a class to write gltf/glb files
*
* glTF Extensions Support:
* KHR_binary_glTF: full
* KHR_materials_common: full
*/
#ifndef GLTFASSETWRITER_H_INC
#define GLTFASSETWRITER_H_INC
#if !defined(ASSIMP_BUILD_NO_GLTF_IMPORTER) && !defined(ASSIMP_BUILD_NO_GLTF1_IMPORTER)
#include "glTFAsset.h"
namespace glTF
{
using rapidjson::MemoryPoolAllocator;
class AssetWriter
{
template<class T>
friend void WriteLazyDict(LazyDict<T>& d, AssetWriter& w);
private:
void WriteBinaryData(IOStream* outfile, size_t sceneLength);
void WriteMetadata();
void WriteExtensionsUsed();
template<class T>
void WriteObjects(LazyDict<T>& d);
public:
Document mDoc;
Asset& mAsset;
MemoryPoolAllocator<>& mAl;
AssetWriter(Asset& asset);
void WriteFile(const char* path);
void WriteGLBFile(const char* path);
};
}
// Include the implementation of the methods
#include "glTFAssetWriter.inl"
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
#endif // GLTFASSETWRITER_H_INC

View file

@ -0,0 +1,716 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
#include <assimp/Base64.hpp>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <rapidjson/prettywriter.h>
#if _MSC_VER
# pragma warning(push)
# pragma warning( disable : 4706)
#endif // _MSC_VER
namespace glTF {
using rapidjson::StringBuffer;
using rapidjson::PrettyWriter;
using rapidjson::Writer;
using rapidjson::StringRef;
using rapidjson::StringRef;
namespace {
template<typename T, size_t N>
inline
Value& MakeValue(Value& val, T(&r)[N], MemoryPoolAllocator<>& al) {
val.SetArray();
val.Reserve(N, al);
for (decltype(N) i = 0; i < N; ++i) {
val.PushBack(r[i], al);
}
return val;
}
template<typename T>
inline
Value& MakeValue(Value& val, const std::vector<T> & r, MemoryPoolAllocator<>& al) {
val.SetArray();
val.Reserve(static_cast<rapidjson::SizeType>(r.size()), al);
for (unsigned int i = 0; i < r.size(); ++i) {
val.PushBack(r[i], al);
}
return val;
}
template<typename C, typename T>
inline Value& MakeValueCast(Value& val, const std::vector<T> & r, MemoryPoolAllocator<>& al) {
val.SetArray();
val.Reserve(static_cast<rapidjson::SizeType>(r.size()), al);
for (unsigned int i = 0; i < r.size(); ++i) {
val.PushBack(static_cast<C>(r[i]), al);
}
return val;
}
template<class T>
inline void AddRefsVector(Value& obj, const char* fieldId, std::vector< Ref<T> >& v, MemoryPoolAllocator<>& al) {
if (v.empty()) return;
Value lst;
lst.SetArray();
lst.Reserve(unsigned(v.size()), al);
for (size_t i = 0; i < v.size(); ++i) {
lst.PushBack(StringRef(v[i]->id), al);
}
obj.AddMember(StringRef(fieldId), lst, al);
}
}
inline void Write(Value& obj, Accessor& a, AssetWriter& w)
{
obj.AddMember("bufferView", Value(a.bufferView->id, w.mAl).Move(), w.mAl);
obj.AddMember("byteOffset", a.byteOffset, w.mAl);
obj.AddMember("byteStride", a.byteStride, w.mAl);
obj.AddMember("componentType", int(a.componentType), w.mAl);
obj.AddMember("count", a.count, w.mAl);
obj.AddMember("type", StringRef(AttribType::ToString(a.type)), w.mAl);
Value vTmpMax, vTmpMin;
if (a.componentType == ComponentType_FLOAT) {
obj.AddMember("max", MakeValue(vTmpMax, a.max, w.mAl), w.mAl);
obj.AddMember("min", MakeValue(vTmpMin, a.min, w.mAl), w.mAl);
} else {
obj.AddMember("max", MakeValueCast<int64_t>(vTmpMax, a.max, w.mAl), w.mAl);
obj.AddMember("min", MakeValueCast<int64_t>(vTmpMin, a.min, w.mAl), w.mAl);
}
}
inline void Write(Value& obj, Animation& a, AssetWriter& w)
{
/****************** Channels *******************/
Value channels;
channels.SetArray();
channels.Reserve(unsigned(a.Channels.size()), w.mAl);
for (size_t i = 0; i < unsigned(a.Channels.size()); ++i) {
Animation::AnimChannel& c = a.Channels[i];
Value valChannel;
valChannel.SetObject();
{
valChannel.AddMember("sampler", c.sampler, w.mAl);
Value valTarget;
valTarget.SetObject();
{
valTarget.AddMember("id", StringRef(c.target.id->id), w.mAl);
valTarget.AddMember("path", c.target.path, w.mAl);
}
valChannel.AddMember("target", valTarget, w.mAl);
}
channels.PushBack(valChannel, w.mAl);
}
obj.AddMember("channels", channels, w.mAl);
/****************** Parameters *******************/
Value valParameters;
valParameters.SetObject();
{
if (a.Parameters.TIME) {
valParameters.AddMember("TIME", StringRef(a.Parameters.TIME->id), w.mAl);
}
if (a.Parameters.rotation) {
valParameters.AddMember("rotation", StringRef(a.Parameters.rotation->id), w.mAl);
}
if (a.Parameters.scale) {
valParameters.AddMember("scale", StringRef(a.Parameters.scale->id), w.mAl);
}
if (a.Parameters.translation) {
valParameters.AddMember("translation", StringRef(a.Parameters.translation->id), w.mAl);
}
}
obj.AddMember("parameters", valParameters, w.mAl);
/****************** Samplers *******************/
Value valSamplers;
valSamplers.SetObject();
for (size_t i = 0; i < unsigned(a.Samplers.size()); ++i) {
Animation::AnimSampler& s = a.Samplers[i];
Value valSampler;
valSampler.SetObject();
{
valSampler.AddMember("input", s.input, w.mAl);
valSampler.AddMember("interpolation", s.interpolation, w.mAl);
valSampler.AddMember("output", s.output, w.mAl);
}
valSamplers.AddMember(StringRef(s.id), valSampler, w.mAl);
}
obj.AddMember("samplers", valSamplers, w.mAl);
}
inline void Write(Value& obj, Buffer& b, AssetWriter& w)
{
const char* type;
switch (b.type) {
case Buffer::Type_text:
type = "text"; break;
default:
type = "arraybuffer";
}
obj.AddMember("byteLength", static_cast<uint64_t>(b.byteLength), w.mAl);
obj.AddMember("type", StringRef(type), w.mAl);
obj.AddMember("uri", Value(b.GetURI(), w.mAl).Move(), w.mAl);
}
inline void Write(Value& obj, BufferView& bv, AssetWriter& w)
{
obj.AddMember("buffer", Value(bv.buffer->id, w.mAl).Move(), w.mAl);
obj.AddMember("byteOffset", static_cast<uint64_t>(bv.byteOffset), w.mAl);
obj.AddMember("byteLength", static_cast<uint64_t>(bv.byteLength), w.mAl);
if (bv.target != BufferViewTarget_NONE) {
obj.AddMember("target", int(bv.target), w.mAl);
}
}
inline void Write(Value& /*obj*/, Camera& /*c*/, AssetWriter& /*w*/)
{
}
inline void Write(Value& obj, Image& img, AssetWriter& w)
{
std::string uri;
if (w.mAsset.extensionsUsed.KHR_binary_glTF && img.bufferView) {
Value exts, ext;
exts.SetObject();
ext.SetObject();
ext.AddMember("bufferView", StringRef(img.bufferView->id), w.mAl);
if (!img.mimeType.empty())
ext.AddMember("mimeType", StringRef(img.mimeType), w.mAl);
exts.AddMember("KHR_binary_glTF", ext, w.mAl);
obj.AddMember("extensions", exts, w.mAl);
return;
}
else if (img.HasData()) {
uri = "data:" + (img.mimeType.empty() ? "application/octet-stream" : img.mimeType);
uri += ";base64,";
Base64::Encode(img.GetData(), img.GetDataLength(), uri);
}
else {
uri = img.uri;
}
obj.AddMember("uri", Value(uri, w.mAl).Move(), w.mAl);
}
namespace {
inline void WriteColorOrTex(Value& obj, TexProperty& prop, const char* propName, MemoryPoolAllocator<>& al)
{
if (prop.texture)
obj.AddMember(StringRef(propName), Value(prop.texture->id, al).Move(), al);
else {
Value col;
obj.AddMember(StringRef(propName), MakeValue(col, prop.color, al), al);
}
}
}
inline void Write(Value& obj, Material& m, AssetWriter& w)
{
Value v;
v.SetObject();
{
WriteColorOrTex(v, m.ambient, "ambient", w.mAl);
WriteColorOrTex(v, m.diffuse, "diffuse", w.mAl);
WriteColorOrTex(v, m.specular, "specular", w.mAl);
WriteColorOrTex(v, m.emission, "emission", w.mAl);
if (m.transparent)
v.AddMember("transparency", m.transparency, w.mAl);
v.AddMember("shininess", m.shininess, w.mAl);
}
obj.AddMember("values", v, w.mAl);
}
namespace {
inline void WriteAttrs(AssetWriter& w, Value& attrs, Mesh::AccessorList& lst,
const char* semantic, bool forceNumber = false)
{
if (lst.empty()) return;
if (lst.size() == 1 && !forceNumber) {
attrs.AddMember(StringRef(semantic), Value(lst[0]->id, w.mAl).Move(), w.mAl);
}
else {
for (size_t i = 0; i < lst.size(); ++i) {
char buffer[32];
ai_snprintf(buffer, 32, "%s_%d", semantic, int(i));
attrs.AddMember(Value(buffer, w.mAl).Move(), Value(lst[i]->id, w.mAl).Move(), w.mAl);
}
}
}
}
inline void Write(Value& obj, Mesh& m, AssetWriter& w)
{
/********************* Name **********************/
obj.AddMember("name", m.name, w.mAl);
/**************** Mesh extensions ****************/
if(m.Extension.size() > 0)
{
Value json_extensions;
json_extensions.SetObject();
#ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
for(Mesh::SExtension* ptr_ext : m.Extension)
{
switch(ptr_ext->Type)
{
case Mesh::SExtension::EType::Compression_Open3DGC:
{
Value json_comp_data;
Mesh::SCompression_Open3DGC* ptr_ext_comp = (Mesh::SCompression_Open3DGC*)ptr_ext;
// filling object "compressedData"
json_comp_data.SetObject();
json_comp_data.AddMember("buffer", ptr_ext_comp->Buffer, w.mAl);
json_comp_data.AddMember("byteOffset", static_cast<uint64_t>(ptr_ext_comp->Offset), w.mAl);
json_comp_data.AddMember("componentType", 5121, w.mAl);
json_comp_data.AddMember("type", "SCALAR", w.mAl);
json_comp_data.AddMember("count", static_cast<uint64_t>(ptr_ext_comp->Count), w.mAl);
if(ptr_ext_comp->Binary)
json_comp_data.AddMember("mode", "binary", w.mAl);
else
json_comp_data.AddMember("mode", "ascii", w.mAl);
json_comp_data.AddMember("indicesCount", static_cast<uint64_t>(ptr_ext_comp->IndicesCount), w.mAl);
json_comp_data.AddMember("verticesCount", static_cast<uint64_t>(ptr_ext_comp->VerticesCount), w.mAl);
// filling object "Open3DGC-compression"
Value json_o3dgc;
json_o3dgc.SetObject();
json_o3dgc.AddMember("compressedData", json_comp_data, w.mAl);
// add member to object "extensions"
json_extensions.AddMember("Open3DGC-compression", json_o3dgc, w.mAl);
}
break;
default:
throw DeadlyImportError("GLTF: Can not write mesh: unknown mesh extension, only Open3DGC is supported.");
}// switch(ptr_ext->Type)
}// for(Mesh::SExtension* ptr_ext : m.Extension)
#endif
// Add extensions to mesh
obj.AddMember("extensions", json_extensions, w.mAl);
}// if(m.Extension.size() > 0)
/****************** Primitives *******************/
Value primitives;
primitives.SetArray();
primitives.Reserve(unsigned(m.primitives.size()), w.mAl);
for (size_t i = 0; i < m.primitives.size(); ++i) {
Mesh::Primitive& p = m.primitives[i];
Value prim;
prim.SetObject();
{
prim.AddMember("mode", Value(int(p.mode)).Move(), w.mAl);
if (p.material)
prim.AddMember("material", p.material->id, w.mAl);
if (p.indices)
prim.AddMember("indices", Value(p.indices->id, w.mAl).Move(), w.mAl);
Value attrs;
attrs.SetObject();
{
WriteAttrs(w, attrs, p.attributes.position, "POSITION");
WriteAttrs(w, attrs, p.attributes.normal, "NORMAL");
WriteAttrs(w, attrs, p.attributes.texcoord, "TEXCOORD", true);
WriteAttrs(w, attrs, p.attributes.color, "COLOR");
WriteAttrs(w, attrs, p.attributes.joint, "JOINT");
WriteAttrs(w, attrs, p.attributes.jointmatrix, "JOINTMATRIX");
WriteAttrs(w, attrs, p.attributes.weight, "WEIGHT");
}
prim.AddMember("attributes", attrs, w.mAl);
}
primitives.PushBack(prim, w.mAl);
}
obj.AddMember("primitives", primitives, w.mAl);
}
inline void Write(Value& obj, Node& n, AssetWriter& w)
{
if (n.matrix.isPresent) {
Value val;
obj.AddMember("matrix", MakeValue(val, n.matrix.value, w.mAl).Move(), w.mAl);
}
if (n.translation.isPresent) {
Value val;
obj.AddMember("translation", MakeValue(val, n.translation.value, w.mAl).Move(), w.mAl);
}
if (n.scale.isPresent) {
Value val;
obj.AddMember("scale", MakeValue(val, n.scale.value, w.mAl).Move(), w.mAl);
}
if (n.rotation.isPresent) {
Value val;
obj.AddMember("rotation", MakeValue(val, n.rotation.value, w.mAl).Move(), w.mAl);
}
AddRefsVector(obj, "children", n.children, w.mAl);
AddRefsVector(obj, "meshes", n.meshes, w.mAl);
AddRefsVector(obj, "skeletons", n.skeletons, w.mAl);
if (n.skin) {
obj.AddMember("skin", Value(n.skin->id, w.mAl).Move(), w.mAl);
}
if (!n.jointName.empty()) {
obj.AddMember("jointName", n.jointName, w.mAl);
}
}
inline void Write(Value& /*obj*/, Program& /*b*/, AssetWriter& /*w*/)
{
}
inline void Write(Value& obj, Sampler& b, AssetWriter& w)
{
if (b.wrapS) {
obj.AddMember("wrapS", b.wrapS, w.mAl);
}
if (b.wrapT) {
obj.AddMember("wrapT", b.wrapT, w.mAl);
}
if (b.magFilter) {
obj.AddMember("magFilter", b.magFilter, w.mAl);
}
if (b.minFilter) {
obj.AddMember("minFilter", b.minFilter, w.mAl);
}
}
inline void Write(Value& scene, Scene& s, AssetWriter& w)
{
AddRefsVector(scene, "nodes", s.nodes, w.mAl);
}
inline void Write(Value& /*obj*/, Shader& /*b*/, AssetWriter& /*w*/)
{
}
inline void Write(Value& obj, Skin& b, AssetWriter& w)
{
/****************** jointNames *******************/
Value vJointNames;
vJointNames.SetArray();
vJointNames.Reserve(unsigned(b.jointNames.size()), w.mAl);
for (size_t i = 0; i < unsigned(b.jointNames.size()); ++i) {
vJointNames.PushBack(StringRef(b.jointNames[i]->jointName), w.mAl);
}
obj.AddMember("jointNames", vJointNames, w.mAl);
if (b.bindShapeMatrix.isPresent) {
Value val;
obj.AddMember("bindShapeMatrix", MakeValue(val, b.bindShapeMatrix.value, w.mAl).Move(), w.mAl);
}
if (b.inverseBindMatrices) {
obj.AddMember("inverseBindMatrices", Value(b.inverseBindMatrices->id, w.mAl).Move(), w.mAl);
}
}
inline void Write(Value& /*obj*/, Technique& /*b*/, AssetWriter& /*w*/)
{
}
inline void Write(Value& obj, Texture& tex, AssetWriter& w)
{
if (tex.source) {
obj.AddMember("source", Value(tex.source->id, w.mAl).Move(), w.mAl);
}
if (tex.sampler) {
obj.AddMember("sampler", Value(tex.sampler->id, w.mAl).Move(), w.mAl);
}
}
inline void Write(Value& /*obj*/, Light& /*b*/, AssetWriter& /*w*/)
{
}
inline AssetWriter::AssetWriter(Asset& a)
: mDoc()
, mAsset(a)
, mAl(mDoc.GetAllocator())
{
mDoc.SetObject();
WriteMetadata();
WriteExtensionsUsed();
// Dump the contents of the dictionaries
for (size_t i = 0; i < a.mDicts.size(); ++i) {
a.mDicts[i]->WriteObjects(*this);
}
// Add the target scene field
if (mAsset.scene) {
mDoc.AddMember("scene", StringRef(mAsset.scene->id), mAl);
}
}
inline void AssetWriter::WriteFile(const char* path)
{
std::unique_ptr<IOStream> jsonOutFile(mAsset.OpenFile(path, "wt", true));
if (jsonOutFile == 0) {
throw DeadlyExportError("Could not open output file: " + std::string(path));
}
StringBuffer docBuffer;
PrettyWriter<StringBuffer> writer(docBuffer);
if (!mDoc.Accept(writer)) {
throw DeadlyExportError("Failed to write scene data!");
}
if (jsonOutFile->Write(docBuffer.GetString(), docBuffer.GetSize(), 1) != 1) {
throw DeadlyExportError("Failed to write scene data!");
}
// Write buffer data to separate .bin files
for (unsigned int i = 0; i < mAsset.buffers.Size(); ++i) {
Ref<Buffer> b = mAsset.buffers.Get(i);
std::string binPath = b->GetURI();
std::unique_ptr<IOStream> binOutFile(mAsset.OpenFile(binPath, "wb", true));
if (binOutFile == 0) {
throw DeadlyExportError("Could not open output file: " + binPath);
}
if (b->byteLength > 0) {
if (binOutFile->Write(b->GetPointer(), b->byteLength, 1) != 1) {
throw DeadlyExportError("Failed to write binary file: " + binPath);
}
}
}
}
inline void AssetWriter::WriteGLBFile(const char* path)
{
std::unique_ptr<IOStream> outfile(mAsset.OpenFile(path, "wb", true));
if (outfile == 0) {
throw DeadlyExportError("Could not open output file: " + std::string(path));
}
// we will write the header later, skip its size
outfile->Seek(sizeof(GLB_Header), aiOrigin_SET);
StringBuffer docBuffer;
Writer<StringBuffer> writer(docBuffer);
if (!mDoc.Accept(writer)) {
throw DeadlyExportError("Failed to write scene data!");
}
if (outfile->Write(docBuffer.GetString(), docBuffer.GetSize(), 1) != 1) {
throw DeadlyExportError("Failed to write scene data!");
}
WriteBinaryData(outfile.get(), docBuffer.GetSize());
}
inline void AssetWriter::WriteBinaryData(IOStream* outfile, size_t sceneLength)
{
//
// write the body data
//
size_t bodyLength = 0;
if (Ref<Buffer> b = mAsset.GetBodyBuffer()) {
bodyLength = b->byteLength;
if (bodyLength > 0) {
size_t bodyOffset = sizeof(GLB_Header) + sceneLength;
bodyOffset = (bodyOffset + 3) & ~3; // Round up to next multiple of 4
outfile->Seek(bodyOffset, aiOrigin_SET);
if (outfile->Write(b->GetPointer(), b->byteLength, 1) != 1) {
throw DeadlyExportError("Failed to write body data!");
}
}
}
//
// write the header
//
GLB_Header header;
memcpy(header.magic, AI_GLB_MAGIC_NUMBER, sizeof(header.magic));
header.version = 1;
AI_SWAP4(header.version);
header.length = uint32_t(sizeof(header) + sceneLength + bodyLength);
AI_SWAP4(header.length);
header.sceneLength = uint32_t(sceneLength);
AI_SWAP4(header.sceneLength);
header.sceneFormat = SceneFormat_JSON;
AI_SWAP4(header.sceneFormat);
outfile->Seek(0, aiOrigin_SET);
if (outfile->Write(&header, 1, sizeof(header)) != sizeof(header)) {
throw DeadlyExportError("Failed to write the header!");
}
}
inline void AssetWriter::WriteMetadata()
{
Value asset;
asset.SetObject();
asset.AddMember("version", Value(mAsset.asset.version, mAl).Move(), mAl);
asset.AddMember("generator", Value(mAsset.asset.generator, mAl).Move(), mAl);
if (!mAsset.asset.copyright.empty())
asset.AddMember("copyright", Value(mAsset.asset.copyright, mAl).Move(), mAl);
mDoc.AddMember("asset", asset, mAl);
}
inline void AssetWriter::WriteExtensionsUsed()
{
Value exts;
exts.SetArray();
{
if (false)
exts.PushBack(StringRef("KHR_binary_glTF"), mAl);
if (false)
exts.PushBack(StringRef("KHR_materials_common"), mAl);
}
if (!exts.Empty())
mDoc.AddMember("extensionsUsed", exts, mAl);
}
template<class T>
void AssetWriter::WriteObjects(LazyDict<T>& d)
{
if (d.mObjs.empty()) return;
Value* container = &mDoc;
if (d.mExtId) {
Value* exts = FindObject(mDoc, "extensions");
if (!exts) {
mDoc.AddMember("extensions", Value().SetObject().Move(), mDoc.GetAllocator());
exts = FindObject(mDoc, "extensions");
}
if (!(container = FindObject(*exts, d.mExtId))) {
exts->AddMember(StringRef(d.mExtId), Value().SetObject().Move(), mDoc.GetAllocator());
container = FindObject(*exts, d.mExtId);
}
}
Value* dict;
if (!(dict = FindObject(*container, d.mDictId))) {
container->AddMember(StringRef(d.mDictId), Value().SetObject().Move(), mDoc.GetAllocator());
dict = FindObject(*container, d.mDictId);
}
for (size_t i = 0; i < d.mObjs.size(); ++i) {
if (d.mObjs[i]->IsSpecial()) continue;
Value obj;
obj.SetObject();
if (!d.mObjs[i]->name.empty()) {
obj.AddMember("name", StringRef(d.mObjs[i]->name.c_str()), mAl);
}
Write(obj, *d.mObjs[i], *this);
dict->AddMember(StringRef(d.mObjs[i]->id), obj, mAl);
}
}
template<class T>
void WriteLazyDict(LazyDict<T>& d, AssetWriter& w)
{
w.WriteObjects(d);
}
#if _MSC_VER
# pragma warning(pop)
#endif // _WIN32
}

View file

@ -0,0 +1,117 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
#include "AssetLib/glTF/glTFCommon.h"
namespace glTFCommon {
using namespace glTFCommon::Util;
namespace Util {
bool ParseDataURI(const char *const_uri, size_t uriLen, DataURI &out) {
if (nullptr == const_uri) {
return false;
}
if (const_uri[0] != 0x10) { // we already parsed this uri?
if (strncmp(const_uri, "data:", 5) != 0) // not a data uri?
return false;
}
// set defaults
out.mediaType = "text/plain";
out.charset = "US-ASCII";
out.base64 = false;
char *uri = const_cast<char *>(const_uri);
if (uri[0] != 0x10) {
uri[0] = 0x10;
uri[1] = uri[2] = uri[3] = uri[4] = 0;
size_t i = 5, j;
if (uri[i] != ';' && uri[i] != ',') { // has media type?
uri[1] = char(i);
for (;i < uriLen && uri[i] != ';' && uri[i] != ','; ++i) {
// nothing to do!
}
}
while (i < uriLen && uri[i] == ';') {
uri[i++] = '\0';
for (j = i; i < uriLen && uri[i] != ';' && uri[i] != ','; ++i) {
// nothing to do!
}
if (strncmp(uri + j, "charset=", 8) == 0) {
uri[2] = char(j + 8);
} else if (strncmp(uri + j, "base64", 6) == 0) {
uri[3] = char(j);
}
}
if (i < uriLen) {
uri[i++] = '\0';
uri[4] = char(i);
} else {
uri[1] = uri[2] = uri[3] = 0;
uri[4] = 5;
}
}
if (uri[1] != 0) {
out.mediaType = uri + uri[1];
}
if (uri[2] != 0) {
out.charset = uri + uri[2];
}
if (uri[3] != 0) {
out.base64 = true;
}
out.data = uri + uri[4];
out.dataLength = (uri + uriLen) - out.data;
return true;
}
} // namespace Util
} // namespace glTFCommon
#endif

View file

@ -0,0 +1,520 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
#ifndef AI_GLFTCOMMON_H_INC
#define AI_GLFTCOMMON_H_INC
#ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
#include <assimp/Exceptional.h>
#include <algorithm>
#include <list>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <rapidjson/rapidjson.h>
// clang-format off
#ifdef ASSIMP_API
# include <assimp/ByteSwapper.h>
# include <assimp/DefaultIOSystem.h>
# include <memory>
#else
# include <memory>
# define AI_SWAP4(p)
# define ai_assert
#endif
#if _MSC_VER > 1500 || (defined __GNUC___)
# define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
#else
# define gltf_unordered_map map
#endif
#ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
# include <unordered_map>
# if defined(_MSC_VER) && _MSC_VER <= 1600
# define gltf_unordered_map tr1::unordered_map
# else
# define gltf_unordered_map unordered_map
# endif
#endif
// clang-format on
namespace glTFCommon {
using rapidjson::Document;
using rapidjson::Value;
#ifdef ASSIMP_API
using Assimp::IOStream;
using Assimp::IOSystem;
using std::shared_ptr;
#else
using std::shared_ptr;
typedef std::runtime_error DeadlyImportError;
typedef std::runtime_error DeadlyExportError;
enum aiOrigin {
aiOrigin_SET = 0,
aiOrigin_CUR = 1,
aiOrigin_END = 2
};
class IOSystem;
class IOStream {
public:
IOStream(FILE *file) :
f(file) {}
~IOStream() {
fclose(f);
}
size_t Read(void *b, size_t sz, size_t n) { return fread(b, sz, n, f); }
size_t Write(const void *b, size_t sz, size_t n) { return fwrite(b, sz, n, f); }
int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); }
size_t Tell() const { return ftell(f); }
size_t FileSize() {
long p = Tell(), len = (Seek(0, aiOrigin_END), Tell());
return size_t((Seek(p, aiOrigin_SET), len));
}
private:
FILE *f;
};
#endif
// Vec/matrix types, as raw float arrays
typedef float(vec3)[3];
typedef float(vec4)[4];
typedef float(mat4)[16];
inline void CopyValue(const glTFCommon::vec3 &v, aiColor4D &out) {
out.r = v[0];
out.g = v[1];
out.b = v[2];
out.a = 1.0;
}
inline void CopyValue(const glTFCommon::vec4 &v, aiColor4D &out) {
out.r = v[0];
out.g = v[1];
out.b = v[2];
out.a = v[3];
}
inline void CopyValue(const glTFCommon::vec4 &v, aiColor3D &out) {
out.r = v[0];
out.g = v[1];
out.b = v[2];
}
inline void CopyValue(const glTFCommon::vec3 &v, aiColor3D &out) {
out.r = v[0];
out.g = v[1];
out.b = v[2];
}
inline void CopyValue(const glTFCommon::vec3 &v, aiVector3D &out) {
out.x = v[0];
out.y = v[1];
out.z = v[2];
}
inline void CopyValue(const glTFCommon::vec4 &v, aiQuaternion &out) {
out.x = v[0];
out.y = v[1];
out.z = v[2];
out.w = v[3];
}
inline void CopyValue(const glTFCommon::mat4 &v, aiMatrix4x4 &o) {
o.a1 = v[0];
o.b1 = v[1];
o.c1 = v[2];
o.d1 = v[3];
o.a2 = v[4];
o.b2 = v[5];
o.c2 = v[6];
o.d2 = v[7];
o.a3 = v[8];
o.b3 = v[9];
o.c3 = v[10];
o.d3 = v[11];
o.a4 = v[12];
o.b4 = v[13];
o.c4 = v[14];
o.d4 = v[15];
}
#if _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4310)
#endif // _MSC_VER
inline std::string getCurrentAssetDir(const std::string &pFile) {
int pos = std::max(int(pFile.rfind('/')), int(pFile.rfind('\\')));
if (pos == int(std::string::npos)) {
return std::string();
}
return pFile.substr(0, pos + 1);
}
#if _MSC_VER
# pragma warning(pop)
#endif // _MSC_VER
namespace Util {
void EncodeBase64(const uint8_t *in, size_t inLength, std::string &out);
size_t DecodeBase64(const char *in, size_t inLength, uint8_t *&out);
inline size_t DecodeBase64(const char *in, uint8_t *&out) {
return DecodeBase64(in, strlen(in), out);
}
struct DataURI {
const char *mediaType;
const char *charset;
bool base64;
const char *data;
size_t dataLength;
};
//! Check if a uri is a data URI
bool ParseDataURI(const char *const_uri, size_t uriLen, DataURI &out);
} // namespace Util
#define CHECK_EXT(EXT) \
if (exts.find(#EXT) != exts.end()) extensionsUsed.EXT = true;
//! Helper struct to represent values that might not be present
template <class T>
struct Nullable {
T value;
bool isPresent;
Nullable() :
isPresent(false) {}
Nullable(T &val) :
value(val),
isPresent(true) {}
};
//! A reference to one top-level object, which is valid
//! until the Asset instance is destroyed
template <class T>
class Ref {
std::vector<T *> *vector;
unsigned int index;
public:
Ref() :
vector(0),
index(0) {}
Ref(std::vector<T *> &vec, unsigned int idx) :
vector(&vec),
index(idx) {}
inline unsigned int GetIndex() const { return index; }
operator bool() const { return vector != nullptr && index < vector->size(); }
T *operator->() { return (*vector)[index]; }
T &operator*() { return *((*vector)[index]); }
};
//
// JSON Value reading helpers
//
template <class T>
struct ReadHelper {
static bool Read(Value &val, T &out) {
return val.IsInt() ? out = static_cast<T>(val.GetInt()), true : false;
}
};
template <>
struct ReadHelper<bool> {
static bool Read(Value &val, bool &out) {
return val.IsBool() ? out = val.GetBool(), true : false;
}
};
template <>
struct ReadHelper<float> {
static bool Read(Value &val, float &out) {
return val.IsNumber() ? out = static_cast<float>(val.GetDouble()), true : false;
}
};
template <unsigned int N>
struct ReadHelper<float[N]> {
static bool Read(Value &val, float (&out)[N]) {
if (!val.IsArray() || val.Size() != N) return false;
for (unsigned int i = 0; i < N; ++i) {
if (val[i].IsNumber())
out[i] = static_cast<float>(val[i].GetDouble());
}
return true;
}
};
template <>
struct ReadHelper<const char *> {
static bool Read(Value &val, const char *&out) {
return val.IsString() ? (out = val.GetString(), true) : false;
}
};
template <>
struct ReadHelper<std::string> {
static bool Read(Value &val, std::string &out) {
return val.IsString() ? (out = std::string(val.GetString(), val.GetStringLength()), true) : false;
}
};
template <class T>
struct ReadHelper<Nullable<T>> {
static bool Read(Value &val, Nullable<T> &out) {
return out.isPresent = ReadHelper<T>::Read(val, out.value);
}
};
template <>
struct ReadHelper<uint64_t> {
static bool Read(Value &val, uint64_t &out) {
return val.IsUint64() ? out = val.GetUint64(), true : false;
}
};
template <>
struct ReadHelper<int64_t> {
static bool Read(Value &val, int64_t &out) {
return val.IsInt64() ? out = val.GetInt64(), true : false;
}
};
template <class T>
inline static bool ReadValue(Value &val, T &out) {
return ReadHelper<T>::Read(val, out);
}
template <class T>
inline static bool ReadMember(Value &obj, const char *id, T &out) {
if (!obj.IsObject()) {
return false;
}
Value::MemberIterator it = obj.FindMember(id);
if (it != obj.MemberEnd()) {
return ReadHelper<T>::Read(it->value, out);
}
return false;
}
template <class T>
inline static T MemberOrDefault(Value &obj, const char *id, T defaultValue) {
T out;
return ReadMember(obj, id, out) ? out : defaultValue;
}
inline Value *FindMember(Value &val, const char *id) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(id);
return (it != val.MemberEnd()) ? &it->value : nullptr;
}
template <int N>
inline void throwUnexpectedTypeError(const char (&expectedTypeName)[N], const char *memberId, const char *context, const char *extraContext) {
std::string fullContext = context;
if (extraContext && (strlen(extraContext) > 0)) {
fullContext = fullContext + " (" + extraContext + ")";
}
throw DeadlyImportError("Member \"", memberId, "\" was not of type \"", expectedTypeName, "\" when reading ", fullContext);
}
// Look-up functions with type checks. Context and extra context help the user identify the problem if there's an error.
inline Value *FindStringInContext(Value &val, const char *memberId, const char *context, const char *extraContext = nullptr) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(memberId);
if (it == val.MemberEnd()) {
return nullptr;
}
if (!it->value.IsString()) {
throwUnexpectedTypeError("string", memberId, context, extraContext);
}
return &it->value;
}
inline Value *FindNumberInContext(Value &val, const char *memberId, const char *context, const char *extraContext = nullptr) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(memberId);
if (it == val.MemberEnd()) {
return nullptr;
}
if (!it->value.IsNumber()) {
throwUnexpectedTypeError("number", memberId, context, extraContext);
}
return &it->value;
}
inline Value *FindUIntInContext(Value &val, const char *memberId, const char *context, const char *extraContext = nullptr) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(memberId);
if (it == val.MemberEnd()) {
return nullptr;
}
if (!it->value.IsUint()) {
throwUnexpectedTypeError("uint", memberId, context, extraContext);
}
return &it->value;
}
inline Value *FindArrayInContext(Value &val, const char *memberId, const char *context, const char *extraContext = nullptr) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(memberId);
if (it == val.MemberEnd()) {
return nullptr;
}
if (!it->value.IsArray()) {
throwUnexpectedTypeError("array", memberId, context, extraContext);
}
return &it->value;
}
inline Value *FindObjectInContext(Value &val, const char *memberId, const char *context, const char *extraContext = nullptr) {
if (!val.IsObject()) {
return nullptr;
}
Value::MemberIterator it = val.FindMember(memberId);
if (it == val.MemberEnd()) {
return nullptr;
}
if (!it->value.IsObject()) {
throwUnexpectedTypeError("object", memberId, context, extraContext);
}
return &it->value;
}
inline Value *FindExtensionInContext(Value &val, const char *extensionId, const char *context, const char *extraContext = nullptr) {
if (Value *extensionList = FindObjectInContext(val, "extensions", context, extraContext)) {
if (Value *extension = FindObjectInContext(*extensionList, extensionId, context, extraContext)) {
return extension;
}
}
return nullptr;
}
// Overloads when the value is the document.
inline Value *FindString(Document &doc, const char *memberId) {
return FindStringInContext(doc, memberId, "the document");
}
inline Value *FindNumber(Document &doc, const char *memberId) {
return FindNumberInContext(doc, memberId, "the document");
}
inline Value *FindUInt(Document &doc, const char *memberId) {
return FindUIntInContext(doc, memberId, "the document");
}
inline Value *FindArray(Document &val, const char *memberId) {
return FindArrayInContext(val, memberId, "the document");
}
inline Value *FindObject(Document &doc, const char *memberId) {
return FindObjectInContext(doc, memberId, "the document");
}
inline Value *FindExtension(Value &val, const char *extensionId) {
return FindExtensionInContext(val, extensionId, "the document");
}
inline Value *FindString(Value &val, const char *id) {
Value::MemberIterator it = val.FindMember(id);
return (it != val.MemberEnd() && it->value.IsString()) ? &it->value : 0;
}
inline Value *FindObject(Value &val, const char *id) {
Value::MemberIterator it = val.FindMember(id);
return (it != val.MemberEnd() && it->value.IsObject()) ? &it->value : 0;
}
inline Value *FindArray(Value &val, const char *id) {
Value::MemberIterator it = val.FindMember(id);
return (it != val.MemberEnd() && it->value.IsArray()) ? &it->value : 0;
}
inline Value *FindNumber(Value &val, const char *id) {
Value::MemberIterator it = val.FindMember(id);
return (it != val.MemberEnd() && it->value.IsNumber()) ? &it->value : 0;
}
} // namespace glTFCommon
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
#endif // AI_GLFTCOMMON_H_INC

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,118 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
/** @file GltfExporter.h
* Declares the exporter class to write a scene to a gltf/glb file
*/
#pragma once
#ifndef AI_GLTFEXPORTER_H_INC
#define AI_GLTFEXPORTER_H_INC
#if !defined(ASSIMP_BUILD_NO_GLTF_EXPORTER) && !defined(ASSIMP_BUILD_NO_GLTF1_EXPORTER)
#include <assimp/material.h>
#include <assimp/types.h>
#include <map>
#include <memory>
#include <sstream>
#include <vector>
struct aiScene;
struct aiNode;
namespace glTFCommon {
template <class T>
class Ref;
}
namespace glTF {
class Asset;
struct TexProperty;
struct Node;
} // namespace glTF
namespace Assimp {
class IOSystem;
class IOStream;
class ExportProperties;
// ------------------------------------------------------------------------------------------------
/** Helper class to export a given scene to an glTF file. */
// ------------------------------------------------------------------------------------------------
class glTFExporter {
public:
/// Constructor for a specific scene to export
glTFExporter(const char *filename, IOSystem *pIOSystem, const aiScene *pScene,
const ExportProperties *pProperties, bool binary);
private:
const char *mFilename;
IOSystem *mIOSystem;
std::shared_ptr<const aiScene> mScene;
const ExportProperties *mProperties;
std::map<std::string, unsigned int> mTexturesByPath;
std::shared_ptr<glTF::Asset> mAsset;
std::vector<unsigned char> mBodyData;
void WriteBinaryData(IOStream *outfile, std::size_t sceneLength);
void GetTexSampler(const aiMaterial *mat, glTF::TexProperty &prop);
void GetMatColorOrTex(const aiMaterial *mat, glTF::TexProperty &prop, const char *propName, int type, int idx, aiTextureType tt);
void ExportMetadata();
void ExportMaterials();
void ExportMeshes();
unsigned int ExportNodeHierarchy(const aiNode *n);
unsigned int ExportNode(const aiNode *node, glTFCommon::Ref<glTF::Node> & parent);
void ExportScene();
void ExportAnimations();
};
} // namespace Assimp
#endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
#endif // AI_GLTFEXPORTER_H_INC

View file

@ -0,0 +1,725 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
#if !defined(ASSIMP_BUILD_NO_GLTF_IMPORTER) && !defined(ASSIMP_BUILD_NO_GLTF1_IMPORTER)
#include "AssetLib/glTF/glTFImporter.h"
#include "AssetLib/glTF/glTFAsset.h"
#if !defined(ASSIMP_BUILD_NO_EXPORT)
#include "AssetLib/glTF/glTFAssetWriter.h"
#endif
#include "PostProcessing/MakeVerboseFormat.h"
#include <assimp/StringComparison.h>
#include <assimp/StringUtils.h>
#include <assimp/ai_assert.h>
#include <assimp/commonMetaData.h>
#include <assimp/importerdesc.h>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/Importer.hpp>
#include <memory>
using namespace Assimp;
using namespace glTF;
//
// glTFImporter
//
static const aiImporterDesc desc = {
"glTF Importer",
"",
"",
"",
aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
0,
0,
0,
0,
"gltf glb"
};
glTFImporter::glTFImporter() :
BaseImporter(), meshOffsets(), embeddedTexIdxs(), mScene(nullptr) {
// empty
}
glTFImporter::~glTFImporter() {
// empty
}
const aiImporterDesc *glTFImporter::GetInfo() const {
return &desc;
}
bool glTFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /* checkSig */) const {
glTF::Asset asset(pIOHandler);
try {
asset.Load(pFile, GetExtension(pFile) == "glb");
std::string version = asset.asset.version;
return !version.empty() && version[0] == '1';
} catch (...) {
return false;
}
}
inline void SetMaterialColorProperty(std::vector<int> &embeddedTexIdxs, Asset & /*r*/, glTF::TexProperty prop, aiMaterial *mat,
aiTextureType texType, const char *pKey, unsigned int type, unsigned int idx) {
if (prop.texture) {
if (prop.texture->source) {
aiString uri(prop.texture->source->uri);
int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
if (texIdx != -1) { // embedded
// setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
uri.data[0] = '*';
uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
}
mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0);
}
} else {
aiColor4D col;
CopyValue(prop.color, col);
mat->AddProperty(&col, 1, pKey, type, idx);
}
}
void glTFImporter::ImportMaterials(glTF::Asset &r) {
mScene->mNumMaterials = unsigned(r.materials.Size());
mScene->mMaterials = new aiMaterial *[mScene->mNumMaterials];
for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
aiMaterial *aimat = mScene->mMaterials[i] = new aiMaterial();
Material &mat = r.materials[i];
/*if (!mat.name.empty())*/ {
aiString str(mat.id /*mat.name*/);
aimat->AddProperty(&str, AI_MATKEY_NAME);
}
SetMaterialColorProperty(embeddedTexIdxs, r, mat.ambient, aimat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
SetMaterialColorProperty(embeddedTexIdxs, r, mat.diffuse, aimat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
SetMaterialColorProperty(embeddedTexIdxs, r, mat.specular, aimat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
SetMaterialColorProperty(embeddedTexIdxs, r, mat.emission, aimat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
if (mat.transparent && (mat.transparency != 1.0f)) {
aimat->AddProperty(&mat.transparency, 1, AI_MATKEY_OPACITY);
}
if (mat.shininess > 0.f) {
aimat->AddProperty(&mat.shininess, 1, AI_MATKEY_SHININESS);
}
}
if (mScene->mNumMaterials == 0) {
mScene->mNumMaterials = 1;
// Delete the array of length zero created above.
delete[] mScene->mMaterials;
mScene->mMaterials = new aiMaterial *[1];
mScene->mMaterials[0] = new aiMaterial();
}
}
static inline void SetFace(aiFace &face, int a) {
face.mNumIndices = 1;
face.mIndices = new unsigned int[1];
face.mIndices[0] = a;
}
static inline void SetFace(aiFace &face, int a, int b) {
face.mNumIndices = 2;
face.mIndices = new unsigned int[2];
face.mIndices[0] = a;
face.mIndices[1] = b;
}
static inline void SetFace(aiFace &face, int a, int b, int c) {
face.mNumIndices = 3;
face.mIndices = new unsigned int[3];
face.mIndices[0] = a;
face.mIndices[1] = b;
face.mIndices[2] = c;
}
static inline bool CheckValidFacesIndices(aiFace *faces, unsigned nFaces, unsigned nVerts) {
for (unsigned i = 0; i < nFaces; ++i) {
for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
unsigned idx = faces[i].mIndices[j];
if (idx >= nVerts)
return false;
}
}
return true;
}
void glTFImporter::ImportMeshes(glTF::Asset &r) {
std::vector<aiMesh *> meshes;
unsigned int k = 0;
meshOffsets.clear();
for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
Mesh &mesh = r.meshes[m];
// Check if mesh extensions is used
if (mesh.Extension.size() > 0) {
#ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
for (Mesh::SExtension *cur_ext : mesh.Extension) {
if (cur_ext->Type == Mesh::SExtension::EType::Compression_Open3DGC) {
// Limitations for meshes when using Open3DGC-compression.
// It's a current limitation of sp... Specification have not this part still - about mesh compression. Why only one primitive?
// Because glTF is very flexibly. But in fact it ugly flexible. Every primitive can has own set of accessors and accessors can
// point to a-a-a-a-any part of buffer (through bufferview of course) and even to another buffer. We know that "Open3DGC-compression"
// is applicable only to part of buffer. As we can't guaranty continuity of the data for decoder, we will limit quantity of primitives.
// Yes indices, coordinates etc. still can br stored in different buffers, but with current specification it's a exporter problem.
// Also primitive can has only one of "POSITION", "NORMAL" and less then "AI_MAX_NUMBER_OF_TEXTURECOORDS" of "TEXCOORD". All accessor
// of primitive must point to one continuous region of the buffer.
if (mesh.primitives.size() > 2) throw DeadlyImportError("GLTF: When using Open3DGC compression then only one primitive per mesh are allowed.");
Mesh::SCompression_Open3DGC *o3dgc_ext = (Mesh::SCompression_Open3DGC *)cur_ext;
Ref<Buffer> buf = r.buffers.Get(o3dgc_ext->Buffer);
buf->EncodedRegion_SetCurrent(mesh.id);
} else
{
throw DeadlyImportError("GLTF: Can not import mesh: unknown mesh extension (code: \"", ai_to_string(cur_ext->Type),
"\"), only Open3DGC is supported.");
}
}
#endif
} // if(mesh.Extension.size() > 0)
meshOffsets.push_back(k);
k += unsigned(mesh.primitives.size());
for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
Mesh::Primitive &prim = mesh.primitives[p];
aiMesh *aim = new aiMesh();
meshes.push_back(aim);
aim->mName = mesh.id;
if (mesh.primitives.size() > 1) {
ai_uint32 &len = aim->mName.length;
aim->mName.data[len] = '-';
len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
}
switch (prim.mode) {
case PrimitiveMode_POINTS:
aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
break;
case PrimitiveMode_LINES:
case PrimitiveMode_LINE_LOOP:
case PrimitiveMode_LINE_STRIP:
aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
break;
case PrimitiveMode_TRIANGLES:
case PrimitiveMode_TRIANGLE_STRIP:
case PrimitiveMode_TRIANGLE_FAN:
aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
break;
}
Mesh::Primitive::Attributes &attr = prim.attributes;
if (attr.position.size() > 0 && attr.position[0]) {
aim->mNumVertices = attr.position[0]->count;
attr.position[0]->ExtractData(aim->mVertices);
}
if (attr.normal.size() > 0 && attr.normal[0]) attr.normal[0]->ExtractData(aim->mNormals);
for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
aiVector3D *values = aim->mTextureCoords[tc];
for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
values[i].y = 1 - values[i].y; // Flip Y coords
}
}
aiFace *faces = 0;
unsigned int nFaces = 0;
if (prim.indices) {
unsigned int count = prim.indices->count;
Accessor::Indexer data = prim.indices->GetIndexer();
ai_assert(data.IsValid());
switch (prim.mode) {
case PrimitiveMode_POINTS: {
nFaces = count;
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; ++i) {
SetFace(faces[i], data.GetUInt(i));
}
break;
}
case PrimitiveMode_LINES: {
nFaces = count / 2;
if (nFaces * 2 != count) {
ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
count = nFaces * 2;
}
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 2) {
SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
}
break;
}
case PrimitiveMode_LINE_LOOP:
case PrimitiveMode_LINE_STRIP: {
nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
for (unsigned int i = 2; i < count; ++i) {
SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
}
if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
}
break;
}
case PrimitiveMode_TRIANGLES: {
nFaces = count / 3;
if (nFaces * 3 != count) {
ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
count = nFaces * 3;
}
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 3) {
SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
}
break;
}
case PrimitiveMode_TRIANGLE_STRIP: {
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
}
break;
}
case PrimitiveMode_TRIANGLE_FAN:
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
}
break;
}
} else { // no indices provided so directly generate from counts
// use the already determined count as it includes checks
unsigned int count = aim->mNumVertices;
switch (prim.mode) {
case PrimitiveMode_POINTS: {
nFaces = count;
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; ++i) {
SetFace(faces[i], i);
}
break;
}
case PrimitiveMode_LINES: {
nFaces = count / 2;
if (nFaces * 2 != count) {
ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
count = nFaces * 2;
}
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 2) {
SetFace(faces[i / 2], i, i + 1);
}
break;
}
case PrimitiveMode_LINE_LOOP:
case PrimitiveMode_LINE_STRIP: {
nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
faces = new aiFace[nFaces];
SetFace(faces[0], 0, 1);
for (unsigned int i = 2; i < count; ++i) {
SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
}
if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
}
break;
}
case PrimitiveMode_TRIANGLES: {
nFaces = count / 3;
if (nFaces * 3 != count) {
ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
count = nFaces * 3;
}
faces = new aiFace[nFaces];
for (unsigned int i = 0; i < count; i += 3) {
SetFace(faces[i / 3], i, i + 1, i + 2);
}
break;
}
case PrimitiveMode_TRIANGLE_STRIP: {
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], 0, 1, 2);
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], i);
}
break;
}
case PrimitiveMode_TRIANGLE_FAN:
nFaces = count - 2;
faces = new aiFace[nFaces];
SetFace(faces[0], 0, 1, 2);
for (unsigned int i = 3; i < count; ++i) {
SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], i);
}
break;
}
}
if (faces) {
aim->mFaces = faces;
aim->mNumFaces = nFaces;
const bool validRes = CheckValidFacesIndices(faces, nFaces, aim->mNumVertices);
if (!validRes) {
ai_assert(validRes);
ASSIMP_LOG_WARN("Invalid number of faces detected.");
}
}
if (prim.material) {
aim->mMaterialIndex = prim.material.GetIndex();
}
}
}
meshOffsets.push_back(k);
CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
}
void glTFImporter::ImportCameras(glTF::Asset &r) {
if (!r.cameras.Size()) {
return;
}
mScene->mNumCameras = r.cameras.Size();
mScene->mCameras = new aiCamera *[r.cameras.Size()];
for (size_t i = 0; i < r.cameras.Size(); ++i) {
Camera &cam = r.cameras[i];
aiCamera *aicam = mScene->mCameras[i] = new aiCamera();
if (cam.type == Camera::Perspective) {
aicam->mAspect = cam.perspective.aspectRatio;
aicam->mHorizontalFOV = cam.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect);
aicam->mClipPlaneFar = cam.perspective.zfar;
aicam->mClipPlaneNear = cam.perspective.znear;
} else {
aicam->mClipPlaneFar = cam.ortographic.zfar;
aicam->mClipPlaneNear = cam.ortographic.znear;
aicam->mHorizontalFOV = 0.0;
aicam->mAspect = 1.0f;
if (0.f != cam.ortographic.ymag) {
aicam->mAspect = cam.ortographic.xmag / cam.ortographic.ymag;
}
}
}
}
void glTFImporter::ImportLights(glTF::Asset &r) {
if (!r.lights.Size()) return;
mScene->mNumLights = r.lights.Size();
mScene->mLights = new aiLight *[r.lights.Size()];
for (size_t i = 0; i < r.lights.Size(); ++i) {
Light &l = r.lights[i];
aiLight *ail = mScene->mLights[i] = new aiLight();
switch (l.type) {
case Light::Type_directional:
ail->mType = aiLightSource_DIRECTIONAL;
break;
case Light::Type_spot:
ail->mType = aiLightSource_SPOT;
break;
case Light::Type_ambient:
ail->mType = aiLightSource_AMBIENT;
break;
default: // Light::Type_point
ail->mType = aiLightSource_POINT;
break;
}
CopyValue(l.color, ail->mColorAmbient);
CopyValue(l.color, ail->mColorDiffuse);
CopyValue(l.color, ail->mColorSpecular);
ail->mAngleOuterCone = l.falloffAngle;
ail->mAngleInnerCone = l.falloffExponent; // TODO fix this, it does not look right at all
ail->mAttenuationConstant = l.constantAttenuation;
ail->mAttenuationLinear = l.linearAttenuation;
ail->mAttenuationQuadratic = l.quadraticAttenuation;
}
}
aiNode *ImportNode(aiScene *pScene, glTF::Asset &r, std::vector<unsigned int> &meshOffsets, glTF::Ref<glTF::Node> &ptr) {
Node &node = *ptr;
aiNode *ainode = new aiNode(node.id);
if (!node.children.empty()) {
ainode->mNumChildren = unsigned(node.children.size());
ainode->mChildren = new aiNode *[ainode->mNumChildren];
for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
aiNode *child = ImportNode(pScene, r, meshOffsets, node.children[i]);
child->mParent = ainode;
ainode->mChildren[i] = child;
}
}
aiMatrix4x4 &matrix = ainode->mTransformation;
if (node.matrix.isPresent) {
CopyValue(node.matrix.value, matrix);
} else {
if (node.translation.isPresent) {
aiVector3D trans;
CopyValue(node.translation.value, trans);
aiMatrix4x4 t;
aiMatrix4x4::Translation(trans, t);
matrix = t * matrix;
}
if (node.scale.isPresent) {
aiVector3D scal(1.f);
CopyValue(node.scale.value, scal);
aiMatrix4x4 s;
aiMatrix4x4::Scaling(scal, s);
matrix = s * matrix;
}
if (node.rotation.isPresent) {
aiQuaternion rot;
CopyValue(node.rotation.value, rot);
matrix = aiMatrix4x4(rot.GetMatrix()) * matrix;
}
}
if (!node.meshes.empty()) {
int count = 0;
for (size_t i = 0; i < node.meshes.size(); ++i) {
int idx = node.meshes[i].GetIndex();
count += meshOffsets[idx + 1] - meshOffsets[idx];
}
ainode->mNumMeshes = count;
ainode->mMeshes = new unsigned int[count];
int k = 0;
for (size_t i = 0; i < node.meshes.size(); ++i) {
int idx = node.meshes[i].GetIndex();
for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
ainode->mMeshes[k] = j;
}
}
}
if (node.camera) {
pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
}
if (node.light) {
pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
}
return ainode;
}
void glTFImporter::ImportNodes(glTF::Asset &r) {
if (!r.scene) return;
std::vector<Ref<Node>> rootNodes = r.scene->nodes;
// The root nodes
unsigned int numRootNodes = unsigned(rootNodes.size());
if (numRootNodes == 1) { // a single root node: use it
mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
} else if (numRootNodes > 1) { // more than one root node: create a fake root
aiNode *root = new aiNode("ROOT");
root->mChildren = new aiNode *[numRootNodes];
for (unsigned int i = 0; i < numRootNodes; ++i) {
aiNode *node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
node->mParent = root;
root->mChildren[root->mNumChildren++] = node;
}
mScene->mRootNode = root;
}
//if (!mScene->mRootNode) {
// mScene->mRootNode = new aiNode("EMPTY");
//}
}
void glTFImporter::ImportEmbeddedTextures(glTF::Asset &r) {
embeddedTexIdxs.resize(r.images.Size(), -1);
int numEmbeddedTexs = 0;
for (size_t i = 0; i < r.images.Size(); ++i) {
if (r.images[i].HasData())
numEmbeddedTexs += 1;
}
if (numEmbeddedTexs == 0)
return;
mScene->mTextures = new aiTexture *[numEmbeddedTexs];
// Add the embedded textures
for (size_t i = 0; i < r.images.Size(); ++i) {
Image &img = r.images[i];
if (!img.HasData()) continue;
int idx = mScene->mNumTextures++;
embeddedTexIdxs[i] = idx;
aiTexture *tex = mScene->mTextures[idx] = new aiTexture();
size_t length = img.GetDataLength();
void *data = img.StealData();
tex->mFilename = img.name;
tex->mWidth = static_cast<unsigned int>(length);
tex->mHeight = 0;
tex->pcData = reinterpret_cast<aiTexel *>(data);
if (!img.mimeType.empty()) {
const char *ext = strchr(img.mimeType.c_str(), '/') + 1;
if (ext) {
if (strcmp(ext, "jpeg") == 0) ext = "jpg";
size_t len = strlen(ext);
if (len <= 3) {
strcpy(tex->achFormatHint, ext);
}
}
}
}
}
void glTFImporter::ImportCommonMetadata(glTF::Asset &a) {
ai_assert(mScene->mMetaData == nullptr);
const bool hasVersion = !a.asset.version.empty();
const bool hasGenerator = !a.asset.generator.empty();
const bool hasCopyright = !a.asset.copyright.empty();
if (hasVersion || hasGenerator || hasCopyright) {
mScene->mMetaData = new aiMetadata;
if (hasVersion) {
mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT_VERSION, aiString(a.asset.version));
}
if (hasGenerator) {
mScene->mMetaData->Add(AI_METADATA_SOURCE_GENERATOR, aiString(a.asset.generator));
}
if (hasCopyright) {
mScene->mMetaData->Add(AI_METADATA_SOURCE_COPYRIGHT, aiString(a.asset.copyright));
}
}
}
void glTFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
// clean all member arrays
meshOffsets.clear();
embeddedTexIdxs.clear();
this->mScene = pScene;
// read the asset file
glTF::Asset asset(pIOHandler);
asset.Load(pFile, GetExtension(pFile) == "glb");
//
// Copy the data out
//
ImportEmbeddedTextures(asset);
ImportMaterials(asset);
ImportMeshes(asset);
ImportCameras(asset);
ImportLights(asset);
ImportNodes(asset);
ImportCommonMetadata(asset);
if (pScene->mNumMeshes == 0) {
pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
}
}
#endif // ASSIMP_BUILD_NO_GLTF_IMPORTER

View file

@ -0,0 +1,89 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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 THE COPYRIGHT
OWNER OR CONTRIBUTORS 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.
----------------------------------------------------------------------
*/
#pragma once
#ifndef AI_GLTFIMPORTER_H_INC
#define AI_GLTFIMPORTER_H_INC
#include <assimp/BaseImporter.h>
#include <assimp/DefaultIOSystem.h>
struct aiNode;
namespace glTF {
class Asset;
}
namespace Assimp {
/**
* Load the glTF format.
* https://github.com/KhronosGroup/glTF/tree/master/specification
*/
class glTFImporter : public BaseImporter {
public:
glTFImporter();
~glTFImporter() override;
bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const override;
protected:
const aiImporterDesc *GetInfo() const override;
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) override;
private:
void ImportEmbeddedTextures(glTF::Asset &a);
void ImportMaterials(glTF::Asset &a);
void ImportMeshes(glTF::Asset &a);
void ImportCameras(glTF::Asset &a);
void ImportLights(glTF::Asset &a);
void ImportNodes(glTF::Asset &a);
void ImportCommonMetadata(glTF::Asset &a);
private:
std::vector<unsigned int> meshOffsets;
std::vector<int> embeddedTexIdxs;
aiScene *mScene;
};
} // namespace Assimp
#endif // AI_GLTFIMPORTER_H_INC