| 1 |
/* |
| 2 |
* Copyright (C) 2021 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 "MorphHelper.h" |
| 18 |
|
| 19 |
#include <filament/BufferObject.h> |
| 20 |
#include <filament/RenderableManager.h> |
| 21 |
#include <filament/VertexBuffer.h> |
| 22 |
|
| 23 |
#include "GltfEnums.h" |
| 24 |
#include "TangentsJob.h" |
| 25 |
|
| 26 |
using namespace filament; |
| 27 |
using namespace filament::math; |
| 28 |
using namespace utils; |
| 29 |
|
| 30 |
static constexpr uint8_t kUnused = 0xff; |
| 31 |
|
| 32 |
namespace gltfio { |
| 33 |
|
| 34 |
uint32_t computeBindingSize(const cgltf_accessor* accessor); |
| 35 |
uint32_t computeBindingOffset(const cgltf_accessor* accessor); |
| 36 |
|
| 37 |
static const auto FREE_CALLBACK = [](void* mem, size_t, void*) { free(mem); }; |
| 38 |
|
| 39 |
// Returns true if a is a subset of b. |
| 40 |
static bool isSubsetOf(ubyte4 a, ubyte4 b) { |
| 41 |
if (a.x != kUnused && a.x != b.x && a.x != b.y && a.x != b.z && a.x != b.w) return false; |
| 42 |
if (a.y != kUnused && a.y != b.x && a.y != b.y && a.y != b.z && a.y != b.w) return false; |
| 43 |
if (a.z != kUnused && a.z != b.x && a.z != b.y && a.z != b.z && a.z != b.w) return false; |
| 44 |
if (a.w != kUnused && a.w != b.x && a.w != b.y && a.w != b.z && a.w != b.w) return false; |
| 45 |
return true; |
| 46 |
} |
| 47 |
|
| 48 |
static int indexOf(int a, ubyte4 b) { |
| 49 |
if (a == b.x) return 0; |
| 50 |
if (a == b.y) return 1; |
| 51 |
if (a == b.z) return 2; |
| 52 |
if (a == b.w) return 3; |
| 53 |
return -1; |
| 54 |
} |
| 55 |
|
| 56 |
MorphHelper::MorphHelper(FFilamentAsset* asset, FFilamentInstance* inst) : mAsset(asset), |
| 57 |
mInstance(inst) { |
| 58 |
NodeMap& sourceNodes = asset->isInstanced() ? asset->mInstances[0]->nodeMap : asset->mNodeMap; |
| 59 |
for (auto pair : sourceNodes) { |
| 60 |
cgltf_node const* node = pair.first; |
| 61 |
cgltf_mesh const* mesh = node->mesh; |
| 62 |
if (mesh) { |
| 63 |
cgltf_primitive const* prims = mesh->primitives; |
| 64 |
for (cgltf_size pi = 0, count = mesh->primitives_count; pi < count; ++pi) { |
| 65 |
addPrimitive(mesh, pi, &mMorphTable[pair.second]); |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
MorphHelper::~MorphHelper() { |
| 72 |
auto engine = mAsset->mEngine; |
| 73 |
for (auto& entry : mMorphTable) { |
| 74 |
for (auto& prim : entry.second.primitives) { |
| 75 |
for (auto& target : prim.targets) { |
| 76 |
engine->destroy(target.bufferObject); |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
void MorphHelper::applyWeights(Entity entity, float const* weights, size_t count) noexcept { |
| 83 |
auto& engine = *mAsset->mEngine; |
| 84 |
auto renderableManager = &engine.getRenderableManager(); |
| 85 |
auto renderable = renderableManager->getInstance(entity); |
| 86 |
|
| 87 |
// If there are 4 or fewer targets, we can simply re-use the original VertexBuffer. |
| 88 |
if (count <= 4) { |
| 89 |
float4 vec{}; |
| 90 |
for (size_t i = 0; i < count; i++) { |
| 91 |
vec[i] = weights[i]; |
| 92 |
} |
| 93 |
renderableManager->setMorphWeights(renderable, vec); |
| 94 |
return; |
| 95 |
} |
| 96 |
|
| 97 |
// We honor up to 255 weights because our set representation is a 4-tuple of bytes, with one |
| 98 |
// slot reserved for a sentinel value. Note that 255 is much more than the glTF min spec of 4. |
| 99 |
count = std::min(count, size_t(255)); |
| 100 |
|
| 101 |
// Make a copy of the weights because we want to re-order them. |
| 102 |
auto& sorted = mPartiallySortedWeights; |
| 103 |
sorted.clear(); |
| 104 |
sorted.insert(sorted.begin(), weights, weights + count); |
| 105 |
|
| 106 |
// Find the four highest weights in O(n) by doing a partial sort. |
| 107 |
std::nth_element(sorted.begin(), sorted.begin() + 4, sorted.end(), [](float a, float b) { |
| 108 |
return a > b; |
| 109 |
}); |
| 110 |
|
| 111 |
// Find the "primary indices" which are the indices of the four highest weights. This is O(n). |
| 112 |
ubyte4 primaryIndices = {kUnused, kUnused, kUnused, kUnused}; |
| 113 |
for (size_t index = 0, primary = 0; index < count && primary < 4; ++index) { |
| 114 |
const float w = weights[index]; |
| 115 |
if (w > 0 && (w == sorted[0] || w == sorted[1] || w == sorted[2] || w == sorted[3])) { |
| 116 |
primaryIndices[primary++] = index; |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// Swap out the buffer objects for the primary indices. |
| 121 |
for (const auto& prim : mMorphTable[entity].primitives) { |
| 122 |
for (const auto& target : prim.targets) { |
| 123 |
const int index = indexOf(target.morphTargetIndex, primaryIndices); |
| 124 |
if (index > -1) { |
| 125 |
VertexBuffer* vb = prim.vertexBuffer; |
| 126 |
vb->setBufferObjectAt(engine, prim.baseSlot + index, target.bufferObject); |
| 127 |
// Do not break out early because there could be more than one target entry for this |
| 128 |
// particular target index (e.g. positions + tangents). |
| 129 |
} |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
// Finally, set the 4-tuple uniform for the weight values by derefing the primary indices. |
| 134 |
// Note that we first create a "safe set" by replacing the unused sentinel with zero. |
| 135 |
float4 highest; |
| 136 |
for (int i = 0; i < 4; i++) { |
| 137 |
highest[i] = (primaryIndices[i] == kUnused) ? 0 : weights[primaryIndices[i]]; |
| 138 |
} |
| 139 |
renderableManager->setMorphWeights(renderable, highest); |
| 140 |
} |
| 141 |
|
| 142 |
void MorphHelper::addPrimitive(cgltf_mesh const* mesh, int primitiveIndex, TableEntry* entry) { |
| 143 |
auto& engine = *mAsset->mEngine; |
| 144 |
const cgltf_primitive& prim = mesh->primitives[primitiveIndex]; |
| 145 |
VertexBuffer* vertexBuffer = mAsset->mMeshCache.at(mesh)[primitiveIndex].vertices; |
| 146 |
|
| 147 |
entry->primitives.push_back({ vertexBuffer, determineBaseSlot(prim) }); |
| 148 |
std::vector<GltfTarget>& targets = entry->primitives.back().targets; |
| 149 |
|
| 150 |
const cgltf_accessor* previous = nullptr; |
| 151 |
for (int targetIndex = 0; targetIndex < prim.targets_count; targetIndex++) { |
| 152 |
const cgltf_morph_target& morphTarget = prim.targets[targetIndex]; |
| 153 |
for (cgltf_size aindex = 0; aindex < morphTarget.attributes_count; aindex++) { |
| 154 |
const cgltf_attribute& attribute = morphTarget.attributes[aindex]; |
| 155 |
const cgltf_accessor* accessor = attribute.data; |
| 156 |
const cgltf_attribute_type atype = attribute.type; |
| 157 |
if (atype == cgltf_attribute_type_tangent) { |
| 158 |
continue; |
| 159 |
} |
| 160 |
if (atype == cgltf_attribute_type_normal) { |
| 161 |
|
| 162 |
// TODO: use JobSystem for this, like what we do for non-morph tangents. |
| 163 |
TangentsJob job; |
| 164 |
TangentsJob::Params params = { .in = { &prim, targetIndex } }; |
| 165 |
TangentsJob::run(¶ms); |
| 166 |
|
| 167 |
if (params.out.results) { |
| 168 |
const size_t size = params.out.vertexCount * sizeof(short4); |
| 169 |
BufferObject* bufferObject = BufferObject::Builder().size(size).build(engine); |
| 170 |
VertexBuffer::BufferDescriptor bd(params.out.results, size, FREE_CALLBACK); |
| 171 |
bufferObject->setBuffer(engine, std::move(bd)); |
| 172 |
params.out.results = nullptr; |
| 173 |
targets.push_back({bufferObject, targetIndex, atype}); |
| 174 |
} |
| 175 |
continue; |
| 176 |
} |
| 177 |
if (atype == cgltf_attribute_type_position) { |
| 178 |
// All position attributes must have the same data type. |
| 179 |
assert(!previous || previous->component_type == accessor->component_type); |
| 180 |
assert(!previous || previous->type == accessor->type); |
| 181 |
previous = accessor; |
| 182 |
|
| 183 |
// This should always be non-null, but don't crash if the glTF is malformed. |
| 184 |
if (accessor->buffer_view) { |
| 185 |
auto bufferData = (const uint8_t*) accessor->buffer_view->buffer->data; |
| 186 |
assert(bufferData); |
| 187 |
const uint8_t* data = computeBindingOffset(accessor) + bufferData; |
| 188 |
const uint32_t size = computeBindingSize(accessor); |
| 189 |
|
| 190 |
// This creates a copy because we don't know when the user will free the cgltf |
| 191 |
// source data. For non-morphed vertex buffers, we use a sharing mechanism to |
| 192 |
// prevent copies, but here we just want to keep it as simple as possible. |
| 193 |
uint8_t* clone = (uint8_t*) malloc(size); |
| 194 |
memcpy(clone, data, size); |
| 195 |
|
| 196 |
BufferObject* bufferObject = BufferObject::Builder().size(size).build(engine); |
| 197 |
VertexBuffer::BufferDescriptor bd(clone, size, FREE_CALLBACK); |
| 198 |
bufferObject->setBuffer(engine, std::move(bd)); |
| 199 |
targets.push_back({bufferObject, targetIndex, atype}); |
| 200 |
} |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
// This mimics some of the logic in AssetLoader in order to determine which VertexBuffer slots |
| 207 |
// correspond to the morph targets. |
| 208 |
int MorphHelper::determineBaseSlot(const cgltf_primitive& prim) const { |
| 209 |
int slot = 0; |
| 210 |
bool hasNormals = false; |
| 211 |
for (cgltf_size aindex = 0; aindex < prim.attributes_count; aindex++) { |
| 212 |
const cgltf_attribute& attribute = prim.attributes[aindex]; |
| 213 |
const int index = attribute.index; |
| 214 |
const cgltf_attribute_type atype = attribute.type; |
| 215 |
const cgltf_accessor* accessor = attribute.data; |
| 216 |
if (atype == cgltf_attribute_type_tangent) { |
| 217 |
continue; |
| 218 |
} |
| 219 |
if (atype == cgltf_attribute_type_normal) { |
| 220 |
slot++; |
| 221 |
hasNormals = true; |
| 222 |
continue; |
| 223 |
} |
| 224 |
slot++; |
| 225 |
} |
| 226 |
|
| 227 |
// If the model has lighting but not normals, then a slot is used for generated flat normals. |
| 228 |
if (prim.material && !prim.material->unlit && !hasNormals) { |
| 229 |
slot++; |
| 230 |
} |
| 231 |
|
| 232 |
return slot; |
| 233 |
}; |
| 234 |
|
| 235 |
} // namespace gltfio |