| 1 |
/* |
| 2 |
* Copyright (C) 2019 The Android Open Source Project |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
* you may not use this file except in compliance with the License. |
| 6 |
* You may obtain a copy of the License at |
| 7 |
* |
| 8 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
* |
| 10 |
* Unless required by applicable law or agreed to in writing, software |
| 11 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
* See the License for the specific language governing permissions and |
| 14 |
* limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
#include <gltfio/Animator.h> |
| 18 |
#include <gltfio/AssetLoader.h> |
| 19 |
#include <gltfio/MaterialProvider.h> |
| 20 |
|
| 21 |
#include "FFilamentAsset.h" |
| 22 |
#include "GltfEnums.h" |
| 23 |
|
| 24 |
#include <filament/Box.h> |
| 25 |
#include <filament/BufferObject.h> |
| 26 |
#include <filament/Camera.h> |
| 27 |
#include <filament/Engine.h> |
| 28 |
#include <filament/IndexBuffer.h> |
| 29 |
#include <filament/LightManager.h> |
| 30 |
#include <filament/Material.h> |
| 31 |
#include <filament/RenderableManager.h> |
| 32 |
#include <filament/Scene.h> |
| 33 |
#include <filament/TextureSampler.h> |
| 34 |
#include <filament/TransformManager.h> |
| 35 |
#include <filament/VertexBuffer.h> |
| 36 |
|
| 37 |
#include <math/mat4.h> |
| 38 |
#include <math/vec3.h> |
| 39 |
#include <math/vec4.h> |
| 40 |
|
| 41 |
#include <utils/EntityManager.h> |
| 42 |
#include <utils/Log.h> |
| 43 |
#include <utils/Panic.h> |
| 44 |
#include <utils/NameComponentManager.h> |
| 45 |
#include <utils/Systrace.h> |
| 46 |
|
| 47 |
#include <tsl/robin_map.h> |
| 48 |
|
| 49 |
#include <vector> |
| 50 |
|
| 51 |
#define CGLTF_IMPLEMENTATION |
| 52 |
#include <cgltf.h> |
| 53 |
|
| 54 |
#include "math.h" |
| 55 |
#include "upcast.h" |
| 56 |
|
| 57 |
using namespace filament; |
| 58 |
using namespace filament::math; |
| 59 |
using namespace utils; |
| 60 |
|
| 61 |
namespace gltfio { |
| 62 |
|
| 63 |
void importSkins(const cgltf_data* gltf, const NodeMap& nodeMap, SkinVector& dstSkins); |
| 64 |
|
| 65 |
static const auto FREE_CALLBACK = [](void* mem, size_t, void*) { free(mem); }; |
| 66 |
|
| 67 |
// Sometimes a glTF bufferview includes unused data at the end (e.g. in skinning.gltf) so we need to |
| 68 |
// compute the correct size of the vertex buffer. Filament automatically infers the size of |
| 69 |
// driver-level vertex buffers from the attribute data (stride, count, offset) and clients are |
| 70 |
// expected to avoid uploading data blobs that exceed this size. Since this information doesn't |
| 71 |
// exist in the glTF we need to compute it manually. This is a bit of a cheat, cgltf_calc_size is |
| 72 |
// private but its implementation file is available in this cpp file. |
| 73 |
uint32_t computeBindingSize(const cgltf_accessor* accessor) { |
| 74 |
cgltf_size element_size = cgltf_calc_size(accessor->type, accessor->component_type); |
| 75 |
return uint32_t(accessor->stride * (accessor->count - 1) + element_size); |
| 76 |
} |
| 77 |
|
| 78 |
uint32_t computeBindingOffset(const cgltf_accessor* accessor) { |
| 79 |
return uint32_t(accessor->offset + accessor->buffer_view->offset); |
| 80 |
} |
| 81 |
|
| 82 |
static const char* getNodeName(const cgltf_node* node, const char* defaultNodeName) { |
| 83 |
if (node->name) return node->name; |
| 84 |
if (node->mesh && node->mesh->name) return node->mesh->name; |
| 85 |
if (node->light && node->light->name) return node->light->name; |
| 86 |
if (node->camera && node->camera->name) return node->camera->name; |
| 87 |
return defaultNodeName; |
| 88 |
} |
| 89 |
|
| 90 |
struct FAssetLoader : public AssetLoader { |
| 91 |
FAssetLoader(const AssetConfiguration& config) : |
| 92 |
mEntityManager(config.entities ? *config.entities : EntityManager::get()), |
| 93 |
mRenderableManager(config.engine->getRenderableManager()), |
| 94 |
mNameManager(config.names), |
| 95 |
mTransformManager(config.engine->getTransformManager()), |
| 96 |
mMaterials(config.materials), |
| 97 |
mEngine(config.engine), |
| 98 |
mDefaultNodeName(config.defaultNodeName) {} |
| 99 |
|
| 100 |
FFilamentAsset* createAssetFromJson(const uint8_t* bytes, uint32_t nbytes); |
| 101 |
FFilamentAsset* createAssetFromBinary(const uint8_t* bytes, uint32_t nbytes); |
| 102 |
FFilamentAsset* createInstancedAsset(const uint8_t* bytes, uint32_t numBytes, |
| 103 |
FilamentInstance** instances, size_t numInstances); |
| 104 |
FilamentInstance* createInstance(FFilamentAsset* primary); |
| 105 |
|
| 106 |
bool createAssets(const uint8_t* bytes, uint32_t numBytes, FilamentAsset** assets, |
| 107 |
size_t numAssets); |
| 108 |
|
| 109 |
~FAssetLoader() { |
| 110 |
delete mMaterials; |
| 111 |
} |
| 112 |
|
| 113 |
void destroyAsset(const FFilamentAsset* asset) { |
| 114 |
delete asset; |
| 115 |
} |
| 116 |
|
| 117 |
size_t getMaterialsCount() const noexcept { |
| 118 |
return mMaterials->getMaterialsCount(); |
| 119 |
} |
| 120 |
|
| 121 |
NameComponentManager* getNames() const noexcept { |
| 122 |
return mNameManager; |
| 123 |
} |
| 124 |
|
| 125 |
const Material* const* getMaterials() const noexcept { |
| 126 |
return mMaterials->getMaterials(); |
| 127 |
} |
| 128 |
|
| 129 |
void createAsset(const cgltf_data* srcAsset, size_t numInstances); |
| 130 |
FFilamentInstance* createInstance(FFilamentAsset* primary, const cgltf_scene* scene); |
| 131 |
void createEntity(const cgltf_node* node, Entity parent, bool enableLight, |
| 132 |
FFilamentInstance* instance); |
| 133 |
void createRenderable(const cgltf_node* node, Entity entity, const char* name); |
| 134 |
bool createPrimitive(const cgltf_primitive* inPrim, Primitive* outPrim, const UvMap& uvmap, |
| 135 |
const char* name); |
| 136 |
void createLight(const cgltf_light* light, Entity entity); |
| 137 |
void createCamera(const cgltf_camera* camera, Entity entity); |
| 138 |
MaterialInstance* createMaterialInstance(const cgltf_material* inputMat, UvMap* uvmap, |
| 139 |
bool vertexColor); |
| 140 |
void addTextureBinding(MaterialInstance* materialInstance, const char* parameterName, |
| 141 |
const cgltf_texture* srcTexture, bool srgb); |
| 142 |
bool primitiveHasVertexColor(const cgltf_primitive* inPrim) const; |
| 143 |
|
| 144 |
static LightManager::Type getLightType(const cgltf_light_type type); |
| 145 |
|
| 146 |
EntityManager& mEntityManager; |
| 147 |
RenderableManager& mRenderableManager; |
| 148 |
NameComponentManager* mNameManager; |
| 149 |
TransformManager& mTransformManager; |
| 150 |
MaterialProvider* mMaterials; |
| 151 |
Engine* mEngine; |
| 152 |
|
| 153 |
// Transient state used only for the asset currently being loaded: |
| 154 |
FFilamentAsset* mResult; |
| 155 |
const char* mDefaultNodeName; |
| 156 |
bool mError = false; |
| 157 |
bool mDiagnosticsEnabled = false; |
| 158 |
}; |
| 159 |
|
| 160 |
FILAMENT_UPCAST(AssetLoader) |
| 161 |
|
| 162 |
FFilamentAsset* FAssetLoader::createAssetFromJson(const uint8_t* bytes, uint32_t nbytes) { |
| 163 |
cgltf_options options { cgltf_file_type_invalid }; |
| 164 |
cgltf_data* sourceAsset; |
| 165 |
cgltf_result result = cgltf_parse(&options, bytes, nbytes, &sourceAsset); |
| 166 |
if (result != cgltf_result_success) { |
| 167 |
slog.e << "Unable to parse JSON file." << io::endl; |
| 168 |
return nullptr; |
| 169 |
} |
| 170 |
createAsset(sourceAsset, 0); |
| 171 |
return mResult; |
| 172 |
} |
| 173 |
|
| 174 |
FFilamentAsset* FAssetLoader::createAssetFromBinary(const uint8_t* bytes, uint32_t nbytes) { |
| 175 |
|
| 176 |
// The cgltf library handles GLB efficiently by pointing all buffer views into the source data. |
| 177 |
// However, we wish our API to be simple and safe, allowing clients to free up their source blob |
| 178 |
// immediately, without worrying about when all the data has finished uploading asynchronously |
| 179 |
// to the GPU. To achieve this we create a copy of the source blob and stash it inside the |
| 180 |
// asset, asking cgltf to parse the copy. This allows us to free it at the correct time (i.e. |
| 181 |
// after all GPU uploads have completed). Although it incurs a copy, the added safety of this |
| 182 |
// API seems worthwhile. |
| 183 |
std::vector<uint8_t> glbdata(bytes, bytes + nbytes); |
| 184 |
|
| 185 |
cgltf_options options { cgltf_file_type_glb }; |
| 186 |
cgltf_data* sourceAsset; |
| 187 |
cgltf_result result = cgltf_parse(&options, glbdata.data(), nbytes, &sourceAsset); |
| 188 |
if (result != cgltf_result_success) { |
| 189 |
slog.e << "Unable to parse glb file." << io::endl; |
| 190 |
return nullptr; |
| 191 |
} |
| 192 |
createAsset(sourceAsset, 0); |
| 193 |
if (mResult) { |
| 194 |
glbdata.swap(mResult->mSourceAsset->glbData); |
| 195 |
} |
| 196 |
return mResult; |
| 197 |
} |
| 198 |
|
| 199 |
FFilamentAsset* FAssetLoader::createInstancedAsset(const uint8_t* bytes, uint32_t numBytes, |
| 200 |
FilamentInstance** instances, size_t numInstances) { |
| 201 |
ASSERT_PRECONDITION(numInstances > 0, "Instance count must be 1 or more."); |
| 202 |
|
| 203 |
// This method can be used to load JSON or GLB. By using a default options struct, we are asking |
| 204 |
// cgltf to examine the magic identifier to determine which type of file is being loaded. |
| 205 |
cgltf_options options {}; |
| 206 |
|
| 207 |
// Clients can free up their source blob immediately, but cgltf has pointers into the data that |
| 208 |
// need to stay valid. Therefore we create a copy of the source blob and stash it inside the |
| 209 |
// asset. |
| 210 |
std::vector<uint8_t> glbdata(bytes, bytes + numBytes); |
| 211 |
|
| 212 |
cgltf_data* sourceAsset; |
| 213 |
cgltf_result result = cgltf_parse(&options, glbdata.data(), numBytes, &sourceAsset); |
| 214 |
if (result != cgltf_result_success) { |
| 215 |
slog.e << "Unable to parse glTF file." << io::endl; |
| 216 |
return nullptr; |
| 217 |
} |
| 218 |
createAsset(sourceAsset, numInstances); |
| 219 |
if (mResult) { |
| 220 |
glbdata.swap(mResult->mSourceAsset->glbData); |
| 221 |
std::copy_n(mResult->mInstances.data(), numInstances, instances); |
| 222 |
} |
| 223 |
return mResult; |
| 224 |
} |
| 225 |
|
| 226 |
FilamentInstance* FAssetLoader::createInstance(FFilamentAsset* primary) { |
| 227 |
if (!primary->mSourceAsset) { |
| 228 |
slog.e << "Source data has been released; asset is frozen." << io::endl; |
| 229 |
return nullptr; |
| 230 |
} |
| 231 |
if (!primary->isInstanced()) { |
| 232 |
slog.e << "Cannot add an instance to a non-instanced asset." << io::endl; |
| 233 |
return nullptr; |
| 234 |
} |
| 235 |
const cgltf_data* srcAsset = primary->mSourceAsset->hierarchy; |
| 236 |
const cgltf_scene* scene = srcAsset->scene ? srcAsset->scene : srcAsset->scenes; |
| 237 |
if (!scene) { |
| 238 |
slog.e << "There is no scene in the asset." << io::endl; |
| 239 |
return nullptr; |
| 240 |
} |
| 241 |
FFilamentInstance* instance = createInstance(primary, scene); |
| 242 |
|
| 243 |
// Import the skin data. This is normally done by ResourceLoader but dynamically created |
| 244 |
// instances are a bit special. |
| 245 |
importSkins(primary->mSourceAsset->hierarchy, instance->nodeMap, instance->skins); |
| 246 |
if (primary->mAnimator) { |
| 247 |
primary->mAnimator->addInstance(instance); |
| 248 |
} |
| 249 |
|
| 250 |
primary->mDependencyGraph.refinalize(); |
| 251 |
return instance; |
| 252 |
} |
| 253 |
|
| 254 |
void FAssetLoader::createAsset(const cgltf_data* srcAsset, size_t numInstances) { |
| 255 |
SYSTRACE_CALL(); |
| 256 |
#if !GLTFIO_DRACO_SUPPORTED |
| 257 |
for (cgltf_size i = 0; i < srcAsset->extensions_required_count; i++) { |
| 258 |
if (!strcmp(srcAsset->extensions_required[i], "KHR_draco_mesh_compression")) { |
| 259 |
slog.e << "KHR_draco_mesh_compression is not supported." << io::endl; |
| 260 |
mResult = nullptr; |
| 261 |
return; |
| 262 |
} |
| 263 |
} |
| 264 |
#endif |
| 265 |
|
| 266 |
mResult = new FFilamentAsset(mEngine, mNameManager, &mEntityManager, srcAsset); |
| 267 |
|
| 268 |
// If there is no default scene specified, then the default is the first one. |
| 269 |
// It is not an error for a glTF file to have zero scenes. |
| 270 |
const cgltf_scene* scene = srcAsset->scene ? srcAsset->scene : srcAsset->scenes; |
| 271 |
if (!scene) { |
| 272 |
return; |
| 273 |
} |
| 274 |
|
| 275 |
// Create a single root node with an identity transform as a convenience to the client. |
| 276 |
mResult->mRoot = mEntityManager.create(); |
| 277 |
mTransformManager.create(mResult->mRoot); |
| 278 |
|
| 279 |
if (numInstances == 0) { |
| 280 |
// For each scene root, recursively create all entities. |
| 281 |
for (cgltf_size i = 0, len = scene->nodes_count; i < len; ++i) { |
| 282 |
cgltf_node** nodes = scene->nodes; |
| 283 |
createEntity(nodes[i], mResult->mRoot, true, nullptr); |
| 284 |
} |
| 285 |
} else { |
| 286 |
// Create a separate entity hierarchy for each instance. Note that MeshCache (vertex |
| 287 |
// buffers and index buffers) and MatInstanceCache (materials and textures) help avoid |
| 288 |
// needless duplication of resources. |
| 289 |
for (size_t index = 0; index < numInstances; ++index) { |
| 290 |
if (createInstance(mResult, scene) == nullptr) { |
| 291 |
mError = true; |
| 292 |
break; |
| 293 |
} |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
// Find every unique resource URI and store a pointer to any of the cgltf-owned cstrings |
| 298 |
// that match the URI. These strings get freed during releaseSourceData(). |
| 299 |
tsl::robin_map<std::string, const char*> resourceUris; |
| 300 |
auto addResourceUri = [&resourceUris](const char* uri) { |
| 301 |
if (uri) { |
| 302 |
resourceUris[uri] = uri; |
| 303 |
} |
| 304 |
}; |
| 305 |
for (cgltf_size i = 0, len = srcAsset->buffers_count; i < len; ++i) { |
| 306 |
addResourceUri(srcAsset->buffers[i].uri); |
| 307 |
} |
| 308 |
for (cgltf_size i = 0, len = srcAsset->images_count; i < len; ++i) { |
| 309 |
addResourceUri(srcAsset->images[i].uri); |
| 310 |
} |
| 311 |
mResult->mResourceUris.reserve(resourceUris.size()); |
| 312 |
for (auto pair : resourceUris) { |
| 313 |
mResult->mResourceUris.push_back(pair.second); |
| 314 |
} |
| 315 |
|
| 316 |
if (mError) { |
| 317 |
destroyAsset(mResult); |
| 318 |
mResult = nullptr; |
| 319 |
mError = false; |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
FFilamentInstance* FAssetLoader::createInstance(FFilamentAsset* primary, const cgltf_scene* scene) { |
| 324 |
auto rootTransform = mTransformManager.getInstance(primary->mRoot); |
| 325 |
Entity instanceRoot = mEntityManager.create(); |
| 326 |
mTransformManager.create(instanceRoot, rootTransform); |
| 327 |
|
| 328 |
// Create an instance object, which is a just a lightweight wrapper around a vector of |
| 329 |
// entities and a lazily created animator. |
| 330 |
FFilamentInstance* instance = new FFilamentInstance; |
| 331 |
instance->root = instanceRoot; |
| 332 |
instance->animator = nullptr; |
| 333 |
instance->owner = primary; |
| 334 |
primary->mInstances.push_back(instance); |
| 335 |
|
| 336 |
// For each scene root, recursively create all entities. |
| 337 |
for (cgltf_size i = 0, len = scene->nodes_count; i < len; ++i) { |
| 338 |
cgltf_node** nodes = scene->nodes; |
| 339 |
createEntity(nodes[i], instanceRoot, false, instance); |
| 340 |
} |
| 341 |
return instance; |
| 342 |
} |
| 343 |
|
| 344 |
void FAssetLoader::createEntity(const cgltf_node* node, Entity parent, bool enableLight, |
| 345 |
FFilamentInstance* instance) { |
| 346 |
Entity entity = mEntityManager.create(); |
| 347 |
|
| 348 |
// Always create a transform component to reflect the original hierarchy. |
| 349 |
mat4f localTransform; |
| 350 |
if (node->has_matrix) { |
| 351 |
memcpy(&localTransform[0][0], &node->matrix[0], 16 * sizeof(float)); |
| 352 |
} else { |
| 353 |
quatf* rotation = (quatf*) &node->rotation[0]; |
| 354 |
float3* scale = (float3*) &node->scale[0]; |
| 355 |
float3* translation = (float3*) &node->translation[0]; |
| 356 |
localTransform = composeMatrix(*translation, *rotation, *scale); |
| 357 |
} |
| 358 |
|
| 359 |
auto parentTransform = mTransformManager.getInstance(parent); |
| 360 |
mTransformManager.create(entity, parentTransform, localTransform); |
| 361 |
|
| 362 |
// Update the asset's entity list and private node mapping. |
| 363 |
mResult->mEntities.push_back(entity); |
| 364 |
if (instance) { |
| 365 |
instance->entities.push_back(entity); |
| 366 |
instance->nodeMap[node] = entity; |
| 367 |
} else { |
| 368 |
mResult->mNodeMap[node] = entity; |
| 369 |
} |
| 370 |
|
| 371 |
const char* name = getNodeName(node, mDefaultNodeName); |
| 372 |
|
| 373 |
if (name) { |
| 374 |
mResult->mNameToEntity[name].push_back(entity); |
| 375 |
if (mNameManager) { |
| 376 |
mNameManager->addComponent(entity); |
| 377 |
mNameManager->setName(mNameManager->getInstance(entity), name); |
| 378 |
} |
| 379 |
} |
| 380 |
|
| 381 |
// If no name is provided in the glTF or AssetConfiguration, use "node" for error messages. |
| 382 |
name = name ? name : "node"; |
| 383 |
|
| 384 |
// If the node has a mesh, then create a renderable component. |
| 385 |
if (node->mesh) { |
| 386 |
createRenderable(node, entity, name); |
| 387 |
} |
| 388 |
|
| 389 |
if (node->light && enableLight) { |
| 390 |
createLight(node->light, entity); |
| 391 |
} |
| 392 |
|
| 393 |
if (node->camera) { |
| 394 |
createCamera(node->camera, entity); |
| 395 |
} |
| 396 |
|
| 397 |
for (cgltf_size i = 0, len = node->children_count; i < len; ++i) { |
| 398 |
createEntity(node->children[i], entity, enableLight, instance); |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
void FAssetLoader::createRenderable(const cgltf_node* node, Entity entity, const char* name) { |
| 403 |
const cgltf_mesh* mesh = node->mesh; |
| 404 |
|
| 405 |
// Compute the transform relative to the root. |
| 406 |
auto thisTransform = mTransformManager.getInstance(entity); |
| 407 |
mat4f worldTransform = mTransformManager.getWorldTransform(thisTransform); |
| 408 |
|
| 409 |
cgltf_size nprims = mesh->primitives_count; |
| 410 |
RenderableManager::Builder builder(nprims); |
| 411 |
|
| 412 |
// If the mesh is already loaded, obtain the list of Filament VertexBuffer / IndexBuffer objects |
| 413 |
// that were already generated (one for each primitive), otherwise allocate a new list of |
| 414 |
// pointers for the primitives. |
| 415 |
auto iter = mResult->mMeshCache.find(mesh); |
| 416 |
if (iter == mResult->mMeshCache.end()) { |
| 417 |
mResult->mMeshCache[mesh].resize(nprims); |
| 418 |
} |
| 419 |
Primitive* outputPrim = mResult->mMeshCache[mesh].data(); |
| 420 |
const cgltf_primitive* inputPrim = &mesh->primitives[0]; |
| 421 |
|
| 422 |
Aabb aabb; |
| 423 |
|
| 424 |
cgltf_size numMorphTargets = 0; |
| 425 |
|
| 426 |
// For each prim, create a Filament VertexBuffer, IndexBuffer, and MaterialInstance. |
| 427 |
for (cgltf_size index = 0; index < nprims; ++index, ++outputPrim, ++inputPrim) { |
| 428 |
RenderableManager::PrimitiveType primType; |
| 429 |
if (!getPrimitiveType(inputPrim->type, &primType)) { |
| 430 |
slog.e << "Unsupported primitive type in " << name << io::endl; |
| 431 |
} |
| 432 |
|
| 433 |
if (inputPrim->targets_count > 0) { |
| 434 |
if (numMorphTargets > 0 && inputPrim->targets_count != numMorphTargets) { |
| 435 |
slog.e << "Sister primitives must all have the same number of morph targets." |
| 436 |
<< io::endl; |
| 437 |
} |
| 438 |
numMorphTargets = inputPrim->targets_count; |
| 439 |
} |
| 440 |
|
| 441 |
// Create a material instance for this primitive or fetch one from the cache. |
| 442 |
UvMap uvmap {}; |
| 443 |
bool hasVertexColor = primitiveHasVertexColor(inputPrim); |
| 444 |
MaterialInstance* mi = createMaterialInstance(inputPrim->material, &uvmap, hasVertexColor); |
| 445 |
if (!mi) { |
| 446 |
mError = true; |
| 447 |
continue; |
| 448 |
} |
| 449 |
|
| 450 |
mResult->mDependencyGraph.addEdge(entity, mi); |
| 451 |
builder.material(index, mi); |
| 452 |
|
| 453 |
// Create a Filament VertexBuffer and IndexBuffer for this prim if we haven't already. |
| 454 |
if (!outputPrim->vertices && !createPrimitive(inputPrim, outputPrim, uvmap, name)) { |
| 455 |
mError = true; |
| 456 |
continue; |
| 457 |
} |
| 458 |
|
| 459 |
// Expand the object-space bounding box. |
| 460 |
aabb.min = min(outputPrim->aabb.min, aabb.min); |
| 461 |
aabb.max = max(outputPrim->aabb.max, aabb.max); |
| 462 |
|
| 463 |
// We are not using the optional offset, minIndex, maxIndex, and count arguments when |
| 464 |
// calling geometry() on the builder. It appears that the glTF spec does not have |
| 465 |
// facilities for these parameters, which is not a huge loss since some of the buffer |
| 466 |
// view and accessor features already have this functionality. |
| 467 |
builder.geometry(index, primType, outputPrim->vertices, outputPrim->indices); |
| 468 |
} |
| 469 |
|
| 470 |
if (numMorphTargets > 0) { |
| 471 |
builder.morphing(true); |
| 472 |
} |
| 473 |
|
| 474 |
const Aabb transformed = aabb.transform(worldTransform); |
| 475 |
|
| 476 |
// Expand the world-space bounding box. |
| 477 |
mResult->mBoundingBox.min = min(mResult->mBoundingBox.min, transformed.min); |
| 478 |
mResult->mBoundingBox.max = max(mResult->mBoundingBox.max, transformed.max); |
| 479 |
|
| 480 |
if (node->skin) { |
| 481 |
builder.skinning(node->skin->joints_count); |
| 482 |
} |
| 483 |
|
| 484 |
// Per the spec, glTF models must have valid mix / max annotations for position attributes. |
| 485 |
// However in practice these can be missing and we should be as robust as other glTF viewers. |
| 486 |
// If desired, clients can enable the "recomputeBoundingBoxes" feature in ResourceLoader. |
| 487 |
Box box = Box().set(aabb.min, aabb.max); |
| 488 |
if (box.isEmpty()) { |
| 489 |
slog.w << "Missing bounding box in " << name << io::endl; |
| 490 |
box = Box().set(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::max()); |
| 491 |
} |
| 492 |
|
| 493 |
builder |
| 494 |
.boundingBox(box) |
| 495 |
.culling(true) |
| 496 |
.castShadows(true) |
| 497 |
.receiveShadows(true) |
| 498 |
.build(*mEngine, entity); |
| 499 |
|
| 500 |
// According to the spec, the mesh may or may not specify default weights, regardless of whether |
| 501 |
// it actually has morph targets. If it has morphing enabled then the default weights are 0. If |
| 502 |
// node weights are provided, they override the ones specified on the mesh. |
| 503 |
if (numMorphTargets > 0) { |
| 504 |
RenderableManager::Instance renderable = mRenderableManager.getInstance(entity); |
| 505 |
float4 weights(0, 0, 0, 0); |
| 506 |
for (cgltf_size i = 0; i < std::min(MAX_MORPH_TARGETS, mesh->weights_count); ++i) { |
| 507 |
weights[i] = mesh->weights[i]; |
| 508 |
} |
| 509 |
for (cgltf_size i = 0; i < std::min(MAX_MORPH_TARGETS, node->weights_count); ++i) { |
| 510 |
weights[i] = node->weights[i]; |
| 511 |
} |
| 512 |
mRenderableManager.setMorphWeights(renderable, weights); |
| 513 |
} |
| 514 |
} |
| 515 |
|
| 516 |
bool FAssetLoader::createPrimitive(const cgltf_primitive* inPrim, Primitive* outPrim, |
| 517 |
const UvMap& uvmap, const char* name) { |
| 518 |
outPrim->uvmap = uvmap; |
| 519 |
|
| 520 |
// Create a little lambda that appends to the asset's vertex buffer slots. |
| 521 |
auto slots = &mResult->mBufferSlots; |
| 522 |
auto addBufferSlot = [slots](BufferSlot entry) { |
| 523 |
slots->push_back(entry); |
| 524 |
}; |
| 525 |
|
| 526 |
// In glTF, each primitive may or may not have an index buffer. |
| 527 |
IndexBuffer* indices = nullptr; |
| 528 |
const cgltf_accessor* accessor = inPrim->indices; |
| 529 |
if (accessor) { |
| 530 |
IndexBuffer::IndexType indexType; |
| 531 |
if (!getIndexType(accessor->component_type, &indexType)) { |
| 532 |
utils::slog.e << "Unrecognized index type in " << name << utils::io::endl; |
| 533 |
return false; |
| 534 |
} |
| 535 |
|
| 536 |
indices = IndexBuffer::Builder() |
| 537 |
.indexCount(accessor->count) |
| 538 |
.bufferType(indexType) |
| 539 |
.build(*mEngine); |
| 540 |
|
| 541 |
BufferSlot slot = { accessor }; |
| 542 |
slot.indexBuffer = indices; |
| 543 |
addBufferSlot(slot); |
| 544 |
} else if (inPrim->attributes_count > 0) { |
| 545 |
// If a primitive does not have an index buffer, generate a trivial one now. |
| 546 |
const uint32_t vertexCount = inPrim->attributes[0].data->count; |
| 547 |
|
| 548 |
indices = IndexBuffer::Builder() |
| 549 |
.indexCount(vertexCount) |
| 550 |
.bufferType(IndexBuffer::IndexType::UINT) |
| 551 |
.build(*mEngine); |
| 552 |
|
| 553 |
const size_t indexDataSize = vertexCount * sizeof(uint32_t); |
| 554 |
uint32_t* indexData = (uint32_t*) malloc(indexDataSize); |
| 555 |
for (size_t i = 0; i < vertexCount; ++i) { |
| 556 |
indexData[i] = i; |
| 557 |
} |
| 558 |
IndexBuffer::BufferDescriptor bd(indexData, indexDataSize, FREE_CALLBACK); |
| 559 |
indices->setBuffer(*mEngine, std::move(bd)); |
| 560 |
} |
| 561 |
mResult->mIndexBuffers.push_back(indices); |
| 562 |
|
| 563 |
VertexBuffer::Builder vbb; |
| 564 |
vbb.enableBufferObjects(); |
| 565 |
|
| 566 |
bool hasUv0 = false, hasUv1 = false, hasVertexColor = false, hasNormals = false; |
| 567 |
uint32_t vertexCount = 0; |
| 568 |
|
| 569 |
const size_t firstSlot = mResult->mBufferSlots.size(); |
| 570 |
int slot = 0; |
| 571 |
|
| 572 |
for (cgltf_size aindex = 0; aindex < inPrim->attributes_count; aindex++) { |
| 573 |
const cgltf_attribute& attribute = inPrim->attributes[aindex]; |
| 574 |
const int index = attribute.index; |
| 575 |
const cgltf_attribute_type atype = attribute.type; |
| 576 |
const cgltf_accessor* accessor = attribute.data; |
| 577 |
|
| 578 |
// The glTF tangent data is ignored here, but honored in ResourceLoader. |
| 579 |
if (atype == cgltf_attribute_type_tangent) { |
| 580 |
continue; |
| 581 |
} |
| 582 |
|
| 583 |
// At a minimum, surface orientation requires normals to be present in the source data. |
| 584 |
// Here we re-purpose the normals slot to point to the quats that get computed later. |
| 585 |
if (atype == cgltf_attribute_type_normal) { |
| 586 |
vbb.attribute(VertexAttribute::TANGENTS, slot, VertexBuffer::AttributeType::SHORT4); |
| 587 |
vbb.normalized(VertexAttribute::TANGENTS); |
| 588 |
hasNormals = true; |
| 589 |
addBufferSlot({&mResult->mGenerateTangents, atype, slot++}); |
| 590 |
continue; |
| 591 |
} |
| 592 |
|
| 593 |
if (atype == cgltf_attribute_type_color) { |
| 594 |
hasVertexColor = true; |
| 595 |
} |
| 596 |
|
| 597 |
// Translate the cgltf attribute enum into a Filament enum. |
| 598 |
VertexAttribute semantic; |
| 599 |
if (!getVertexAttrType(atype, &semantic)) { |
| 600 |
utils::slog.e << "Unrecognized vertex semantic in " << name << utils::io::endl; |
| 601 |
return false; |
| 602 |
} |
| 603 |
if (atype == cgltf_attribute_type_texcoord) { |
| 604 |
if (index >= UvMapSize) { |
| 605 |
utils::slog.e << "Too many texture coordinate sets in " << name << utils::io::endl; |
| 606 |
continue; |
| 607 |
} |
| 608 |
UvSet uvset = uvmap[index]; |
| 609 |
switch (uvset) { |
| 610 |
case UV0: |
| 611 |
semantic = VertexAttribute::UV0; |
| 612 |
hasUv0 = true; |
| 613 |
break; |
| 614 |
case UV1: |
| 615 |
semantic = VertexAttribute::UV1; |
| 616 |
hasUv1 = true; |
| 617 |
break; |
| 618 |
case UNUSED: |
| 619 |
// If we have a free slot, then include this unused UV set in the VertexBuffer. |
| 620 |
// This allows clients to swap the glTF material with a custom material. |
| 621 |
if (!hasUv0 && getNumUvSets(uvmap) == 0) { |
| 622 |
semantic = VertexAttribute::UV0; |
| 623 |
hasUv0 = true; |
| 624 |
break; |
| 625 |
} |
| 626 |
|
| 627 |
// If there are no free slots then drop this unused texture coordinate set. |
| 628 |
// This should not print an error or warning because the glTF spec stipulates an |
| 629 |
// order of degradation for gracefully dropping UV sets. We implement this in |
| 630 |
// constrainMaterial in MaterialProvider. |
| 631 |
continue; |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
vertexCount = accessor->count; |
| 636 |
|
| 637 |
// The positions accessor is required to have min/max properties, use them to expand |
| 638 |
// the bounding box for this primitive. |
| 639 |
if (atype == cgltf_attribute_type_position) { |
| 640 |
const float* minp = &accessor->min[0]; |
| 641 |
const float* maxp = &accessor->max[0]; |
| 642 |
outPrim->aabb.min = min(outPrim->aabb.min, float3(minp[0], minp[1], minp[2])); |
| 643 |
outPrim->aabb.max = max(outPrim->aabb.max, float3(maxp[0], maxp[1], maxp[2])); |
| 644 |
} |
| 645 |
|
| 646 |
VertexBuffer::AttributeType fatype; |
| 647 |
VertexBuffer::AttributeType actualType; |
| 648 |
if (!getElementType(accessor->type, accessor->component_type, &fatype, &actualType)) { |
| 649 |
slog.e << "Unsupported accessor type in " << name << io::endl; |
| 650 |
return false; |
| 651 |
} |
| 652 |
const int stride = (fatype == actualType) ? accessor->stride : 0; |
| 653 |
|
| 654 |
// The cgltf library provides a stride value for all accessors, even though they do not |
| 655 |
// exist in the glTF file. It is computed from the type and the stride of the buffer view. |
| 656 |
// As a convenience, cgltf also replaces zero (default) stride with the actual stride. |
| 657 |
vbb.attribute(semantic, slot, fatype, 0, stride); |
| 658 |
vbb.normalized(semantic, accessor->normalized); |
| 659 |
addBufferSlot({accessor, atype, slot++}); |
| 660 |
} |
| 661 |
|
| 662 |
// If the model is lit but does not have normals, we'll need to generate flat normals. |
| 663 |
if (inPrim->material && !inPrim->material->unlit && !hasNormals) { |
| 664 |
vbb.attribute(VertexAttribute::TANGENTS, slot, VertexBuffer::AttributeType::SHORT4); |
| 665 |
vbb.normalized(VertexAttribute::TANGENTS); |
| 666 |
cgltf_attribute_type atype = cgltf_attribute_type_normal; |
| 667 |
addBufferSlot({&mResult->mGenerateNormals, atype, slot++}); |
| 668 |
} |
| 669 |
|
| 670 |
cgltf_size targetsCount = inPrim->targets_count; |
| 671 |
|
| 672 |
// There is no need to emit a warning if there are more than 4 targets. This is only the base |
| 673 |
// VertexBuffer and more might be created by MorphHelper. |
| 674 |
if (targetsCount > MAX_MORPH_TARGETS) { |
| 675 |
targetsCount = MAX_MORPH_TARGETS; |
| 676 |
} |
| 677 |
|
| 678 |
constexpr int baseTangentsAttr = (int) VertexAttribute::MORPH_TANGENTS_0; |
| 679 |
constexpr int basePositionAttr = (int) VertexAttribute::MORPH_POSITION_0; |
| 680 |
|
| 681 |
for (cgltf_size targetIndex = 0; targetIndex < targetsCount; targetIndex++) { |
| 682 |
const cgltf_morph_target& morphTarget = inPrim->targets[targetIndex]; |
| 683 |
for (cgltf_size aindex = 0; aindex < morphTarget.attributes_count; aindex++) { |
| 684 |
const cgltf_attribute& attribute = morphTarget.attributes[aindex]; |
| 685 |
const cgltf_accessor* accessor = attribute.data; |
| 686 |
const cgltf_attribute_type atype = attribute.type; |
| 687 |
const int morphId = targetIndex + 1; |
| 688 |
|
| 689 |
// The glTF tangent data is ignored here, but honored in ResourceLoader. |
| 690 |
if (atype == cgltf_attribute_type_tangent) { |
| 691 |
continue; |
| 692 |
} |
| 693 |
|
| 694 |
if (atype == cgltf_attribute_type_normal) { |
| 695 |
VertexAttribute attr = (VertexAttribute) (baseTangentsAttr + targetIndex); |
| 696 |
vbb.attribute(attr, slot, VertexBuffer::AttributeType::SHORT4); |
| 697 |
vbb.normalized(attr); |
| 698 |
addBufferSlot({&mResult->mGenerateTangents, atype, slot++, morphId}); |
| 699 |
continue; |
| 700 |
} |
| 701 |
|
| 702 |
if (atype != cgltf_attribute_type_position) { |
| 703 |
utils::slog.e << "Only positions, normals, and tangents can be morphed." |
| 704 |
<< utils::io::endl; |
| 705 |
return false; |
| 706 |
} |
| 707 |
|
| 708 |
const float* minp = &accessor->min[0]; |
| 709 |
const float* maxp = &accessor->max[0]; |
| 710 |
outPrim->aabb.min = min(outPrim->aabb.min, float3(minp[0], minp[1], minp[2])); |
| 711 |
outPrim->aabb.max = max(outPrim->aabb.max, float3(maxp[0], maxp[1], maxp[2])); |
| 712 |
|
| 713 |
VertexBuffer::AttributeType fatype; |
| 714 |
VertexBuffer::AttributeType actualType; |
| 715 |
if (!getElementType(accessor->type, accessor->component_type, &fatype, &actualType)) { |
| 716 |
slog.e << "Unsupported accessor type in " << name << io::endl; |
| 717 |
return false; |
| 718 |
} |
| 719 |
const int stride = (fatype == actualType) ? accessor->stride : 0; |
| 720 |
|
| 721 |
VertexAttribute attr = (VertexAttribute) (basePositionAttr + targetIndex); |
| 722 |
vbb.attribute(attr, slot, fatype, 0, stride); |
| 723 |
vbb.normalized(attr, accessor->normalized); |
| 724 |
addBufferSlot({accessor, atype, slot++, morphId}); |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
if (vertexCount == 0) { |
| 729 |
slog.e << "Empty vertex buffer in " << name << io::endl; |
| 730 |
return false; |
| 731 |
} |
| 732 |
|
| 733 |
vbb.vertexCount(vertexCount); |
| 734 |
|
| 735 |
// If an ubershader is used, then we provide a single dummy buffer for all unfulfilled vertex |
| 736 |
// requirements. The color data should be a sequence of normalized UBYTE4, so dummy UVs are |
| 737 |
// USHORT2 to make the sizes match. |
| 738 |
bool needsDummyData = false; |
| 739 |
if (mMaterials->getSource() == LOAD_UBERSHADERS) { |
| 740 |
if (!hasUv0) { |
| 741 |
needsDummyData = true; |
| 742 |
vbb.attribute(VertexAttribute::UV0, slot, VertexBuffer::AttributeType::USHORT2); |
| 743 |
vbb.normalized(VertexAttribute::UV0); |
| 744 |
} |
| 745 |
if (!hasUv1) { |
| 746 |
needsDummyData = true; |
| 747 |
vbb.attribute(VertexAttribute::UV1, slot, VertexBuffer::AttributeType::USHORT2); |
| 748 |
vbb.normalized(VertexAttribute::UV1); |
| 749 |
} |
| 750 |
if (!hasVertexColor) { |
| 751 |
needsDummyData = true; |
| 752 |
vbb.attribute(VertexAttribute::COLOR, slot, VertexBuffer::AttributeType::UBYTE4); |
| 753 |
vbb.normalized(VertexAttribute::COLOR); |
| 754 |
} |
| 755 |
} else { |
| 756 |
int numUvSets = getNumUvSets(uvmap); |
| 757 |
if (!hasUv0 && numUvSets > 0) { |
| 758 |
needsDummyData = true; |
| 759 |
vbb.attribute(VertexAttribute::UV0, slot, VertexBuffer::AttributeType::USHORT2); |
| 760 |
vbb.normalized(VertexAttribute::UV0); |
| 761 |
slog.w << "Missing UV0 data in " << name << io::endl; |
| 762 |
} |
| 763 |
if (!hasUv1 && numUvSets > 1) { |
| 764 |
needsDummyData = true; |
| 765 |
vbb.attribute(VertexAttribute::UV1, slot, VertexBuffer::AttributeType::USHORT2); |
| 766 |
vbb.normalized(VertexAttribute::UV1); |
| 767 |
slog.w << "Missing UV1 data in " << name << io::endl; |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
vbb.bufferCount(needsDummyData ? slot + 1 : slot); |
| 772 |
|
| 773 |
VertexBuffer* vertices = vbb.build(*mEngine); |
| 774 |
|
| 775 |
outPrim->indices = indices; |
| 776 |
outPrim->vertices = vertices; |
| 777 |
mResult->mPrimitives.push_back({inPrim, vertices}); |
| 778 |
mResult->mVertexBuffers.push_back(vertices); |
| 779 |
|
| 780 |
for (size_t i = firstSlot; i < mResult->mBufferSlots.size(); ++i) { |
| 781 |
mResult->mBufferSlots[i].vertexBuffer = vertices; |
| 782 |
} |
| 783 |
|
| 784 |
if (needsDummyData) { |
| 785 |
uint32_t size = sizeof(ubyte4) * vertexCount; |
| 786 |
BufferObject* bufferObject = BufferObject::Builder().size(size).build(*mEngine); |
| 787 |
mResult->mBufferObjects.push_back(bufferObject); |
| 788 |
uint32_t* dummyData = (uint32_t*) malloc(size); |
| 789 |
memset(dummyData, 0xff, size); |
| 790 |
VertexBuffer::BufferDescriptor bd(dummyData, size, FREE_CALLBACK); |
| 791 |
bufferObject->setBuffer(*mEngine, std::move(bd)); |
| 792 |
vertices->setBufferObjectAt(*mEngine, slot, bufferObject); |
| 793 |
} |
| 794 |
|
| 795 |
return true; |
| 796 |
} |
| 797 |
|
| 798 |
void FAssetLoader::createLight(const cgltf_light* light, Entity entity) { |
| 799 |
LightManager::Type type = getLightType(light->type); |
| 800 |
LightManager::Builder builder(type); |
| 801 |
|
| 802 |
builder.direction({0.0f, 0.0f, -1.0f}); |
| 803 |
builder.color({light->color[0], light->color[1], light->color[2]}); |
| 804 |
|
| 805 |
switch (type) { |
| 806 |
case LightManager::Type::SUN: |
| 807 |
case LightManager::Type::DIRECTIONAL: |
| 808 |
builder.intensity(light->intensity); |
| 809 |
break; |
| 810 |
case LightManager::Type::POINT: |
| 811 |
builder.intensityCandela(light->intensity); |
| 812 |
break; |
| 813 |
case LightManager::Type::FOCUSED_SPOT: |
| 814 |
case LightManager::Type::SPOT: |
| 815 |
// glTF specifies half angles, so does Filament |
| 816 |
builder.spotLightCone( |
| 817 |
light->spot_inner_cone_angle, |
| 818 |
light->spot_outer_cone_angle); |
| 819 |
builder.intensityCandela(light->intensity); |
| 820 |
break; |
| 821 |
} |
| 822 |
|
| 823 |
if (light->range == 0.0f) { |
| 824 |
// Use 10.0f units as a resonable default falloff value. |
| 825 |
builder.falloff(10.0f); |
| 826 |
} else { |
| 827 |
builder.falloff(light->range); |
| 828 |
} |
| 829 |
|
| 830 |
builder.build(*mEngine, entity); |
| 831 |
mResult->mLightEntities.push_back(entity); |
| 832 |
} |
| 833 |
|
| 834 |
void FAssetLoader::createCamera(const cgltf_camera* camera, Entity entity) { |
| 835 |
Camera* filamentCamera = mEngine->createCamera(entity); |
| 836 |
|
| 837 |
if (camera->type == cgltf_camera_type_perspective) { |
| 838 |
auto& projection = camera->data.perspective; |
| 839 |
|
| 840 |
const cgltf_float yfovDegrees = 180.0 / F_PI * projection.yfov; |
| 841 |
|
| 842 |
// Use an "infinite" zfar plane if the provided one is missing (set to 0.0). |
| 843 |
const double far = projection.zfar > 0.0 ? projection.zfar : 100000000; |
| 844 |
|
| 845 |
filamentCamera->setProjection(yfovDegrees, 1.0, |
| 846 |
projection.znear, far, |
| 847 |
filament::Camera::Fov::VERTICAL); |
| 848 |
|
| 849 |
// Use a default aspect ratio of 1.0 if the provided one is missing. |
| 850 |
const double aspect = projection.aspect_ratio > 0.0 ? projection.aspect_ratio : 1.0; |
| 851 |
|
| 852 |
// Use the scaling matrix to set the aspect ratio, so clients can easily change it. |
| 853 |
filamentCamera->setScaling({1.0 / aspect, 1.0 }); |
| 854 |
} else if (camera->type == cgltf_camera_type_orthographic) { |
| 855 |
auto& projection = camera->data.orthographic; |
| 856 |
|
| 857 |
const double left = -projection.xmag * 0.5; |
| 858 |
const double right = projection.xmag * 0.5; |
| 859 |
const double bottom = -projection.ymag * 0.5; |
| 860 |
const double top = projection.ymag * 0.5; |
| 861 |
|
| 862 |
filamentCamera->setProjection(Camera::Projection::ORTHO, |
| 863 |
left, right, bottom, top, projection.znear, projection.zfar); |
| 864 |
} else { |
| 865 |
slog.e << "Invalid GLTF camera type." << io::endl; |
| 866 |
return; |
| 867 |
} |
| 868 |
|
| 869 |
mResult->mCameraEntities.push_back(entity); |
| 870 |
} |
| 871 |
|
| 872 |
MaterialInstance* FAssetLoader::createMaterialInstance(const cgltf_material* inputMat, |
| 873 |
UvMap* uvmap, bool vertexColor) { |
| 874 |
intptr_t key = ((intptr_t) inputMat) ^ (vertexColor ? 1 : 0); |
| 875 |
auto iter = mResult->mMatInstanceCache.find(key); |
| 876 |
if (iter != mResult->mMatInstanceCache.end()) { |
| 877 |
*uvmap = iter->second.uvmap; |
| 878 |
return iter->second.instance; |
| 879 |
} |
| 880 |
|
| 881 |
// The default glTF material. |
| 882 |
static const cgltf_material kDefaultMat = { |
| 883 |
.name = (char*) "Default GLTF material", |
| 884 |
.has_pbr_metallic_roughness = true, |
| 885 |
.has_pbr_specular_glossiness = false, |
| 886 |
.has_clearcoat = false, |
| 887 |
.has_transmission = false, |
| 888 |
.has_ior = false, |
| 889 |
.has_specular = false, |
| 890 |
.has_sheen = false, |
| 891 |
.pbr_metallic_roughness = { |
| 892 |
.base_color_factor = {1.0, 1.0, 1.0, 1.0}, |
| 893 |
.metallic_factor = 1.0, |
| 894 |
.roughness_factor = 1.0, |
| 895 |
}, |
| 896 |
}; |
| 897 |
inputMat = inputMat ? inputMat : &kDefaultMat; |
| 898 |
|
| 899 |
auto mrConfig = inputMat->pbr_metallic_roughness; |
| 900 |
auto sgConfig = inputMat->pbr_specular_glossiness; |
| 901 |
auto ccConfig = inputMat->clearcoat; |
| 902 |
auto trConfig = inputMat->transmission; |
| 903 |
auto shConfig = inputMat->sheen; |
| 904 |
|
| 905 |
bool hasTextureTransforms = |
| 906 |
sgConfig.diffuse_texture.has_transform || |
| 907 |
sgConfig.specular_glossiness_texture.has_transform || |
| 908 |
mrConfig.base_color_texture.has_transform || |
| 909 |
mrConfig.metallic_roughness_texture.has_transform || |
| 910 |
inputMat->normal_texture.has_transform || |
| 911 |
inputMat->occlusion_texture.has_transform || |
| 912 |
inputMat->emissive_texture.has_transform || |
| 913 |
ccConfig.clearcoat_texture.has_transform || |
| 914 |
ccConfig.clearcoat_roughness_texture.has_transform || |
| 915 |
ccConfig.clearcoat_normal_texture.has_transform || |
| 916 |
shConfig.sheen_color_texture.has_transform || |
| 917 |
shConfig.sheen_roughness_texture.has_transform || |
| 918 |
trConfig.transmission_texture.has_transform; |
| 919 |
|
| 920 |
cgltf_texture_view baseColorTexture = mrConfig.base_color_texture; |
| 921 |
cgltf_texture_view metallicRoughnessTexture = mrConfig.metallic_roughness_texture; |
| 922 |
|
| 923 |
MaterialKey matkey { |
| 924 |
.doubleSided = !!inputMat->double_sided, |
| 925 |
.unlit = !!inputMat->unlit, |
| 926 |
.hasVertexColors = vertexColor, |
| 927 |
.hasBaseColorTexture = !!baseColorTexture.texture, |
| 928 |
.hasNormalTexture = !!inputMat->normal_texture.texture, |
| 929 |
.hasOcclusionTexture = !!inputMat->occlusion_texture.texture, |
| 930 |
.hasEmissiveTexture = !!inputMat->emissive_texture.texture, |
| 931 |
.enableDiagnostics = mDiagnosticsEnabled, |
| 932 |
.baseColorUV = (uint8_t) baseColorTexture.texcoord, |
| 933 |
.hasClearCoatTexture = !!ccConfig.clearcoat_texture.texture, |
| 934 |
.clearCoatUV = (uint8_t) ccConfig.clearcoat_texture.texcoord, |
| 935 |
.hasClearCoatRoughnessTexture = !!ccConfig.clearcoat_roughness_texture.texture, |
| 936 |
.clearCoatRoughnessUV = (uint8_t) ccConfig.clearcoat_roughness_texture.texcoord, |
| 937 |
.hasClearCoatNormalTexture = !!ccConfig.clearcoat_normal_texture.texture, |
| 938 |
.clearCoatNormalUV = (uint8_t) ccConfig.clearcoat_normal_texture.texcoord, |
| 939 |
.hasClearCoat = !!inputMat->has_clearcoat, |
| 940 |
.hasTransmission = !!inputMat->has_transmission, |
| 941 |
.hasTextureTransforms = hasTextureTransforms, |
| 942 |
.emissiveUV = (uint8_t) inputMat->emissive_texture.texcoord, |
| 943 |
.aoUV = (uint8_t) inputMat->occlusion_texture.texcoord, |
| 944 |
.normalUV = (uint8_t) inputMat->normal_texture.texcoord, |
| 945 |
.hasTransmissionTexture = !!trConfig.transmission_texture.texture, |
| 946 |
.transmissionUV = (uint8_t) trConfig.transmission_texture.texcoord, |
| 947 |
.hasSheenColorTexture = !!shConfig.sheen_color_texture.texture, |
| 948 |
.sheenColorUV = (uint8_t) shConfig.sheen_color_texture.texcoord, |
| 949 |
.hasSheenRoughnessTexture = !!shConfig.sheen_roughness_texture.texture, |
| 950 |
.sheenRoughnessUV = (uint8_t) shConfig.sheen_roughness_texture.texcoord, |
| 951 |
.hasSheen = !!inputMat->has_sheen, |
| 952 |
}; |
| 953 |
|
| 954 |
if (inputMat->has_pbr_specular_glossiness) { |
| 955 |
matkey.useSpecularGlossiness = true; |
| 956 |
if (sgConfig.diffuse_texture.texture) { |
| 957 |
baseColorTexture = sgConfig.diffuse_texture; |
| 958 |
matkey.hasBaseColorTexture = true; |
| 959 |
matkey.baseColorUV = (uint8_t) baseColorTexture.texcoord; |
| 960 |
} |
| 961 |
if (sgConfig.specular_glossiness_texture.texture) { |
| 962 |
metallicRoughnessTexture = sgConfig.specular_glossiness_texture; |
| 963 |
matkey.hasSpecularGlossinessTexture = true; |
| 964 |
matkey.specularGlossinessUV = (uint8_t) metallicRoughnessTexture.texcoord; |
| 965 |
} |
| 966 |
} else { |
| 967 |
matkey.hasMetallicRoughnessTexture = !!metallicRoughnessTexture.texture; |
| 968 |
matkey.metallicRoughnessUV = (uint8_t) metallicRoughnessTexture.texcoord; |
| 969 |
} |
| 970 |
|
| 971 |
switch (inputMat->alpha_mode) { |
| 972 |
case cgltf_alpha_mode_opaque: |
| 973 |
matkey.alphaMode = AlphaMode::OPAQUE; |
| 974 |
break; |
| 975 |
case cgltf_alpha_mode_mask: |
| 976 |
matkey.alphaMode = AlphaMode::MASK; |
| 977 |
break; |
| 978 |
case cgltf_alpha_mode_blend: |
| 979 |
matkey.alphaMode = AlphaMode::BLEND; |
| 980 |
break; |
| 981 |
} |
| 982 |
|
| 983 |
// This not only creates a material instance, it modifies the material key according to our |
| 984 |
// rendering constraints. For example, Filament only supports 2 sets of texture coordinates. |
| 985 |
MaterialInstance* mi = mMaterials->createMaterialInstance(&matkey, uvmap, inputMat->name); |
| 986 |
if (!mi) { |
| 987 |
slog.e << "No material with the specified requirements exists." << io::endl; |
| 988 |
return nullptr; |
| 989 |
} |
| 990 |
|
| 991 |
mResult->mMaterialInstances.push_back(mi); |
| 992 |
|
| 993 |
// Check the material blending mode, not the cgltf blending mode, because the provider |
| 994 |
// might have selected an alternative blend mode (e.g. to support transmission). |
| 995 |
if (mi->getMaterial()->getBlendingMode() == filament::BlendingMode::MASKED) { |
| 996 |
mi->setMaskThreshold(inputMat->alpha_cutoff); |
| 997 |
} |
| 998 |
|
| 999 |
const float* e = inputMat->emissive_factor; |
| 1000 |
mi->setParameter("emissiveFactor", float3(e[0], e[1], e[2])); |
| 1001 |
|
| 1002 |
const float* c = mrConfig.base_color_factor; |
| 1003 |
mi->setParameter("baseColorFactor", float4(c[0], c[1], c[2], c[3])); |
| 1004 |
mi->setParameter("metallicFactor", mrConfig.metallic_factor); |
| 1005 |
mi->setParameter("roughnessFactor", mrConfig.roughness_factor); |
| 1006 |
|
| 1007 |
if (matkey.useSpecularGlossiness) { |
| 1008 |
const float* df = sgConfig.diffuse_factor; |
| 1009 |
const float* sf = sgConfig.specular_factor; |
| 1010 |
mi->setParameter("baseColorFactor", float4(df[0], df[1], df[2], df[3])); |
| 1011 |
mi->setParameter("specularFactor", float3(sf[0], sf[1], sf[2])); |
| 1012 |
mi->setParameter("glossinessFactor", sgConfig.glossiness_factor); |
| 1013 |
} |
| 1014 |
|
| 1015 |
if (matkey.hasBaseColorTexture) { |
| 1016 |
addTextureBinding(mi, "baseColorMap", baseColorTexture.texture, true); |
| 1017 |
if (matkey.hasTextureTransforms) { |
| 1018 |
const cgltf_texture_transform& uvt = baseColorTexture.transform; |
| 1019 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1020 |
mi->setParameter("baseColorUvMatrix", uvmat); |
| 1021 |
} |
| 1022 |
} |
| 1023 |
|
| 1024 |
if (matkey.hasMetallicRoughnessTexture) { |
| 1025 |
// The "metallicRoughnessMap" is actually a specular-glossiness map when the extension is |
| 1026 |
// enabled. Note that KHR_materials_pbrSpecularGlossiness specifies that diffuseTexture and |
| 1027 |
// specularGlossinessTexture are both sRGB, whereas the core glTF spec stipulates that |
| 1028 |
// metallicRoughness is not sRGB. |
| 1029 |
bool srgb = inputMat->has_pbr_specular_glossiness; |
| 1030 |
addTextureBinding(mi, "metallicRoughnessMap", metallicRoughnessTexture.texture, srgb); |
| 1031 |
if (matkey.hasTextureTransforms) { |
| 1032 |
const cgltf_texture_transform& uvt = metallicRoughnessTexture.transform; |
| 1033 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1034 |
mi->setParameter("metallicRoughnessUvMatrix", uvmat); |
| 1035 |
} |
| 1036 |
} |
| 1037 |
|
| 1038 |
if (matkey.hasNormalTexture) { |
| 1039 |
addTextureBinding(mi, "normalMap", inputMat->normal_texture.texture, false); |
| 1040 |
if (matkey.hasTextureTransforms) { |
| 1041 |
const cgltf_texture_transform& uvt = inputMat->normal_texture.transform; |
| 1042 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1043 |
mi->setParameter("normalUvMatrix", uvmat); |
| 1044 |
} |
| 1045 |
mi->setParameter("normalScale", inputMat->normal_texture.scale); |
| 1046 |
} else { |
| 1047 |
mi->setParameter("normalScale", 1.0f); |
| 1048 |
} |
| 1049 |
|
| 1050 |
if (matkey.hasOcclusionTexture) { |
| 1051 |
addTextureBinding(mi, "occlusionMap", inputMat->occlusion_texture.texture, false); |
| 1052 |
if (matkey.hasTextureTransforms) { |
| 1053 |
const cgltf_texture_transform& uvt = inputMat->occlusion_texture.transform; |
| 1054 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1055 |
mi->setParameter("occlusionUvMatrix", uvmat); |
| 1056 |
} |
| 1057 |
mi->setParameter("aoStrength", inputMat->occlusion_texture.scale); |
| 1058 |
} else { |
| 1059 |
mi->setParameter("aoStrength", 1.0f); |
| 1060 |
} |
| 1061 |
|
| 1062 |
if (matkey.hasEmissiveTexture) { |
| 1063 |
addTextureBinding(mi, "emissiveMap", inputMat->emissive_texture.texture, true); |
| 1064 |
if (matkey.hasTextureTransforms) { |
| 1065 |
const cgltf_texture_transform& uvt = inputMat->emissive_texture.transform; |
| 1066 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1067 |
mi->setParameter("emissiveUvMatrix", uvmat); |
| 1068 |
} |
| 1069 |
} |
| 1070 |
|
| 1071 |
if (matkey.hasClearCoat) { |
| 1072 |
mi->setParameter("clearCoatFactor", ccConfig.clearcoat_factor); |
| 1073 |
mi->setParameter("clearCoatRoughnessFactor", ccConfig.clearcoat_roughness_factor); |
| 1074 |
|
| 1075 |
if (matkey.hasClearCoatTexture) { |
| 1076 |
addTextureBinding(mi, "clearCoatMap", ccConfig.clearcoat_texture.texture, false); |
| 1077 |
if (matkey.hasTextureTransforms) { |
| 1078 |
const cgltf_texture_transform& uvt = ccConfig.clearcoat_texture.transform; |
| 1079 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1080 |
mi->setParameter("clearCoatUvMatrix", uvmat); |
| 1081 |
} |
| 1082 |
} |
| 1083 |
if (matkey.hasClearCoatRoughnessTexture) { |
| 1084 |
addTextureBinding(mi, "clearCoatRoughnessMap", ccConfig.clearcoat_roughness_texture.texture, false); |
| 1085 |
if (matkey.hasTextureTransforms) { |
| 1086 |
const cgltf_texture_transform& uvt = ccConfig.clearcoat_roughness_texture.transform; |
| 1087 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1088 |
mi->setParameter("clearCoatRoughnessUvMatrix", uvmat); |
| 1089 |
} |
| 1090 |
} |
| 1091 |
if (matkey.hasClearCoatNormalTexture) { |
| 1092 |
addTextureBinding(mi, "clearCoatNormalMap", ccConfig.clearcoat_normal_texture.texture, false); |
| 1093 |
if (matkey.hasTextureTransforms) { |
| 1094 |
const cgltf_texture_transform& uvt = ccConfig.clearcoat_normal_texture.transform; |
| 1095 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1096 |
mi->setParameter("clearCoatNormalUvMatrix", uvmat); |
| 1097 |
} |
| 1098 |
mi->setParameter("clearCoatNormalScale", ccConfig.clearcoat_normal_texture.scale); |
| 1099 |
} |
| 1100 |
} |
| 1101 |
|
| 1102 |
if (matkey.hasSheen) { |
| 1103 |
const float* s = shConfig.sheen_color_factor; |
| 1104 |
mi->setParameter("sheenColorFactor", float3{s[0], s[1], s[2]}); |
| 1105 |
mi->setParameter("sheenRoughnessFactor", shConfig.sheen_roughness_factor); |
| 1106 |
|
| 1107 |
if (matkey.hasSheenColorTexture) { |
| 1108 |
addTextureBinding(mi, "sheenColorMap", shConfig.sheen_color_texture.texture, true); |
| 1109 |
if (matkey.hasTextureTransforms) { |
| 1110 |
const cgltf_texture_transform& uvt = shConfig.sheen_color_texture.transform; |
| 1111 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1112 |
mi->setParameter("sheenColorUvMatrix", uvmat); |
| 1113 |
} |
| 1114 |
} |
| 1115 |
if (matkey.hasSheenRoughnessTexture) { |
| 1116 |
addTextureBinding(mi, "sheenRoughnessMap", shConfig.sheen_roughness_texture.texture, false); |
| 1117 |
if (matkey.hasTextureTransforms) { |
| 1118 |
const cgltf_texture_transform& uvt = shConfig.sheen_roughness_texture.transform; |
| 1119 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1120 |
mi->setParameter("sheenRoughnessUvMatrix", uvmat); |
| 1121 |
} |
| 1122 |
} |
| 1123 |
} |
| 1124 |
|
| 1125 |
if (matkey.hasTransmission) { |
| 1126 |
mi->setParameter("transmissionFactor", trConfig.transmission_factor); |
| 1127 |
if (matkey.hasTransmissionTexture) { |
| 1128 |
addTextureBinding(mi, "transmissionMap", trConfig.transmission_texture.texture, false); |
| 1129 |
if (matkey.hasTextureTransforms) { |
| 1130 |
const cgltf_texture_transform& uvt = trConfig.transmission_texture.transform; |
| 1131 |
auto uvmat = matrixFromUvTransform(uvt.offset, uvt.rotation, uvt.scale); |
| 1132 |
mi->setParameter("transmissionUvMatrix", uvmat); |
| 1133 |
} |
| 1134 |
} |
| 1135 |
} |
| 1136 |
|
| 1137 |
mResult->mMatInstanceCache[key] = {mi, *uvmap}; |
| 1138 |
return mi; |
| 1139 |
} |
| 1140 |
|
| 1141 |
void FAssetLoader::addTextureBinding(MaterialInstance* materialInstance, const char* parameterName, |
| 1142 |
const cgltf_texture* srcTexture, bool srgb) { |
| 1143 |
if (!srcTexture->image) { |
| 1144 |
slog.w << "Texture is missing image (" << srcTexture->name << ")." << io::endl; |
| 1145 |
return; |
| 1146 |
} |
| 1147 |
TextureSampler dstSampler; |
| 1148 |
auto srcSampler = srcTexture->sampler; |
| 1149 |
if (srcSampler) { |
| 1150 |
dstSampler.setWrapModeS(getWrapMode(srcSampler->wrap_s)); |
| 1151 |
dstSampler.setWrapModeT(getWrapMode(srcSampler->wrap_t)); |
| 1152 |
dstSampler.setMagFilter(getMagFilter(srcSampler->mag_filter)); |
| 1153 |
dstSampler.setMinFilter(getMinFilter(srcSampler->min_filter)); |
| 1154 |
} else { |
| 1155 |
// These defaults are stipulated by the spec: |
| 1156 |
dstSampler.setWrapModeS(TextureSampler::WrapMode::REPEAT); |
| 1157 |
dstSampler.setWrapModeT(TextureSampler::WrapMode::REPEAT); |
| 1158 |
|
| 1159 |
// These defaults are up the implementation but since we generate mipmaps unconditionally, |
| 1160 |
// we might as well use them. In practice the conformance models look awful without |
| 1161 |
// using mipmapping by default. |
| 1162 |
dstSampler.setMagFilter(TextureSampler::MagFilter::LINEAR); |
| 1163 |
dstSampler.setMinFilter(TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR); |
| 1164 |
} |
| 1165 |
|
| 1166 |
mResult->mTextureSlots.push_back({ |
| 1167 |
.texture = srcTexture, |
| 1168 |
.materialInstance = materialInstance, |
| 1169 |
.materialParameter = parameterName, |
| 1170 |
.sampler = dstSampler, |
| 1171 |
.srgb = srgb |
| 1172 |
}); |
| 1173 |
mResult->mDependencyGraph.addEdge(materialInstance, parameterName); |
| 1174 |
} |
| 1175 |
|
| 1176 |
bool FAssetLoader::primitiveHasVertexColor(const cgltf_primitive* inPrim) const { |
| 1177 |
for (int slot = 0; slot < inPrim->attributes_count; slot++) { |
| 1178 |
const cgltf_attribute& inputAttribute = inPrim->attributes[slot]; |
| 1179 |
if (inputAttribute.type == cgltf_attribute_type_color) { |
| 1180 |
return true; |
| 1181 |
} |
| 1182 |
} |
| 1183 |
return false; |
| 1184 |
} |
| 1185 |
|
| 1186 |
LightManager::Type FAssetLoader::getLightType(const cgltf_light_type light) { |
| 1187 |
switch (light) { |
| 1188 |
case cgltf_light_type_invalid: |
| 1189 |
case cgltf_light_type_directional: |
| 1190 |
return LightManager::Type::DIRECTIONAL; |
| 1191 |
case cgltf_light_type_point: |
| 1192 |
return LightManager::Type::POINT; |
| 1193 |
case cgltf_light_type_spot: |
| 1194 |
return LightManager::Type::FOCUSED_SPOT; |
| 1195 |
} |
| 1196 |
} |
| 1197 |
|
| 1198 |
AssetLoader* AssetLoader::create(const AssetConfiguration& config) { |
| 1199 |
return new FAssetLoader(config); |
| 1200 |
} |
| 1201 |
|
| 1202 |
void AssetLoader::destroy(AssetLoader** loader) { |
| 1203 |
delete *loader; |
| 1204 |
*loader = nullptr; |
| 1205 |
} |
| 1206 |
|
| 1207 |
FilamentAsset* AssetLoader::createAssetFromJson(uint8_t const* bytes, uint32_t nbytes) { |
| 1208 |
return upcast(this)->createAssetFromJson(bytes, nbytes); |
| 1209 |
} |
| 1210 |
|
| 1211 |
FilamentAsset* AssetLoader::createAssetFromBinary(uint8_t const* bytes, uint32_t nbytes) { |
| 1212 |
return upcast(this)->createAssetFromBinary(bytes, nbytes); |
| 1213 |
} |
| 1214 |
|
| 1215 |
FilamentAsset* AssetLoader::createInstancedAsset(const uint8_t* bytes, uint32_t numBytes, |
| 1216 |
FilamentInstance** instances, size_t numInstances) { |
| 1217 |
return upcast(this)->createInstancedAsset(bytes, numBytes, instances, numInstances); |
| 1218 |
} |
| 1219 |
|
| 1220 |
FilamentInstance* AssetLoader::createInstance(FilamentAsset* asset) { |
| 1221 |
return upcast(this)->createInstance(upcast(asset)); |
| 1222 |
} |
| 1223 |
|
| 1224 |
void AssetLoader::enableDiagnostics(bool enable) { |
| 1225 |
upcast(this)->mDiagnosticsEnabled = enable; |
| 1226 |
} |
| 1227 |
|
| 1228 |
void AssetLoader::destroyAsset(const FilamentAsset* asset) { |
| 1229 |
upcast(this)->destroyAsset(upcast(asset)); |
| 1230 |
} |
| 1231 |
|
| 1232 |
size_t AssetLoader::getMaterialsCount() const noexcept { |
| 1233 |
return upcast(this)->getMaterialsCount(); |
| 1234 |
} |
| 1235 |
|
| 1236 |
NameComponentManager* AssetLoader::getNames() const noexcept { |
| 1237 |
return upcast(this)->getNames(); |
| 1238 |
} |
| 1239 |
|
| 1240 |
const Material* const* AssetLoader::getMaterials() const noexcept { |
| 1241 |
return upcast(this)->getMaterials(); |
| 1242 |
} |
| 1243 |
|
| 1244 |
} // namespace gltfio |