• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "mesh_util.h"
17 
18 #include <algorithm>
19 
20 #include <3d/ecs/components/material_component.h>
21 #include <3d/ecs/components/name_component.h>
22 #include <3d/ecs/components/render_mesh_component.h>
23 #include <3d/ecs/components/uri_component.h>
24 #include <3d/ecs/systems/intf_node_system.h>
25 #include <3d/implementation_uids.h>
26 #include <3d/render/default_material_constants.h>
27 #include <3d/util/intf_mesh_builder.h>
28 #include <base/containers/vector.h>
29 #include <base/math/quaternion_util.h>
30 #include <base/math/vector.h>
31 #include <core/ecs/intf_ecs.h>
32 #include <core/intf_engine.h>
33 #include <core/log.h>
34 #include <core/namespace.h>
35 #include <core/plugin/intf_class_factory.h>
36 #include <render/device/intf_shader_manager.h>
37 #include <render/implementation_uids.h>
38 #include <render/intf_render_context.h>
39 
40 #include "util/uri_lookup.h"
41 
42 CORE3D_BEGIN_NAMESPACE()
43 using namespace BASE_NS;
44 using namespace CORE_NS;
45 using namespace RENDER_NS;
46 
47 namespace {
48 constexpr Math::Vec3 PLANE_NORM[6u] = {
49     Math::Vec3(0.0f, 1.0f, 0.0f),
50     Math::Vec3(0.0f, 1.0f, 0.0f),
51     Math::Vec3(0.0f, 1.0f, 0.0f),
52 
53     Math::Vec3(0.0f, 1.0f, 0.0f),
54     Math::Vec3(0.0f, 1.0f, 0.0f),
55     Math::Vec3(0.0f, 1.0f, 0.0f),
56 };
57 
58 constexpr Math::Vec2 PLANE_UV[6u] = {
59     Math::Vec2(1.0f, 1.0f),
60     Math::Vec2(1.0f, 0.0f),
61     Math::Vec2(0.0f, 1.0f),
62 
63     Math::Vec2(1.0f, 0.0f),
64     Math::Vec2(0.0f, 0.0f),
65     Math::Vec2(0.0f, 1.0f),
66 };
67 
68 constexpr uint16_t PLANE_IND[] = { 0u, 1u, 2u, 3u, 4u, 5u };
69 
70 constexpr Math::Vec3 CUBE_POS[8u] = {
71     Math::Vec3(-0.5f, -0.5f, -0.5f), //
72     Math::Vec3(0.5f, -0.5f, -0.5f),  //
73     Math::Vec3(0.5f, 0.5f, -0.5f),   //
74     Math::Vec3(-0.5f, 0.5f, -0.5f),  //
75     Math::Vec3(-0.5f, -0.5f, 0.5f),  //
76     Math::Vec3(0.5f, -0.5f, 0.5f),   //
77     Math::Vec3(0.5f, 0.5f, 0.5f),    //
78     Math::Vec3(-0.5f, 0.5f, 0.5f)    //
79 };
80 
81 constexpr Math::Vec2 CUBE_UV[4u] = { Math::Vec2(1.0f, 1.0f), Math::Vec2(0.0f, 1.0f), Math::Vec2(0.0f, 0.0f),
82     Math::Vec2(1.0f, 0.0f) };
83 
84 constexpr uint16_t CUBE_INDICES[6u * 6u] = {
85     0, 3, 1, 3, 2, 1, //
86     1, 2, 5, 2, 6, 5, //
87     5, 6, 4, 6, 7, 4, //
88     4, 7, 0, 7, 3, 0, //
89     3, 7, 2, 7, 6, 2, //
90     4, 0, 5, 0, 1, 5  //
91 };
92 
93 constexpr uint32_t CUBE_UV_INDICES[6u] = { 0, 3, 1, 3, 2, 1 };
94 
95 constexpr float TWO_PI = Math::PI * 2.0f;
96 
97 template<typename IndexType>
98 struct Geometry {
99     vector<Math::Vec3>& vertices;
100     vector<Math::Vec3>& normals;
101     vector<Math::Vec2>& uvs;
102     vector<IndexType>& indices;
103 };
104 
GenerateCubeGeometry(float width,float height,float depth,Geometry<uint16_t> geometry)105 void GenerateCubeGeometry(float width, float height, float depth, Geometry<uint16_t> geometry)
106 {
107     vector<Math::Vec3>& vertices = geometry.vertices;
108     vector<Math::Vec3>& normals = geometry.normals;
109     vector<Math::Vec2>& uvs = geometry.uvs;
110     vector<uint16_t>& indices = geometry.indices;
111 
112     vertices.reserve(countof(CUBE_INDICES));
113     normals.reserve(countof(CUBE_INDICES));
114     uvs.reserve(countof(CUBE_INDICES));
115     indices.reserve(countof(CUBE_INDICES));
116 
117     constexpr size_t triangleCount = countof(CUBE_INDICES) / 3u;
118     for (size_t i = 0; i < triangleCount; ++i) {
119         const size_t vertexIndex = i * 3u;
120 
121         const Math::Vec3 v0 = CUBE_POS[CUBE_INDICES[vertexIndex + 0u]];
122         const Math::Vec3 v1 = CUBE_POS[CUBE_INDICES[vertexIndex + 1u]];
123         const Math::Vec3 v2 = CUBE_POS[CUBE_INDICES[vertexIndex + 2u]];
124 
125         vertices.emplace_back(v0.x * width, v0.y * height, v0.z * depth);
126         vertices.emplace_back(v1.x * width, v1.y * height, v1.z * depth);
127         vertices.emplace_back(v2.x * width, v2.y * height, v2.z * depth);
128 
129         const Math::Vec3 normal = Math::Normalize(Math::Cross((v1 - v0), (v2 - v0)));
130         normals.append(3u, normal);
131 
132         uvs.emplace_back(
133             CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 0u) % 6u]].x, CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 0u) % 6u]].y);
134         uvs.emplace_back(
135             CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 1u) % 6u]].x, CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 1u) % 6u]].y);
136         uvs.emplace_back(
137             CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 2u) % 6u]].x, CUBE_UV[CUBE_UV_INDICES[(vertexIndex + 2u) % 6u]].y);
138     }
139 
140     for (uint16_t i = 0u; i < countof(CUBE_INDICES); ++i) {
141         indices.push_back(i);
142     }
143 }
144 
GenerateSphereGeometry(float radius,uint32_t rings,uint32_t sectors,Geometry<uint32_t> geometry)145 void GenerateSphereGeometry(float radius, uint32_t rings, uint32_t sectors, Geometry<uint32_t> geometry)
146 {
147     vector<Math::Vec3>& vertices = geometry.vertices;
148     vector<Math::Vec3>& normals = geometry.normals;
149     vector<Math::Vec2>& uvs = geometry.uvs;
150     vector<uint32_t>& indices = geometry.indices;
151 
152     const size_t maxVertexCount = rings * sectors;
153     const size_t maxIndexCount = (rings - 1) * sectors * 6u;
154 
155     vertices.reserve(maxVertexCount);
156     normals.reserve(maxVertexCount);
157     uvs.reserve(maxVertexCount);
158     indices.reserve(maxIndexCount);
159 
160     const float r = 1.0f / static_cast<float>(rings - 1);
161     const float s = 1.0f / static_cast<float>(sectors - 1);
162 
163     constexpr float pi = Math::PI;
164     constexpr float halfPi = Math::PI * 0.5f;
165 
166     for (uint32_t ring = 0; ring < rings; ++ring) {
167         const auto ringF = static_cast<float>(ring);
168         for (uint32_t sector = 0; sector < sectors; ++sector) {
169             const auto sectorF = static_cast<float>(sector);
170             const float y = Math::sin(-halfPi + pi * ringF * r);
171             const float x = Math::cos(TWO_PI * sectorF * s) * Math::sin(pi * ringF * r);
172             const float z = Math::sin(TWO_PI * sectorF * s) * Math::sin(pi * ringF * r);
173 
174             vertices.emplace_back(x * radius, y * radius, z * radius);
175             normals.emplace_back(x, y, z);
176             uvs.emplace_back(sectorF * s, ringF * r);
177 
178             if (ring < rings - 1) {
179                 const uint32_t curRow = ring * sectors;
180                 const uint32_t nextRow = (ring + 1) * sectors;
181                 const uint32_t nextS = (sector + 1) % sectors;
182 
183                 indices.push_back(curRow + sector);
184                 indices.push_back(nextRow + sector);
185                 indices.push_back(nextRow + nextS);
186 
187                 indices.push_back(curRow + sector);
188                 indices.push_back(nextRow + nextS);
189                 indices.push_back(curRow + nextS);
190             }
191         }
192     }
193 }
194 
GenerateConeCap(float radius,float length,uint32_t sectors,Geometry<uint32_t> geometry,const vector<Math::Vec2> & unitCoords)195 void GenerateConeCap(
196     float radius, float length, uint32_t sectors, Geometry<uint32_t> geometry, const vector<Math::Vec2>& unitCoords)
197 {
198     vector<Math::Vec3>& vertices = geometry.vertices;
199     vector<Math::Vec3>& normals = geometry.normals;
200     vector<Math::Vec2>& uvs = geometry.uvs;
201     vector<uint32_t>& indices = geometry.indices;
202 
203     // Already generated vertices: tip + sectors
204     uint32_t startVertex = 1U + sectors;
205 
206     // Cap center vert.
207     const uint32_t bottomIndex = startVertex;
208     vertices.emplace_back(0.0f, 0.0f, length);
209     normals.emplace_back(0.0f, 0.0f, 1.0f);
210     uvs.emplace_back(0.5f, 0.5f);
211 
212     ++startVertex;
213 
214     // Cap ring and triangles.
215     for (uint32_t idx = 0; idx < sectors; ++idx) {
216         const uint32_t vertexIndex = startVertex + idx;
217 
218         const Math::Vec2& coords = unitCoords[idx];
219 
220         vertices.emplace_back(coords.x * radius, coords.y * radius, length);
221         normals.emplace_back(0.0f, 0.0f, 1.0f);
222 
223         float uvx = (coords.x + 1.0f) * 0.5f;
224         float uvy = 1.0f - (coords.y + 1.0f) * 0.5f;
225         uvs.emplace_back(uvx, uvy);
226 
227         const uint32_t nextVertexIndex = startVertex + ((idx + 1) % sectors);
228 
229         indices.push_back(vertexIndex);
230         indices.push_back(nextVertexIndex);
231         indices.push_back(bottomIndex);
232     }
233 }
234 
GenerateConeGeometry(float radius,float length,uint32_t sectors,Geometry<uint32_t> geometry)235 void GenerateConeGeometry(float radius, float length, uint32_t sectors, Geometry<uint32_t> geometry)
236 {
237     vector<Math::Vec3>& vertices = geometry.vertices;
238     vector<Math::Vec3>& normals = geometry.normals;
239     vector<Math::Vec2>& uvs = geometry.uvs;
240     vector<uint32_t>& indices = geometry.indices;
241 
242     const float s = (sectors > 0U) ? (1.0f / static_cast<float>(sectors)) : 1.0f;
243 
244     const size_t maxVertexCount = (2 * static_cast<size_t>(sectors)) + 2u;
245     const size_t maxIndexCount = static_cast<size_t>(sectors) * 6u;
246 
247     vertices.reserve(maxVertexCount);
248     normals.reserve(maxVertexCount);
249     uvs.reserve(maxVertexCount);
250     indices.reserve(maxIndexCount);
251 
252     vector<Math::Vec2> unitCoords;
253     unitCoords.reserve(sectors);
254 
255     vertices.emplace_back(0.0f, 0.0f, 0.0f);
256     normals.emplace_back(0.0f, 0.0f, -1.0f);
257     uvs.emplace_back(0.5f, 0.5f);
258 
259     // Bottom ring vertices and side triangles, with given radius
260     const uint32_t startVertex = 1U;
261     for (uint32_t idx = 0; idx < sectors; ++idx) {
262         const auto idxF = static_cast<float>(idx);
263         const float x = Math::cos(idxF * s * TWO_PI);
264         const float y = Math::sin(idxF * s * TWO_PI);
265         unitCoords.emplace_back(x, y);
266 
267         vertices.emplace_back(x * radius, y * radius, length);
268         normals.emplace_back(x, y, 0.f);
269 
270         float uvx = (x + 1.0f) * 0.5f;
271         float uvy = 1.0f - (y + 1.0f) * 0.5f;
272         uvs.emplace_back(uvx, uvy);
273 
274         const uint32_t v0 = 0;
275         const uint32_t v1 = startVertex + idx;
276         const uint32_t v2 = startVertex + ((idx + 1) % sectors);
277 
278         indices.push_back(v0);
279         indices.push_back(v2);
280         indices.push_back(v1);
281     }
282 
283     constexpr bool generateCapping = true;
284     if constexpr (generateCapping) {
285         GenerateConeCap(radius, length, sectors, geometry, unitCoords);
286     }
287 }
288 
GenerateTorusSlices(float minorRadius,uint32_t minorSectors,float minorStep)289 vector<Math::Vec3> GenerateTorusSlices(float minorRadius, uint32_t minorSectors, float minorStep)
290 {
291     vector<Math::Vec3> tubeSlice;
292     tubeSlice.reserve(minorSectors);
293     for (uint32_t tube = 0; tube < minorSectors; tube++) {
294         const float minorRadians = static_cast<float>(tube) * minorStep;
295         const float x = 0.0f;
296         const float y = Math::cos(minorRadians) * minorRadius;
297         const float z = Math::sin(minorRadians) * minorRadius;
298         tubeSlice.emplace_back(x, y, z);
299     }
300     return tubeSlice;
301 }
302 
GenerateTorusGeometry(float majorRadius,float minorRadius,uint32_t majorSectors,uint32_t minorSectors,Geometry<uint32_t> geometry)303 void GenerateTorusGeometry(
304     float majorRadius, float minorRadius, uint32_t majorSectors, uint32_t minorSectors, Geometry<uint32_t> geometry)
305 {
306     vector<Math::Vec3>& vertices = geometry.vertices;
307     vector<Math::Vec3>& normals = geometry.normals;
308     vector<Math::Vec2>& uvs = geometry.uvs;
309     vector<uint32_t>& indices = geometry.indices;
310 
311     const float majorStep = TWO_PI / static_cast<float>(majorSectors);
312     const float minorStep = TWO_PI / static_cast<float>(minorSectors);
313 
314     const size_t maxVertexCount = static_cast<size_t>(majorSectors) * static_cast<size_t>(minorSectors);
315     const size_t maxIndexCount = maxVertexCount * 6u;
316 
317     vertices.reserve(maxVertexCount);
318     normals.reserve(maxVertexCount);
319     uvs.reserve(maxVertexCount);
320     indices.reserve(maxIndexCount);
321 
322     const vector<Math::Vec3> tubeSlice = GenerateTorusSlices(minorRadius, minorSectors, minorStep);
323 
324     uint32_t currentVertexIndex = 0;
325     for (uint32_t ring = 0; ring < majorSectors; ring++) {
326         const float majorRadians = static_cast<float>(ring) * majorStep;
327         const auto rotation = Math::AngleAxis(majorRadians, { 0.0f, 1.0f, 0.0f });
328         const auto translation = Math::Vec3(0.0f, 0.0f, 1.0f) * majorRadius;
329 
330         for (uint32_t vertexIndex = 0; vertexIndex < minorSectors; vertexIndex++) {
331             const auto& ringVertex = tubeSlice[vertexIndex];
332 
333             const auto tubeCenter = rotation * translation;
334 
335             vertices.push_back(rotation * ringVertex + tubeCenter);
336 
337             normals.push_back(Math::Normalize(rotation * ringVertex));
338 
339             const float minorRadians = static_cast<float>(vertexIndex) * minorStep;
340             const float tx = 1.0f - Math::abs(majorRadians / TWO_PI * 2.0f - 1.0f);
341             const float ty = 1.0f - Math::abs(minorRadians / TWO_PI * 2.0f - 1.0f);
342             uvs.emplace_back(tx, ty);
343 
344             const uint32_t i0 = currentVertexIndex;
345             const uint32_t i1 = (i0 + 1) % maxVertexCount;
346             const uint32_t i2 = (i0 + minorSectors) % maxVertexCount;
347             const uint32_t i3 = (i2 + 1) % maxVertexCount;
348 
349             indices.push_back(i0);
350             indices.push_back(i1);
351             indices.push_back(i2);
352 
353             indices.push_back(i1);
354             indices.push_back(i3);
355             indices.push_back(i2);
356 
357             currentVertexIndex++;
358         }
359     }
360 }
361 } // namespace
362 
363 template<typename IndexType>
CalculateTangentImpl(const array_view<const IndexType> & indices,const array_view<const Math::Vec3> & positions,const array_view<const Math::Vec3> & normals,const array_view<const Math::Vec2> & uvs,array_view<Math::Vec4> & outTangents)364 void CalculateTangentImpl(const array_view<const IndexType>& indices, const array_view<const Math::Vec3>& positions,
365     const array_view<const Math::Vec3>& normals, const array_view<const Math::Vec2>& uvs,
366     array_view<Math::Vec4>& outTangents)
367 {
368     // http://www.terathon.com/code/tangent.html
369     vector<Math::Vec3> tan(positions.size(), { 0, 0, 0 });
370     vector<Math::Vec3> bitan(positions.size(), { 0, 0, 0 });
371 
372     for (size_t i = 0; i < indices.size(); i += 3u) {
373         const IndexType aa = indices[i + 0u];
374         const IndexType bb = indices[i + 1u];
375         const IndexType cc = indices[i + 2u];
376 
377         const Math::Vec2& uv1 = uvs[aa];
378         const Math::Vec2& uv2 = uvs[bb];
379         const Math::Vec2& uv3 = uvs[cc];
380 
381         const auto st1 = uv2 - uv1;
382         const auto st2 = uv3 - uv1;
383 
384         auto d = Math::Cross(st1, st2);
385         if (Math::abs(d) < Math::EPSILON) {
386             d = Math::EPSILON;
387         }
388         const float r = 1.0f / d;
389 
390         const Math::Vec3& v1 = positions[aa];
391         const Math::Vec3& v2 = positions[bb];
392         const Math::Vec3& v3 = positions[cc];
393 
394         const auto e1 = v2 - v1;
395         const auto e2 = v3 - v1;
396 
397         const Math::Vec3 sdir { (e1 * st2.y - e2 * st1.y) * r };
398         tan[aa] += sdir;
399         tan[bb] += sdir;
400         tan[cc] += sdir;
401 
402         const Math::Vec3 tdir { (e2 * st1.x - e1 * st2.x) * r };
403 
404         bitan[aa] += tdir;
405         bitan[bb] += tdir;
406         bitan[cc] += tdir;
407     }
408 
409     for (size_t i = 0; i < positions.size(); i++) {
410         const Math::Vec3& n = normals[i];
411         const Math::Vec3& t = tan[i];
412 
413         // Gram-Schmidt orthogonalize
414         const Math::Vec3 tmp = Math::Normalize(t - n * Math::Dot(n, t));
415 
416         // Calculate handedness
417         const float w = (Math::Dot(Math::Cross(n, t), bitan[i]) < 0.0F) ? 1.0F : -1.0F;
418 
419         outTangents[i] = Math::Vec4(tmp.x, tmp.y, tmp.z, w);
420     }
421 }
422 
CalculateTangents(const array_view<const uint32_t> & indices,const array_view<const Math::Vec3> & positions,const array_view<const Math::Vec3> & normals,const array_view<const Math::Vec2> & uvs,array_view<Math::Vec4> outTangents)423 void MeshUtil::CalculateTangents(const array_view<const uint32_t>& indices,
424     const array_view<const Math::Vec3>& positions, const array_view<const Math::Vec3>& normals,
425     const array_view<const Math::Vec2>& uvs, array_view<Math::Vec4> outTangents)
426 {
427     CalculateTangentImpl<uint32_t>(indices, positions, normals, uvs, outTangents);
428 }
429 
CalculateTangents(const array_view<const uint16_t> & indices,const array_view<const Math::Vec3> & positions,const array_view<const Math::Vec3> & normals,const array_view<const Math::Vec2> & uvs,array_view<Math::Vec4> outTangents)430 void MeshUtil::CalculateTangents(const array_view<const uint16_t>& indices,
431     const array_view<const Math::Vec3>& positions, const array_view<const Math::Vec3>& normals,
432     const array_view<const Math::Vec2>& uvs, array_view<Math::Vec4> outTangents)
433 {
434     CalculateTangentImpl<uint16_t>(indices, positions, normals, uvs, outTangents);
435 }
436 
CalculateTangents(const array_view<const uint8_t> & indices,const array_view<const Math::Vec3> & positions,const array_view<const Math::Vec3> & normals,const array_view<const Math::Vec2> & uvs,array_view<Math::Vec4> outTangents)437 void MeshUtil::CalculateTangents(const array_view<const uint8_t>& indices,
438     const array_view<const Math::Vec3>& positions, const array_view<const Math::Vec3>& normals,
439     const array_view<const Math::Vec2>& uvs, array_view<Math::Vec4> outTangents)
440 {
441     CalculateTangentImpl<uint8_t>(indices, positions, normals, uvs, outTangents);
442 }
443 
444 template<typename T>
FillData(array_view<const T> c)445 constexpr inline IMeshBuilder::DataBuffer FillData(array_view<const T> c) noexcept
446 {
447     Format format = BASE_FORMAT_UNDEFINED;
448     if constexpr (is_same_v<T, Math::Vec2>) {
449         format = BASE_FORMAT_R32G32_SFLOAT;
450     } else if constexpr (is_same_v<T, Math::Vec3>) {
451         format = BASE_FORMAT_R32G32B32_SFLOAT;
452     } else if constexpr (is_same_v<T, Math::Vec4>) {
453         format = BASE_FORMAT_R32G32B32A32_SFLOAT;
454     } else if constexpr (is_same_v<T, uint16_t>) {
455         format = BASE_FORMAT_R16_UINT;
456     } else if constexpr (is_same_v<T, uint32_t>) {
457         format = BASE_FORMAT_R32_UINT;
458     }
459     return IMeshBuilder::DataBuffer { format, sizeof(T),
460         { reinterpret_cast<const uint8_t*>(c.data()), c.size() * sizeof(T) } };
461 }
462 
463 template<typename T, size_t N>
FillData(const T (& c)[N])464 constexpr inline IMeshBuilder::DataBuffer FillData(const T (&c)[N]) noexcept
465 {
466     return FillData(array_view(c, N));
467 }
468 
469 template<typename T>
FillData(const vector<T> & c)470 constexpr inline IMeshBuilder::DataBuffer FillData(const vector<T>& c) noexcept
471 {
472     return FillData(array_view<const T> { c });
473 }
474 
GeneratePlaneMesh(const IEcs & ecs,const string_view name,Entity material,float width,float depth)475 Entity MeshUtil::GeneratePlaneMesh(const IEcs& ecs, const string_view name, Entity material, float width, float depth)
476 {
477     const float extentX = width * 0.5f;
478     const float extentZ = depth * 0.5f;
479 
480     const Math::Vec3 pos[6u] = {
481         Math::Vec3(-extentX, 0.0f, -extentZ),
482         Math::Vec3(-extentX, 0.0f, extentZ),
483         Math::Vec3(extentX, 0.0f, -extentZ),
484 
485         Math::Vec3(-extentX, 0.0f, extentZ),
486         Math::Vec3(extentX, 0.0f, extentZ),
487         Math::Vec3(extentX, 0.0f, -extentZ),
488     };
489     vector<Math::Vec4> tangents(countof(pos));
490     {
491         constexpr auto indicesView = array_view(PLANE_IND);
492         const auto positionsView = array_view(pos);
493         constexpr auto normalsView = array_view(PLANE_NORM);
494         constexpr auto uvsView = array_view(PLANE_UV);
495 
496         CalculateTangents(indicesView, positionsView, normalsView, uvsView, tangents);
497     }
498 
499     IMeshBuilder::Submesh submesh;
500     submesh.material = material;
501     submesh.vertexCount = 6u;
502     submesh.indexCount = 6u;
503     submesh.indexType = CORE_INDEX_TYPE_UINT16;
504     submesh.tangents = true;
505 
506     auto builder = InitializeBuilder(submesh);
507 
508     auto positionData = FillData(pos);
509     auto normalData = FillData(PLANE_NORM);
510     auto uvData = FillData(PLANE_UV);
511     auto tangentData = FillData(tangents);
512     IMeshBuilder::DataBuffer dummy {};
513     builder->SetVertexData(0, positionData, normalData, uvData, dummy, tangentData, dummy);
514 
515     builder->CalculateAABB(0, positionData);
516 
517     auto indices = FillData(PLANE_IND);
518     builder->SetIndexData(0, indices);
519 
520     return CreateMesh(ecs, *builder, name);
521 }
522 
GenerateSphereMesh(const IEcs & ecs,const string_view name,Entity material,float radius,uint32_t rings,uint32_t sectors)523 Entity MeshUtil::GenerateSphereMesh(
524     const IEcs& ecs, const string_view name, Entity material, float radius, uint32_t rings, uint32_t sectors)
525 {
526     vector<Math::Vec3> vertices;
527     vector<Math::Vec3> normals;
528     vector<Math::Vec2> uvs;
529     vector<uint32_t> indices;
530     GenerateSphereGeometry(radius, rings, sectors, { vertices, normals, uvs, indices });
531 
532     vector<Math::Vec4> tangents(vertices.size());
533     CalculateTangents(indices, vertices, normals, uvs, tangents);
534 
535     IMeshBuilder::Submesh submesh;
536     submesh.material = material;
537     submesh.vertexCount = static_cast<uint32_t>(vertices.size());
538     submesh.indexCount = static_cast<uint32_t>(indices.size());
539     submesh.indexType = submesh.vertexCount <= UINT16_MAX ? CORE_INDEX_TYPE_UINT16 : CORE_INDEX_TYPE_UINT32;
540     submesh.tangents = true;
541 
542     auto builder = InitializeBuilder(submesh);
543 
544     auto positionData = FillData(vertices);
545     auto normalData = FillData(normals);
546     auto uvData = FillData(uvs);
547     auto tangentData = FillData(tangents);
548     IMeshBuilder::DataBuffer dummy {};
549     builder->SetVertexData(0, positionData, normalData, uvData, dummy, tangentData, dummy);
550 
551     builder->CalculateAABB(0, positionData);
552 
553     auto indexData = FillData(indices);
554     builder->SetIndexData(0, indexData);
555 
556     return CreateMesh(ecs, *builder, name);
557 }
558 
GenerateConeMesh(const IEcs & ecs,const string_view name,Entity material,float radius,float length,uint32_t sectors)559 Entity MeshUtil::GenerateConeMesh(
560     const IEcs& ecs, const string_view name, Entity material, float radius, float length, uint32_t sectors)
561 {
562     vector<Math::Vec3> vertices;
563     vector<Math::Vec3> normals;
564     vector<Math::Vec2> uvs;
565     vector<uint32_t> indices;
566     GenerateConeGeometry(radius, length, sectors, { vertices, normals, uvs, indices });
567 
568     IMeshBuilder::Submesh submesh;
569     submesh.material = material;
570     submesh.vertexCount = static_cast<uint32_t>(vertices.size());
571     submesh.indexCount = static_cast<uint32_t>(indices.size());
572     submesh.indexType = submesh.vertexCount <= UINT16_MAX ? CORE_INDEX_TYPE_UINT16 : CORE_INDEX_TYPE_UINT32;
573     submesh.tangents = true;
574 
575     vector<Math::Vec4> tangents(vertices.size());
576     CalculateTangents(indices, vertices, normals, uvs, tangents);
577 
578     auto builder = InitializeBuilder(submesh);
579 
580     auto positionData = FillData(vertices);
581     auto normalData = FillData(normals);
582     auto uvData = FillData(uvs);
583     auto tangentData = FillData(tangents);
584     IMeshBuilder::DataBuffer dummy {};
585     builder->SetVertexData(0, positionData, normalData, uvData, dummy, tangentData, dummy);
586 
587     builder->CalculateAABB(0, positionData);
588 
589     auto indexData = FillData(indices);
590     builder->SetIndexData(0, indexData);
591 
592     return CreateMesh(ecs, *builder, name);
593 }
594 
GenerateTorusMesh(const IEcs & ecs,const string_view name,Entity material,float majorRadius,float minorRadius,uint32_t majorSectors,uint32_t minorSectors)595 Entity MeshUtil::GenerateTorusMesh(const IEcs& ecs, const string_view name, Entity material, float majorRadius,
596     float minorRadius, uint32_t majorSectors, uint32_t minorSectors)
597 {
598     vector<Math::Vec3> vertices;
599     vector<Math::Vec3> normals;
600     vector<Math::Vec2> uvs;
601     vector<uint32_t> indices;
602     GenerateTorusGeometry(majorRadius, minorRadius, majorSectors, minorSectors, { vertices, normals, uvs, indices });
603 
604     vector<Math::Vec4> tangents(vertices.size());
605     CalculateTangents(indices, vertices, normals, uvs, tangents);
606 
607     IMeshBuilder::Submesh submesh;
608     submesh.material = material;
609     submesh.vertexCount = static_cast<uint32_t>(vertices.size());
610     submesh.indexCount = static_cast<uint32_t>(indices.size());
611     submesh.indexType = submesh.vertexCount <= UINT16_MAX ? CORE_INDEX_TYPE_UINT16 : CORE_INDEX_TYPE_UINT32;
612     submesh.tangents = true;
613 
614     auto builder = InitializeBuilder(submesh);
615 
616     auto positionData = FillData(vertices);
617     auto normalData = FillData(normals);
618     auto uvData = FillData(uvs);
619     auto tangentData = FillData(tangents);
620     IMeshBuilder::DataBuffer dummy {};
621     builder->SetVertexData(0, positionData, normalData, uvData, dummy, tangentData, dummy);
622 
623     builder->CalculateAABB(0, positionData);
624 
625     auto indexData = FillData(indices);
626     builder->SetIndexData(0, indexData);
627 
628     return CreateMesh(ecs, *builder, name);
629 }
630 
GenerateCubeMesh(const IEcs & ecs,const string_view name,Entity material,float width,float height,float depth)631 Entity MeshUtil::GenerateCubeMesh(
632     const IEcs& ecs, const string_view name, Entity material, float width, float height, float depth)
633 {
634     vector<Math::Vec3> positions;
635     vector<Math::Vec3> normals;
636     vector<Math::Vec2> uvs;
637     vector<uint16_t> indices;
638     GenerateCubeGeometry(width, height, depth, { positions, normals, uvs, indices });
639 
640     vector<Math::Vec4> tangents(positions.size());
641     CalculateTangents(indices, positions, normals, uvs, tangents);
642 
643     IMeshBuilder::Submesh submesh;
644     submesh.material = material;
645     submesh.vertexCount = static_cast<uint32_t>(countof(CUBE_INDICES));
646     submesh.indexCount = static_cast<uint32_t>(countof(CUBE_INDICES));
647     submesh.indexType = CORE_INDEX_TYPE_UINT16;
648     submesh.tangents = true;
649 
650     auto builder = InitializeBuilder(submesh);
651 
652     auto positionData = FillData(positions);
653     auto normalData = FillData(normals);
654     auto uvData = FillData(uvs);
655     auto tangentData = FillData(tangents);
656     IMeshBuilder::DataBuffer dummy {};
657     builder->SetVertexData(0, positionData, normalData, uvData, dummy, tangentData, dummy);
658 
659     builder->CalculateAABB(0, positionData);
660 
661     auto indexData = FillData(indices);
662     builder->SetIndexData(0, indexData);
663 
664     return CreateMesh(ecs, *builder, name);
665 }
666 
GenerateEntity(const IEcs & ecs,const string_view name,Entity meshHandle)667 Entity MeshUtil::GenerateEntity(const IEcs& ecs, const string_view name, Entity meshHandle)
668 {
669     INodeSystem* nodesystem = GetSystem<INodeSystem>(ecs);
670     CORE_ASSERT(nodesystem);
671 
672     // Create node to scene.
673     ISceneNode* node = nodesystem->CreateNode();
674     if (!node) {
675         return Entity {};
676     }
677 
678     node->SetName(name);
679 
680     // Add render mesh component.
681     IRenderMeshComponentManager* renderMeshManager = GetManager<IRenderMeshComponentManager>(ecs);
682     CORE_ASSERT(renderMeshManager);
683 
684     RenderMeshComponent component = CreateComponent(*renderMeshManager, node->GetEntity());
685     component.mesh = meshHandle;
686     renderMeshManager->Set(node->GetEntity(), component);
687 
688     return node->GetEntity();
689 }
690 
GenerateCube(const IEcs & ecs,const string_view name,Entity material,float width,float height,float depth)691 Entity MeshUtil::GenerateCube(
692     const IEcs& ecs, const string_view name, Entity material, float width, float height, float depth)
693 {
694     const Entity meshHandle = GenerateCubeMesh(ecs, name, material, width, height, depth);
695     return GenerateEntity(ecs, name, meshHandle);
696 }
697 
GeneratePlane(const IEcs & ecs,const string_view name,Entity material,float width,float depth)698 Entity MeshUtil::GeneratePlane(const IEcs& ecs, const string_view name, Entity material, float width, float depth)
699 {
700     const Entity meshHandle = GeneratePlaneMesh(ecs, name, material, width, depth);
701     return GenerateEntity(ecs, name, meshHandle);
702 }
703 
GenerateSphere(const IEcs & ecs,const string_view name,Entity material,float radius,uint32_t rings,uint32_t sectors)704 Entity MeshUtil::GenerateSphere(
705     const IEcs& ecs, const string_view name, Entity material, float radius, uint32_t rings, uint32_t sectors)
706 {
707     const Entity meshHandle = GenerateSphereMesh(ecs, name, material, radius, rings, sectors);
708     return GenerateEntity(ecs, name, meshHandle);
709 }
710 
GenerateCone(const IEcs & ecs,const string_view name,Entity material,float radius,float length,uint32_t sectors)711 Entity MeshUtil::GenerateCone(
712     const IEcs& ecs, const string_view name, Entity material, float radius, float length, uint32_t sectors)
713 {
714     const Entity meshHandle = GenerateConeMesh(ecs, name, material, radius, length, sectors);
715     return GenerateEntity(ecs, name, meshHandle);
716 }
717 
GenerateTorus(const IEcs & ecs,const string_view name,Entity material,float majorRadius,float minorRadius,uint32_t majorSectors,uint32_t minorSectors)718 Entity MeshUtil::GenerateTorus(const IEcs& ecs, const string_view name, Entity material, float majorRadius,
719     float minorRadius, uint32_t majorSectors, uint32_t minorSectors)
720 {
721     const Entity meshHandle =
722         GenerateTorusMesh(ecs, name, material, majorRadius, minorRadius, majorSectors, minorSectors);
723     return GenerateEntity(ecs, name, meshHandle);
724 }
725 
InitializeBuilder(const IMeshBuilder::Submesh & submesh) const726 IMeshBuilder::Ptr MeshUtil::InitializeBuilder(const IMeshBuilder::Submesh& submesh) const
727 {
728     IMeshBuilder::Ptr builder;
729     if (IClassRegister* classRegister = factory_.GetInterface<IClassRegister>(); classRegister) {
730         auto renderContext = GetInstance<IRenderContext>(*classRegister, UID_RENDER_CONTEXT);
731         IShaderManager& shaderManager = renderContext->GetDevice().GetShaderManager();
732         const VertexInputDeclarationView vertexInputDeclaration =
733             shaderManager.GetVertexInputDeclarationView(shaderManager.GetVertexInputDeclarationHandle(
734                 DefaultMaterialShaderConstants::VERTEX_INPUT_DECLARATION_FORWARD));
735         builder = CreateInstance<IMeshBuilder>(*renderContext, UID_MESH_BUILDER);
736         builder->Initialize(vertexInputDeclaration, 1);
737 
738         builder->AddSubmesh(submesh);
739         builder->Allocate();
740     }
741 
742     return builder;
743 }
744 
CreateMesh(const IEcs & ecs,const IMeshBuilder & builder,const string_view name) const745 Entity MeshUtil::CreateMesh(const IEcs& ecs, const IMeshBuilder& builder, const string_view name) const
746 {
747     auto meshEntity = builder.CreateMesh(const_cast<IEcs&>(ecs));
748     if (!name.empty()) {
749         GetManager<IUriComponentManager>(ecs)->Set(meshEntity, { string(name) });
750         GetManager<INameComponentManager>(ecs)->Set(meshEntity, { string(name) });
751     }
752     return meshEntity;
753 }
754 
MeshUtil(IClassFactory & factory)755 MeshUtil::MeshUtil(IClassFactory& factory) : factory_(factory) {}
756 CORE3D_END_NAMESPACE()
757