-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathllvertexbuffer.cpp
More file actions
1952 lines (1648 loc) · 53.2 KB
/
Copy pathllvertexbuffer.cpp
File metadata and controls
1952 lines (1648 loc) · 53.2 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file llvertexbuffer.cpp
* @brief LLVertexBuffer implementation
*
* $LicenseInfo:firstyear=2003&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, 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 "linden_common.h"
#include "llfasttimer.h"
#include "llsys.h"
#include "llvertexbuffer.h"
// #include "llrender.h"
#include "llglheaders.h"
#include "llrender.h"
#include "llvector4a.h"
#include "llshadermgr.h"
#include "llglslshader.h"
#include "llmemory.h"
#include <glm/gtc/type_ptr.hpp>
//Next Highest Power Of Two
//helper function, returns first number > v that is a power of 2, or v if v is already a power of 2
U32 nhpo2(U32 v)
{
U32 r = 1;
while (r < v) {
r *= 2;
}
return r;
}
//which power of 2 is i?
//assumes i is a power of 2 > 0
U32 wpo2(U32 i)
{
llassert(i > 0);
llassert(nhpo2(i) == i);
U32 r = 0;
while (i >>= 1) ++r;
return r;
}
struct CompareMappedRegion
{
bool operator()(const LLVertexBuffer::MappedRegion& lhs, const LLVertexBuffer::MappedRegion& rhs)
{
return lhs.mStart < rhs.mStart;
}
};
#define ENABLE_GL_WORK_QUEUE 0
#if ENABLE_GL_WORK_QUEUE
#define THREAD_COUNT 1
//============================================================================
// High performance WorkQueue for usage in real-time rendering work
class GLWorkQueue
{
public:
using Work = std::function<void()>;
GLWorkQueue();
void post(const Work& value);
size_t size();
bool done();
// Get the next element from the queue
Work pop();
void runOne();
bool runPending();
void runUntilClose();
void close();
bool isClosed();
void syncGL();
private:
std::mutex mMutex;
std::condition_variable mCondition;
std::queue<Work> mQueue;
bool mClosed = false;
};
GLWorkQueue::GLWorkQueue()
{
}
void GLWorkQueue::syncGL()
{
/*if (mSync)
{
std::lock_guard<std::mutex> lock(mMutex);
glWaitSync(mSync, 0, GL_TIMEOUT_IGNORED);
mSync = 0;
}*/
}
size_t GLWorkQueue::size()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
std::lock_guard<std::mutex> lock(mMutex);
return mQueue.size();
}
bool GLWorkQueue::done()
{
return size() == 0 && isClosed();
}
void GLWorkQueue::post(const GLWorkQueue::Work& value)
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
{
std::lock_guard<std::mutex> lock(mMutex);
mQueue.push(std::move(value));
}
mCondition.notify_one();
}
// Get the next element from the queue
GLWorkQueue::Work GLWorkQueue::pop()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
// Lock the mutex
{
std::unique_lock<std::mutex> lock(mMutex);
// Wait for a new element to become available or for the queue to close
{
mCondition.wait(lock, [=] { return !mQueue.empty() || mClosed; });
}
}
Work ret;
{
std::lock_guard<std::mutex> lock(mMutex);
// Get the next element from the queue
if (mQueue.size() > 0)
{
ret = mQueue.front();
mQueue.pop();
}
else
{
ret = []() {};
}
}
return ret;
}
void GLWorkQueue::runOne()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
Work w = pop();
w();
//mSync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
}
void GLWorkQueue::runUntilClose()
{
while (!isClosed())
{
runOne();
}
}
void GLWorkQueue::close()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
{
std::lock_guard<std::mutex> lock(mMutex);
mClosed = true;
}
mCondition.notify_all();
}
bool GLWorkQueue::isClosed()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_THREAD;
std::lock_guard<std::mutex> lock(mMutex);
return mClosed;
}
#include "llwindow.h"
class LLGLWorkerThread : public LLThread
{
public:
LLGLWorkerThread(const std::string& name, GLWorkQueue* queue, LLWindow* window)
: LLThread(name)
{
mWindow = window;
mContext = mWindow->createSharedContext();
mQueue = queue;
}
void run() override
{
mWindow->makeContextCurrent(mContext);
gGL.init(false);
mQueue->runUntilClose();
gGL.shutdown();
mWindow->destroySharedContext(mContext);
}
GLWorkQueue* mQueue;
LLWindow* mWindow;
void* mContext = nullptr;
};
static LLGLWorkerThread* sVBOThread[THREAD_COUNT];
static GLWorkQueue* sQueue = nullptr;
#endif
//============================================================================
// Pool of reusable VertexBuffer state
// batch calls to glGenBuffers
static GLuint gen_buffer()
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
GLuint ret = 0;
constexpr U32 pool_size = 4096;
thread_local static GLuint sNamePool[pool_size];
thread_local static U32 sIndex = 0;
if (sIndex == 0)
{
LL_PROFILE_ZONE_NAMED_CATEGORY_VERTEX("gen buffer");
sIndex = pool_size;
#if !LL_DARWIN
if (!gGLManager.mIsAMD)
{
glGenBuffers(pool_size, sNamePool);
}
else
#endif
{ // work around for AMD driver bug
for (U32 i = 0; i < pool_size; ++i)
{
glGenBuffers(1, sNamePool + i);
}
}
}
ret = sNamePool[--sIndex];
return ret;
}
static void delete_buffers(S32 count, GLuint* buffers)
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
// wait a few frames before actually deleting the buffers to avoid
// synchronization issues with the GPU
static std::vector<GLuint> sFreeList[4];
if (gGLManager.mInited)
{
U32 idx = LLImageGL::sFrameCount % 4;
for (S32 i = 0; i < count; ++i)
{
sFreeList[idx].push_back(buffers[i]);
}
idx = (LLImageGL::sFrameCount + 3) % 4;
if (!sFreeList[idx].empty())
{
glDeleteBuffers((GLsizei)sFreeList[idx].size(), sFreeList[idx].data());
sFreeList[idx].resize(0);
}
}
}
#define ANALYZE_VBO_POOL 0
// VBO Pool interface
class LLVBOPool
{
public:
virtual ~LLVBOPool() = default;
virtual void allocate(GLenum type, U32 size, GLuint& name, U8*& data) = 0;
virtual void free(GLenum type, U32 size, GLuint name, U8* data) = 0;
virtual U64 getVramBytesUsed() = 0;
};
// VBO Pool for Apple GPUs (as in M1/M2 etc, not Intel macs)
// Effectively disables VBO pooling
class LLAppleVBOPool final: public LLVBOPool
{
public:
U64 mAllocated = 0;
U64 getVramBytesUsed() override
{
return mAllocated;
}
void allocate(GLenum type, U32 size, GLuint& name, U8*& data) override
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
STOP_GLERROR;
llassert(type == GL_ARRAY_BUFFER || type == GL_ELEMENT_ARRAY_BUFFER);
llassert(name == 0); // non zero name indicates a gl name that wasn't freed
llassert(data == nullptr); // non null data indicates a buffer that wasn't freed
llassert(size >= 2); // any buffer size smaller than a single index is nonsensical
mAllocated += size;
{ //allocate a new buffer
LL_PROFILE_GPU_ZONE("vbo alloc");
// ON OS X, we don't allocate a VBO until the last possible moment
// in unmapBuffer
data = (U8*) ll_aligned_malloc_16(size);
STOP_GLERROR;
}
}
void free(GLenum type, U32 size, GLuint name, U8* data) override
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
llassert(type == GL_ARRAY_BUFFER || type == GL_ELEMENT_ARRAY_BUFFER);
llassert(size >= 2);
if (data)
{
ll_aligned_free_16(data);
}
mAllocated -= size;
STOP_GLERROR;
if (name)
{
delete_buffers(1, &name);
}
STOP_GLERROR;
}
};
// VBO Pool for GPUs that benefit from VBO pooling
class LLDefaultVBOPool final : public LLVBOPool
{
public:
typedef std::chrono::steady_clock::time_point Time;
struct Entry
{
U8* mData;
GLuint mGLName;
Time mAge;
};
~LLDefaultVBOPool() override
{
clear();
}
typedef std::unordered_map<U32, std::list<Entry>> Pool;
Pool mVBOPool;
Pool mIBOPool;
U32 mTouchCount = 0;
U64 mDistributed = 0;
U64 mAllocated = 0;
U64 mReserved = 0;
U32 mMisses = 0;
U32 mHits = 0;
U64 getVramBytesUsed() override
{
return mAllocated + mReserved;
}
// increase the size to some common value (e.g. a power of two) to increase hit rate
void adjustSize(U32& size)
{
// size = nhpo2(size); // (193/303)/580 MB (distributed/allocated)/reserved in VBO Pool. Overhead: 66 percent. Hit rate: 77 percent
//(245/276)/385 MB (distributed/allocated)/reserved in VBO Pool. Overhead: 57 percent. Hit rate: 69 percent
//(187/209)/397 MB (distributed/allocated)/reserved in VBO Pool. Overhead: 112 percent. Hit rate: 76 percent
U32 block_size = llmax(nhpo2(size) / 8, (U32) 16);
size += block_size - (size % block_size);
}
void allocate(GLenum type, U32 size, GLuint& name, U8*& data) override
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
llassert(type == GL_ARRAY_BUFFER || type == GL_ELEMENT_ARRAY_BUFFER);
llassert(name == 0); // non zero name indicates a gl name that wasn't freed
llassert(data == nullptr); // non null data indicates a buffer that wasn't freed
llassert(size >= 2); // any buffer size smaller than a single index is nonsensical
mDistributed += size;
adjustSize(size);
mAllocated += size;
auto& pool = type == GL_ELEMENT_ARRAY_BUFFER ? mIBOPool : mVBOPool;
Pool::iterator iter = pool.find(size);
if (iter == pool.end())
{ // cache miss, allocate a new buffer
LL_PROFILE_ZONE_NAMED_CATEGORY_VERTEX("vbo pool miss");
LL_PROFILE_GPU_ZONE("vbo alloc");
mMisses++;
name = gen_buffer();
glBindBuffer(type, name);
glBufferData(type, size, nullptr, GL_DYNAMIC_DRAW);
if (type == GL_ELEMENT_ARRAY_BUFFER)
{
LLVertexBuffer::sGLRenderIndices = name;
}
else
{
LLVertexBuffer::sGLRenderBuffer = name;
}
data = (U8*)ll_aligned_malloc_16(size);
}
else
{
mHits++;
llassert(mReserved >= size); // assert if accounting gets messed up
mReserved -= size;
std::list<Entry>& entries = iter->second;
Entry& entry = entries.back();
name = entry.mGLName;
data = entry.mData;
entries.pop_back();
if (entries.empty())
{
pool.erase(iter);
}
}
clean();
}
void free(GLenum type, U32 size, GLuint name, U8* data) override
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
llassert(type == GL_ARRAY_BUFFER || type == GL_ELEMENT_ARRAY_BUFFER);
llassert(size >= 2);
llassert(name != 0);
llassert(data != nullptr);
clean();
llassert(mDistributed >= size);
mDistributed -= size;
adjustSize(size);
llassert(mAllocated >= size);
mAllocated -= size;
mReserved += size;
auto& pool = type == GL_ELEMENT_ARRAY_BUFFER ? mIBOPool : mVBOPool;
Pool::iterator iter = pool.find(size);
if (iter == pool.end())
{
std::list<Entry> newlist;
newlist.push_front({ data, name, std::chrono::steady_clock::now() });
pool[size] = newlist;
}
else
{
iter->second.push_front({ data, name, std::chrono::steady_clock::now() });
}
}
// clean periodically (clean gets called for every alloc/free)
void clean()
{
mTouchCount++;
if (mTouchCount < 1024) // clean every 1k touches
{
return;
}
mTouchCount = 0;
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
std::unordered_map<U32, std::list<Entry>>* pools[] = { &mVBOPool, &mIBOPool };
using namespace std::chrono_literals;
Time cutoff = std::chrono::steady_clock::now() - 5s;
for (auto* pool : pools)
{
for (Pool::iterator iter = pool->begin(); iter != pool->end(); )
{
auto& entries = iter->second;
while (!entries.empty() && entries.back().mAge < cutoff)
{
LL_PROFILE_ZONE_NAMED_CATEGORY_VERTEX("vbo cache timeout");
auto& entry = entries.back();
ll_aligned_free_16(entry.mData);
delete_buffers(1, &entry.mGLName);
llassert(mReserved >= iter->first);
mReserved -= iter->first;
entries.pop_back();
}
if (entries.empty())
{
iter = pool->erase(iter);
}
else
{
++iter;
}
}
}
#if 0
LL_INFOS() << llformat("(%d/%d)/%d MB (distributed/allocated)/total in VBO Pool. Overhead: %d percent. Hit rate: %d percent",
mDistributed / 1000000,
mAllocated / 1000000,
(mAllocated + mReserved) / 1000000, // total bytes
((mAllocated+mReserved-mDistributed)*100)/llmax(mDistributed, (U64) 1), // overhead percent
(mHits*100)/llmax(mMisses+mHits, (U32)1)) // hit rate percent
<< LL_ENDL;
#endif
}
void clear()
{
for (auto& entries : mIBOPool)
{
for (auto& entry : entries.second)
{
ll_aligned_free_16(entry.mData);
delete_buffers(1, &entry.mGLName);
}
}
for (auto& entries : mVBOPool)
{
for (auto& entry : entries.second)
{
ll_aligned_free_16(entry.mData);
delete_buffers(1, &entry.mGLName);
}
}
mReserved = 0;
mIBOPool.clear();
mVBOPool.clear();
}
};
static LLVBOPool* sVBOPool = nullptr;
void LLVertexBufferData::drawWithMatrix()
{
if (!mVB)
{
llassert(false);
// Not supposed to happen, check buffer generation
return;
}
if (mTexName)
{
gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mTexName);
}
else
{
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
gGL.matrixMode(LLRender::MM_MODELVIEW);
gGL.pushMatrix();
gGL.loadMatrix(glm::value_ptr(mModelView));
gGL.matrixMode(LLRender::MM_PROJECTION);
gGL.pushMatrix();
gGL.loadMatrix(glm::value_ptr(mProjection));
gGL.matrixMode(LLRender::MM_TEXTURE0);
gGL.pushMatrix();
gGL.loadMatrix(glm::value_ptr(mTexture0));
mVB->setBuffer();
mVB->drawArrays(mMode, 0, mCount);
gGL.popMatrix();
gGL.matrixMode(LLRender::MM_PROJECTION);
gGL.popMatrix();
gGL.matrixMode(LLRender::MM_MODELVIEW);
gGL.popMatrix();
}
void LLVertexBufferData::draw()
{
if (!mVB)
{
llassert(false);
// Not supposed to happen, check buffer generation
return;
}
if (mTexName)
{
gGL.getTexUnit(0)->bindManual(LLTexUnit::TT_TEXTURE, mTexName);
}
else
{
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
mVB->setBuffer();
mVB->drawArrays(mMode, 0, mCount);
}
//============================================================================
//static
U64 LLVertexBuffer::getBytesAllocated()
{
return sVBOPool ? sVBOPool->getVramBytesUsed() : 0;
}
//============================================================================
//
//static
U32 LLVertexBuffer::sGLRenderBuffer = 0;
U32 LLVertexBuffer::sGLRenderIndices = 0;
U32 LLVertexBuffer::sLastMask = 0;
U32 LLVertexBuffer::sVertexCount = 0;
// The viewer keeps a single VAO bound. Attribute pointer calls store state in
// that VAO and capture the current array buffer. Track the formats configured
// for sGLRenderBuffer to avoid resubmitting identical state to OpenGL-on-Metal.
// If VAO switching is introduced, invalidate this cache when the VAO changes.
static U32 sVertexAttribsConfigured = 0;
static U32 sColorPointerSource = 0;
static constexpr U32 COLOR_POINTER_COLOR = 1;
static constexpr U32 COLOR_POINTER_EMISSIVE = 2;
//NOTE: each component must be AT LEAST 4 bytes in size to avoid a performance penalty on AMD hardware
const U32 LLVertexBuffer::sTypeSize[LLVertexBuffer::TYPE_MAX] =
{
sizeof(LLVector4), // TYPE_VERTEX,
sizeof(LLVector4), // TYPE_NORMAL,
sizeof(LLVector2), // TYPE_TEXCOORD0,
sizeof(LLVector2), // TYPE_TEXCOORD1,
sizeof(LLVector2), // TYPE_TEXCOORD2,
sizeof(LLVector2), // TYPE_TEXCOORD3,
sizeof(LLColor4U), // TYPE_COLOR,
sizeof(LLColor4U), // TYPE_EMISSIVE, only alpha is used currently
sizeof(LLVector4), // TYPE_TANGENT,
sizeof(F32), // TYPE_WEIGHT,
sizeof(LLVector4), // TYPE_WEIGHT4,
sizeof(LLVector4), // TYPE_CLOTHWEIGHT,
sizeof(U64), // TYPE_JOINT,
sizeof(LLVector4), // TYPE_TEXTURE_INDEX (actually exists as position.w), no extra data, but stride is 16 bytes
};
static const std::string vb_type_name[] =
{
"TYPE_VERTEX",
"TYPE_NORMAL",
"TYPE_TEXCOORD0",
"TYPE_TEXCOORD1",
"TYPE_TEXCOORD2",
"TYPE_TEXCOORD3",
"TYPE_COLOR",
"TYPE_EMISSIVE",
"TYPE_TANGENT",
"TYPE_WEIGHT",
"TYPE_WEIGHT4",
"TYPE_CLOTHWEIGHT",
"TYPE_JOINT"
"TYPE_TEXTURE_INDEX",
"TYPE_MAX",
"TYPE_INDEX",
};
const U32 LLVertexBuffer::sGLMode[LLRender::NUM_MODES] =
{
GL_TRIANGLES,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
GL_LINE_LOOP,
};
//static
void LLVertexBuffer::setupClientArrays(U32 data_mask)
{
if (sLastMask != data_mask)
{
for (U32 i = 0; i < TYPE_MAX; ++i)
{
S32 loc = i;
U32 mask = 1 << i;
if (sLastMask & (1 << i))
{ //was enabled
if (!(data_mask & mask))
{ //needs to be disabled
glDisableVertexAttribArray(loc);
}
}
else
{ //was disabled
if (data_mask & mask)
{ //needs to be enabled
glEnableVertexAttribArray(loc);
}
}
}
}
sLastMask = data_mask;
}
//static
void LLVertexBuffer::drawArrays(U32 mode, const std::vector<LLVector3>& pos)
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
gGL.begin(mode);
for (auto& v : pos)
{
gGL.vertex3fv(v.mV);
}
gGL.end();
gGL.flush();
}
//static
void LLVertexBuffer::drawElements(U32 mode, const LLVector4a* pos, const LLVector2* tc, U32 num_indices, const U16* indicesp)
{
LL_PROFILE_ZONE_SCOPED_CATEGORY_VERTEX;
llassert(LLGLSLShader::sCurBoundShaderPtr != NULL);
STOP_GLERROR;
gGL.syncMatrices();
unbind();
gGL.begin(mode);
if (tc != nullptr)
{
for (U32 i = 0; i < num_indices; ++i)
{
U16 idx = indicesp[i];
gGL.texCoord2fv(tc[idx].mV);
gGL.vertex3fv(pos[idx].getF32ptr());
}
}
else
{
for (U32 i = 0; i < num_indices; ++i)
{
U16 idx = indicesp[i];
gGL.vertex3fv(pos[idx].getF32ptr());
}
}
gGL.end();
gGL.flush();
}
bool LLVertexBuffer::validateRange(U32 start, U32 end, U32 count, U32 indices_offset) const
{
if (!gDebugGL)
{
return true;
}
llassert(start < mNumVerts);
llassert(end < mNumVerts);
if (start >= mNumVerts ||
end >= mNumVerts)
{
LL_ERRS() << "Bad vertex buffer draw range: [" << start << ", " << end << "] vs " << mNumVerts << LL_ENDL;
}
if (indices_offset >= mNumIndices ||
indices_offset + count > mNumIndices)
{
LL_ERRS() << "Bad index buffer draw range: [" << indices_offset << ", " << indices_offset+count << "]" << LL_ENDL;
}
{
#if 0 // not a reliable test for VBOs that are not backed by a CPU buffer
U16* idx = (U16*) mMappedIndexData+indices_offset;
for (U32 i = 0; i < count; ++i)
{
llassert(idx[i] >= start);
llassert(idx[i] <= end);
if (idx[i] < start || idx[i] > end)
{
LL_ERRS() << "Index out of range: " << idx[i] << " not in [" << start << ", " << end << "]" << LL_ENDL;
}
}
LLVector4a* v = (LLVector4a*)mMappedData;
for (U32 i = start; i <= end; ++i)
{
if (!v[i].isFinite3())
{
LL_ERRS() << "Non-finite vertex position data detected." << LL_ENDL;
}
}
LLGLSLShader* shader = LLGLSLShader::sCurBoundShaderPtr;
if (shader && shader->mFeatures.mIndexedTextureChannels > 1)
{
LLVector4a* v = (LLVector4a*) mMappedData;
for (U32 i = start; i < end; i++)
{
U32 idx = (U32) (v[i][3]+0.25f);
if (idx >= (U32)shader->mFeatures.mIndexedTextureChannels)
{
LL_ERRS() << "Bad texture index found in vertex data stream." << LL_ENDL;
}
}
}
#endif
}
return true;
}
#if LL_PROFILER_ENABLE_RENDER_DOC
void LLVertexBuffer::setLabel(const char* label) {
LL_LABEL_OBJECT_GL(GL_BUFFER, mGLBuffer, strlen(label), label);
}
#endif
void LLVertexBuffer::clone(LLVertexBuffer& target) const
{
target.mTypeMask = mTypeMask;
target.mIndicesType = mIndicesType;
target.mIndicesStride = mIndicesStride;
if (target.getNumVerts() != getNumVerts() ||
target.getNumIndices() != getNumIndices())
{
target.allocateBuffer(getNumVerts(), getNumIndices());
}
}
void LLVertexBuffer::drawRange(U32 mode, U32 start, U32 end, U32 count, U32 indices_offset) const
{
llassert(validateRange(start, end, count, indices_offset));
llassert(mGLBuffer == sGLRenderBuffer);
llassert(mGLIndices == sGLRenderIndices);
gGL.syncMatrices();
STOP_GLERROR;
glDrawRangeElements(sGLMode[mode], start, end, count, mIndicesType,
(GLvoid*) (indices_offset * (size_t) mIndicesStride));
STOP_GLERROR;
}
void LLVertexBuffer::drawRangeFast(U32 mode, U32 start, U32 end, U32 count, U32 indices_offset) const
{
glDrawRangeElements(sGLMode[mode], start, end, count, mIndicesType,
(GLvoid*)(indices_offset * (size_t)mIndicesStride));
}
void LLVertexBuffer::draw(U32 mode, U32 count, U32 indices_offset) const
{
drawRange(mode, 0, mNumVerts-1, count, indices_offset);
}
void LLVertexBuffer::drawArrays(U32 mode, U32 first, U32 count) const
{
llassert(first + count <= mNumVerts);
llassert(mGLBuffer == sGLRenderBuffer);
llassert(mGLIndices == sGLRenderIndices);
gGL.syncMatrices();
STOP_GLERROR;
glDrawArrays(sGLMode[mode], first, count);
STOP_GLERROR;
}
//static
void LLVertexBuffer::initClass(LLWindow* window)
{
llassert(sVBOPool == nullptr);
#if LL_DARWIN || LL_ARM64
if (gGLManager.mIsApple)
{
LL_INFOS() << "VBO Pooling Disabled" << LL_ENDL;
sVBOPool = new LLAppleVBOPool();
}
else
#endif
{
LL_INFOS() << "VBO Pooling Enabled" << LL_ENDL;
sVBOPool = new LLDefaultVBOPool();
}
#if ENABLE_GL_WORK_QUEUE
sQueue = new GLWorkQueue();
for (int i = 0; i < THREAD_COUNT; ++i)
{
sVBOThread[i] = new LLGLWorkerThread("VBO Worker", sQueue, window);
sVBOThread[i]->start();
}
#endif
}
//static
void LLVertexBuffer::unbind()
{
STOP_GLERROR;
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
STOP_GLERROR;
sGLRenderBuffer = 0;
sGLRenderIndices = 0;
sVertexAttribsConfigured = 0;
sColorPointerSource = 0;
}
//static
void LLVertexBuffer::cleanupClass()
{
unbind();
delete sVBOPool;
sVBOPool = nullptr;
#if ENABLE_GL_WORK_QUEUE
sQueue->close();
for (int i = 0; i < THREAD_COUNT; ++i)
{
sVBOThread[i]->shutdown();