summaryrefslogtreecommitdiff
path: root/indra/newview/gltf/primitive.cpp
blob: b5d59e1b24a380a0fbe0f802510691ecbb82c1f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/**
 * @file primitive.cpp
 * @brief LL GLTF Implementation
 *
 * $LicenseInfo:firstyear=2024&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2024, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only. 
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "../llviewerprecompiledheaders.h"

#include "asset.h"
#include "../lltinygltfhelper.h"

using namespace LL::GLTF;

#ifdef _MSC_VER
#define LL_FUNCSIG __FUNCSIG__ 
#else
#define LL_FUNCSIG __PRETTY_FUNCTION__
#endif

// copy one vec3 from src to dst
template<class S, class T>
void copyVec2(S* src, T& dst)
{
    LL_ERRS() << "TODO: implement " << LL_FUNCSIG << LL_ENDL;
}

// copy one vec3 from src to dst
template<class S, class T>
void copyVec3(S* src, T& dst)
{
    LL_ERRS() << "TODO: implement " << LL_FUNCSIG << LL_ENDL;
}

// copy one vec4 from src to dst
template<class S, class T>
void copyVec4(S* src, T& dst)
{
    LL_ERRS() << "TODO: implement " << LL_FUNCSIG << LL_ENDL;
}

template<>
void copyVec2<F32, LLVector2>(F32* src, LLVector2& dst)
{
    dst.set(src[0], src[1]);
}

template<>
void copyVec3<F32, LLVector4a>(F32* src, LLVector4a& dst)
{
    dst.load3(src);
}

template<>
void copyVec3<U16, LLColor4U>(U16* src, LLColor4U& dst)
{
    dst.set(src[0], src[1], src[2], 255);
}

template<>
void copyVec4<F32, LLVector4a>(F32* src, LLVector4a& dst)
{
    dst.loadua(src);
}

// copy from src to dst, stride is the number of bytes between each element in src, count is number of elements to copy
template<class S, class T>
void copyVec2(S* src, LLStrider<T> dst, S32 stride, S32 count)
{
    for (S32 i = 0; i < count; ++i)
    {
        copyVec2(src, *dst);
        dst++;
        src = (S*)((U8*)src + stride);
    }
}

// copy from src to dst, stride is the number of bytes between each element in src, count is number of elements to copy
template<class S, class T>
void copyVec3(S* src, LLStrider<T> dst, S32 stride, S32 count)
{
    for (S32 i = 0; i < count; ++i)
    {
        copyVec3(src, *dst);
        dst++;
        src = (S*)((U8*)src + stride);
    }
}

// copy from src to dst, stride is the number of bytes between each element in src, count is number of elements to copy
template<class S, class T>
void copyVec4(S* src, LLStrider<T> dst, S32 stride, S32 count)
{
    for (S32 i = 0; i < count; ++i)
    {
        copyVec3(src, *dst);
        dst++;
        src = (S*)((U8*)src + stride);
    }
}

template<class S, class T>
void copyAttributeArray(Asset& asset, const Accessor& accessor, const S* src, LLStrider<T>& dst, S32 byteStride)
{
    if (accessor.mType == TINYGLTF_TYPE_VEC2)
    {
        S32 stride = byteStride == 0 ? sizeof(S) * 2 : byteStride;
        copyVec2((S*)src, dst, stride, accessor.mCount);
    }
    else if (accessor.mType == TINYGLTF_TYPE_VEC3)
    {
        S32 stride = byteStride == 0 ? sizeof(S) * 3 : byteStride;
        copyVec3((S*)src, dst, stride, accessor.mCount);
    }
    else if (accessor.mType == TINYGLTF_TYPE_VEC4)
    {
        S32 stride = byteStride == 0 ? sizeof(S) * 4 : byteStride;
        copyVec4((S*)src, dst, stride, accessor.mCount);
    }
    else
    {
        LL_ERRS("GLTF") << "Unsupported accessor type" << LL_ENDL;
    }
}

template <class T>
void Primitive::copyAttribute(Asset& asset, S32 accessorIdx, LLStrider<T>& dst)
{
    const Accessor& accessor = asset.mAccessors[accessorIdx];
    const BufferView& bufferView = asset.mBufferViews[accessor.mBufferView];
    const Buffer& buffer = asset.mBuffers[bufferView.mBuffer];
    const U8* src = buffer.mData.data() + bufferView.mByteOffset + accessor.mByteOffset;

    if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_FLOAT)
    {
        copyAttributeArray(asset, accessor, (const F32*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT)
    {
        copyAttributeArray(asset, accessor, (const U16*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT)
    {
        copyAttributeArray(asset, accessor, (const U32*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)
    {
        copyAttributeArray(asset, accessor, (const U8*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_SHORT)
    {
        copyAttributeArray(asset, accessor, (const S16*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_BYTE)
    {
        copyAttributeArray(asset, accessor, (const S8*)src, dst, bufferView.mByteStride);
    }
    else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_DOUBLE)
    {
        copyAttributeArray(asset, accessor, (const F64*)src, dst, bufferView.mByteStride);
    }
    else
    {
        LL_ERRS("GLTF") << "Unsupported component type" << LL_ENDL;
    }
}

void Primitive::allocateGLResources(Asset& asset)
{
    // allocate vertex buffer
    // We diverge from the intent of the GLTF format here to work with our existing render pipeline
    // GLTF wants us to copy the buffer views into GPU storage as is and build render commands that source that data.
    // For our engine, though, it's better to rearrange the buffers at load time into a layout that's more consistent.
    // The GLTF native approach undoubtedly works well if you can count on VAOs, but VAOs perform much worse with our scenes.

    // get the number of vertices
    U32 numVertices = 0;
    if (!mAttributes.empty())
    {
        auto it = mAttributes.begin();
        const Accessor& accessor = asset.mAccessors[it->second];
        numVertices = accessor.mCount;
    }

    // get the number of indices
    U32 numIndices = 0;
    if (mIndices != INVALID_INDEX)
    {
        const Accessor& accessor = asset.mAccessors[mIndices];
        numIndices = accessor.mCount;
    }

    // create vertex buffer
    mVertexBuffer = new LLVertexBuffer(ATTRIBUTE_MASK);
    mVertexBuffer->allocateBuffer(numVertices, numIndices);

    bool needs_color = true;
    bool needs_texcoord = true;
    bool needs_normal = true;
    bool needs_tangent = true;

    // load vertex data
    for (auto& it : mAttributes)
    {
        const std::string& attribName = it.first;

        // load vertex data
        if (attribName == "POSITION")
        {
            // load position data
            LLStrider<LLVector4a> dst;
            mVertexBuffer->getVertexStrider(dst);

            copyAttribute(asset, it.second, dst);
        }
        else if (attribName == "NORMAL")
        {
            needs_normal = false;
            // load normal data
            LLStrider<LLVector4a> dst;
            mVertexBuffer->getNormalStrider(dst);

            copyAttribute(asset, it.second, dst);
        }
        else if (attribName == "TANGENT")
        {
            needs_tangent = false;
            // load tangent data

            LLStrider<LLVector4a> dst;
            mVertexBuffer->getTangentStrider(dst);

            copyAttribute(asset, it.second, dst);
        }
        else if (attribName == "COLOR_0")
        {
            needs_color = false;
            // load color data

            LLStrider<LLColor4U> dst;
            mVertexBuffer->getColorStrider(dst);

            copyAttribute(asset, it.second, dst);
        }
        else if (attribName == "TEXCOORD_0")
        {
            needs_texcoord = false;
            // load texcoord data
            LLStrider<LLVector2> dst;
            mVertexBuffer->getTexCoord0Strider(dst);

            LLStrider<LLVector2> tc = dst;
            copyAttribute(asset, it.second, dst);

            // convert to OpenGL coordinate space
            for (U32 i = 0; i < numVertices; ++i)
            {
                tc->mV[1] = 1.0f - tc->mV[1];;
                tc++;
            }
        }
    }

    // copy index buffer
    if (mIndices != INVALID_INDEX)
    {
        const Accessor& accessor = asset.mAccessors[mIndices];
        const BufferView& bufferView = asset.mBufferViews[accessor.mBufferView];
        const Buffer& buffer = asset.mBuffers[bufferView.mBuffer];

        const U8* src = buffer.mData.data() + bufferView.mByteOffset + accessor.mByteOffset;

        LLStrider<U16> dst;
        mVertexBuffer->getIndexStrider(dst);
        mIndexArray.resize(numIndices);

        if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT)
        {
            for (U32 i = 0; i < numIndices; ++i)
            {
                *(dst++) = (U16) * (U32*)src;
                src += sizeof(U32);
            }
        }
        else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT)
        {
            for (U32 i = 0; i < numIndices; ++i)
            {
                *(dst++) = *(U16*)src;
                src += sizeof(U16);
            }
        }
        else if (accessor.mComponentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)
        {
            for (U32 i = 0; i < numIndices; ++i)
            {
                *(dst++) = *(U8*)src;
                src += sizeof(U8);
            }
        }
        else
        {
            LL_ERRS("GLTF") << "Unsupported component type for indices" << LL_ENDL;
        }

        U16* idx = (U16*)mVertexBuffer->getMappedIndices();
        for (U32 i = 0; i < numIndices; ++i)
        {
            mIndexArray[i] = idx[i];
        }
    }

    // fill in default values for missing attributes
    if (needs_color)
    { // set default color
        LLStrider<LLColor4U> dst;
        mVertexBuffer->getColorStrider(dst);
        for (U32 i = 0; i < numVertices; ++i)
        {
            *(dst++) = LLColor4U(255, 255, 255, 255);
        }
    }

    // bake material basecolor into color array
    if (mMaterial != INVALID_INDEX)
    {
        const Material& material = asset.mMaterials[mMaterial];
        LLColor4 baseColor = material.mMaterial->mBaseColor;
        LLStrider<LLColor4U> dst;
        mVertexBuffer->getColorStrider(dst);

        for (U32 i = 0; i < numVertices; ++i)
        {
            LLColor4 col = *dst;
            *dst = LLColor4U(baseColor * col);
            dst++;
        }
    }

    if (needs_texcoord)
    { // set default texcoord
        LLStrider<LLVector2> dst;
        mVertexBuffer->getTexCoord0Strider(dst);
        for (U32 i = 0; i < numVertices; ++i)
        {
            *(dst++) = LLVector2(0.0f, 0.0f);
        }
    }

    if (needs_normal)
    { // set default normal
        LLStrider<LLVector4a> dst;
        mVertexBuffer->getNormalStrider(dst);
        for (U32 i = 0; i < numVertices; ++i)
        {
            *(dst++) = LLVector4a(0.0f, 0.0f, 1.0f, 0.0f);
        }
    }

    if (needs_tangent)
    {  // TODO: generate tangents if needed
        LLStrider<LLVector4a> dst;
        mVertexBuffer->getTangentStrider(dst);
        for (U32 i = 0; i < numVertices; ++i)
        {
            *(dst++) = LLVector4a(1.0f, 0.0f, 0.0f, 1.0f);
        }
    }

    mPositions.resize(numVertices);
    mTexCoords.resize(numVertices);
    mNormals.resize(numVertices);
    mTangents.resize(numVertices);

    LLVector4a* pos = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_VERTEX));
    LLVector2* tc = (LLVector2*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_TEXCOORD0));
    LLVector4a* norm = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_NORMAL));
    LLVector4a* tangent = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_TANGENT));
    for (U32 i = 0; i < numVertices; ++i)
    {
        mPositions[i] = pos[i];
        mTexCoords[i] = tc[i];
        mNormals[i] = norm[i];
        mTangents[i] = tangent[i];
    }
    createOctree();
    
    mVertexBuffer->unmapBuffer();
}

void initOctreeTriangle(LLVolumeTriangle* tri, F32 scaler, S32 i0, S32 i1, S32 i2, const LLVector4a& v0, const LLVector4a& v1, const LLVector4a& v2)
{
    //store pointers to vertex data
    tri->mV[0] = &v0;
    tri->mV[1] = &v1;
    tri->mV[2] = &v2;

    //store indices
    tri->mIndex[0] = i0;
    tri->mIndex[1] = i1;
    tri->mIndex[2] = i2;

    //get minimum point
    LLVector4a min = v0;
    min.setMin(min, v1);
    min.setMin(min, v2);

    //get maximum point
    LLVector4a max = v0;
    max.setMax(max, v1);
    max.setMax(max, v2);

    //compute center
    LLVector4a center;
    center.setAdd(min, max);
    center.mul(0.5f);

    tri->mPositionGroup = center;

    //compute "radius"
    LLVector4a size;
    size.setSub(max, min);

    tri->mRadius = size.getLength3().getF32() * scaler;
}

void Primitive::createOctree()
{
    // create octree
    mOctree = new LLVolumeOctree();

    F32 scaler = 0.25f;

    if (mMode == TINYGLTF_MODE_TRIANGLES)
    {
        const U32 num_triangles = mVertexBuffer->getNumIndices() / 3;
        // Initialize all the triangles we need
        mOctreeTriangles.resize(num_triangles);

        LLVector4a* pos = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_VERTEX));
        U16* indices = (U16*)mVertexBuffer->getMappedIndices();

        for (U32 triangle_index = 0; triangle_index < num_triangles; ++triangle_index)
        { //for each triangle
            const U32 index = triangle_index * 3;
            LLVolumeTriangle* tri = &mOctreeTriangles[triangle_index];
            S32 i0 = indices[index];
            S32 i1 = indices[index + 1];
            S32 i2 = indices[index + 2];

            const LLVector4a& v0 = pos[i0];
            const LLVector4a& v1 = pos[i1];
            const LLVector4a& v2 = pos[i2];
            
            initOctreeTriangle(tri, scaler, i0, i1, i2, v0, v1, v2);
            
            //insert
            mOctree->insert(tri);
        }
    }
    else if (mMode == TINYGLTF_MODE_TRIANGLE_STRIP)
    {
        const U32 num_triangles = mVertexBuffer->getNumIndices() - 2;
        // Initialize all the triangles we need
        mOctreeTriangles.resize(num_triangles);

        LLVector4a* pos = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_VERTEX));
        U16* indices = (U16*)mVertexBuffer->getMappedIndices();

        for (U32 triangle_index = 0; triangle_index < num_triangles; ++triangle_index)
        { //for each triangle
            const U32 index = triangle_index + 2;
            LLVolumeTriangle* tri = &mOctreeTriangles[triangle_index];
            S32 i0 = indices[index];
            S32 i1 = indices[index - 1];
            S32 i2 = indices[index - 2];

            const LLVector4a& v0 = pos[i0];
            const LLVector4a& v1 = pos[i1];
            const LLVector4a& v2 = pos[i2];

            initOctreeTriangle(tri, scaler, i0, i1, i2, v0, v1, v2);

            //insert
            mOctree->insert(tri);
        }
    }
    else if (mMode == TINYGLTF_MODE_TRIANGLE_FAN)
    {
        const U32 num_triangles = mVertexBuffer->getNumIndices() - 2;
        // Initialize all the triangles we need
        mOctreeTriangles.resize(num_triangles);

        LLVector4a* pos = (LLVector4a*)(mVertexBuffer->getMappedData() + mVertexBuffer->getOffset(LLVertexBuffer::TYPE_VERTEX));
        U16* indices = (U16*)mVertexBuffer->getMappedIndices();

        for (U32 triangle_index = 0; triangle_index < num_triangles; ++triangle_index)
        { //for each triangle
            const U32 index = triangle_index + 2;
            LLVolumeTriangle* tri = &mOctreeTriangles[triangle_index];
            S32 i0 = indices[0];
            S32 i1 = indices[index - 1];
            S32 i2 = indices[index - 2];

            const LLVector4a& v0 = pos[i0];
            const LLVector4a& v1 = pos[i1];
            const LLVector4a& v2 = pos[i2];

            initOctreeTriangle(tri, scaler, i0, i1, i2, v0, v1, v2);

            //insert
            mOctree->insert(tri);
        }
    }
    else if (mMode == TINYGLTF_MODE_POINTS ||
            mMode == TINYGLTF_MODE_LINE ||
        mMode == TINYGLTF_MODE_LINE_LOOP ||
        mMode == TINYGLTF_MODE_LINE_STRIP)
    {
        // nothing to do, no volume... maybe add some collision geometry around these primitive types?
    }
    
    else
    {
        LL_ERRS() << "Unsupported Primitive mode" << LL_ENDL;
    }

    //remove unneeded octree layers
    while (!mOctree->balance()) {}

    //calculate AABB for each node
    LLVolumeOctreeRebound rebound;
    rebound.traverse(mOctree);
}

const LLVolumeTriangle* Primitive::lineSegmentIntersect(const LLVector4a& start, const LLVector4a& end,
    LLVector4a* intersection, LLVector2* tex_coord, LLVector4a* normal, LLVector4a* tangent_out)
{
    if (mOctree.isNull())
    {
        return nullptr;
    }

    LLVector4a dir;
    dir.setSub(end, start);

    F32 closest_t = 2.f; // must be larger than 1

    //create a proxy LLVolumeFace for the raycast
    LLVolumeFace face;
    face.mPositions = mPositions.data();
    face.mTexCoords = mTexCoords.data();
    face.mNormals = mNormals.data();
    face.mTangents = mTangents.data();
    face.mIndices = mIndexArray.data();

    face.mNumIndices = mIndexArray.size();
    face.mNumVertices = mPositions.size();

    LLOctreeTriangleRayIntersect intersect(start, dir, &face, &closest_t, intersection, tex_coord, normal, tangent_out);
    intersect.traverse(mOctree);

    // null out proxy data so it doesn't get freed
    face.mPositions = face.mNormals = face.mTangents = nullptr;
    face.mIndices = nullptr;
    face.mTexCoords = nullptr;

    return intersect.mHitTriangle;
}

Primitive::~Primitive()
{
    mOctree = nullptr;
}