-
Notifications
You must be signed in to change notification settings - Fork 2k
/
bgfx.cpp
5917 lines (4969 loc) · 169 KB
/
bgfx.cpp
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
/*
* Copyright 2011-2024 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
*/
#include <bx/platform.h>
#include "bgfx_p.h"
#include <bgfx/embedded_shader.h>
#include <bx/file.h>
#include <bx/mutex.h>
#include "topology.h"
#if BX_PLATFORM_OSX || BX_PLATFORM_IOS || BX_PLATFORM_VISIONOS
# include <objc/message.h>
#elif BX_PLATFORM_WINDOWS
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif // WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif // BX_PLATFORM_OSX
BX_ERROR_RESULT(BGFX_ERROR_TEXTURE_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 1) );
BX_ERROR_RESULT(BGFX_ERROR_FRAME_BUFFER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 2) );
BX_ERROR_RESULT(BGFX_ERROR_IDENTIFIER_VALIDATION, BX_MAKEFOURCC('b', 'g', 0, 3) );
namespace bgfx
{
#define BGFX_API_THREAD_MAGIC UINT32_C(0x78666762)
#if BGFX_CONFIG_MULTITHREADED
# define BGFX_CHECK_API_THREAD() \
BX_ASSERT(NULL != s_ctx, "Library is not initialized yet."); \
BX_ASSERT(BGFX_API_THREAD_MAGIC == s_threadIndex, "Must be called from main thread.")
# define BGFX_CHECK_RENDER_THREAD() \
BX_ASSERT( (NULL != s_ctx && s_ctx->m_singleThreaded) \
|| ~BGFX_API_THREAD_MAGIC == s_threadIndex \
, "Must be called from render thread." \
)
#else
# define BGFX_CHECK_API_THREAD()
# define BGFX_CHECK_RENDER_THREAD()
#endif // BGFX_CONFIG_MULTITHREADED
#define BGFX_CHECK_CAPS(_caps, _msg) \
BX_ASSERT(0 != (g_caps.supported & (_caps) ) \
, _msg " Use bgfx::getCaps to check " #_caps " backend renderer capabilities." \
);
#if BGFX_CONFIG_USE_TINYSTL
void* TinyStlAllocator::static_allocate(size_t _bytes)
{
return bx::alloc(g_allocator, _bytes);
}
void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
{
if (NULL != _ptr)
{
bx::free(g_allocator, _ptr);
}
}
#endif // BGFX_CONFIG_USE_TINYSTL
struct CallbackStub : public CallbackI
{
virtual ~CallbackStub()
{
}
virtual void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _str) override
{
bgfx::trace(_filePath, _line, "BGFX FATAL 0x%08x: %s\n", _code, _str);
if (Fatal::DebugCheck == _code)
{
bx::debugBreak();
}
else
{
abort();
}
}
virtual void traceVargs(const char* _filePath, uint16_t _line, const char* _format, va_list _argList) override
{
char temp[2048];
char* out = temp;
va_list argListCopy;
va_copy(argListCopy, _argList);
int32_t len = bx::snprintf(out, sizeof(temp), "%s (%d): ", _filePath, _line);
int32_t total = len + bx::vsnprintf(out + len, sizeof(temp)-len, _format, argListCopy);
va_end(argListCopy);
if ( (int32_t)sizeof(temp) < total)
{
out = (char*)alloca(total+1);
bx::memCopy(out, temp, len);
bx::vsnprintf(out + len, total-len, _format, _argList);
}
out[total] = '\0';
bx::debugOutput(out);
}
virtual void profilerBegin(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
{
}
virtual void profilerBeginLiteral(const char* /*_name*/, uint32_t /*_abgr*/, const char* /*_filePath*/, uint16_t /*_line*/) override
{
}
virtual void profilerEnd() override
{
}
virtual uint32_t cacheReadSize(uint64_t /*_id*/) override
{
return 0;
}
virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/) override
{
return false;
}
virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/) override
{
}
virtual void screenShot(const char* _filePath, uint32_t _width, uint32_t _height, uint32_t _pitch, const void* _data, uint32_t _size, bool _yflip) override
{
BX_UNUSED(_filePath, _width, _height, _pitch, _data, _size, _yflip);
const int32_t len = bx::strLen(_filePath)+5;
char* filePath = (char*)alloca(len);
bx::strCopy(filePath, len, _filePath);
bx::strCat(filePath, len, ".tga");
bx::FileWriter writer;
if (bx::open(&writer, filePath) )
{
bimg::imageWriteTga(&writer, _width, _height, _pitch, _data, false, _yflip);
bx::close(&writer);
}
}
virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, TextureFormat::Enum /*_format*/, bool /*_yflip*/) override
{
BX_TRACE("Warning: using capture without callback (a.k.a. pointless).");
}
virtual void captureEnd() override
{
}
virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/) override
{
}
};
#ifndef BGFX_CONFIG_MEMORY_TRACKING
# define BGFX_CONFIG_MEMORY_TRACKING (BGFX_CONFIG_DEBUG && BX_CONFIG_SUPPORTS_THREADING)
#endif // BGFX_CONFIG_MEMORY_TRACKING
const size_t kNaturalAlignment = 8;
class AllocatorStub : public bx::AllocatorI
{
public:
AllocatorStub()
#if BGFX_CONFIG_MEMORY_TRACKING
: m_numBlocks(0)
, m_maxBlocks(0)
#endif // BGFX_CONFIG_MEMORY_TRACKING
{
}
virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* _file, uint32_t _line) override
{
if (0 == _size)
{
if (NULL != _ptr)
{
if (kNaturalAlignment >= _align)
{
#if BGFX_CONFIG_MEMORY_TRACKING
{
bx::MutexScope scope(m_mutex);
BX_ASSERT(m_numBlocks > 0, "Number of blocks is 0. Possible alloc/free mismatch?");
--m_numBlocks;
}
#endif // BGFX_CONFIG_MEMORY_TRACKING
::free(_ptr);
}
else
{
bx::alignedFree(this, _ptr, _align, bx::Location(_file, _line) );
}
}
return NULL;
}
else if (NULL == _ptr)
{
if (kNaturalAlignment >= _align)
{
#if BGFX_CONFIG_MEMORY_TRACKING
{
bx::MutexScope scope(m_mutex);
++m_numBlocks;
m_maxBlocks = bx::max(m_maxBlocks, m_numBlocks);
}
#endif // BGFX_CONFIG_MEMORY_TRACKING
return ::malloc(_size);
}
return bx::alignedAlloc(this, _size, _align, bx::Location(_file, _line) );
}
if (kNaturalAlignment >= _align)
{
return ::realloc(_ptr, _size);
}
return bx::alignedRealloc(this, _ptr, _size, _align, bx::Location(_file, _line) );
}
void checkLeaks();
protected:
#if BGFX_CONFIG_MEMORY_TRACKING
bx::Mutex m_mutex;
uint32_t m_numBlocks;
uint32_t m_maxBlocks;
#endif // BGFX_CONFIG_MEMORY_TRACKING
};
static CallbackStub* s_callbackStub = NULL;
static AllocatorStub* s_allocatorStub = NULL;
static bool s_graphicsDebuggerPresent = false;
CallbackI* g_callback = NULL;
bx::AllocatorI* g_allocator = NULL;
Caps g_caps;
#if BGFX_CONFIG_MULTITHREADED && !defined(BX_THREAD_LOCAL)
class ThreadData
{
BX_CLASS(ThreadData
, NO_DEFAULT_CTOR
, NO_COPY
);
public:
ThreadData(uintptr_t _rhs)
{
union { uintptr_t ui; void* ptr; } cast = { _rhs };
m_tls.set(cast.ptr);
}
operator uintptr_t() const
{
union { uintptr_t ui; void* ptr; } cast;
cast.ptr = m_tls.get();
return cast.ui;
}
uintptr_t operator=(uintptr_t _rhs)
{
union { uintptr_t ui; void* ptr; } cast = { _rhs };
m_tls.set(cast.ptr);
return _rhs;
}
bool operator==(uintptr_t _rhs) const
{
uintptr_t lhs = *this;
return lhs == _rhs;
}
private:
bx::TlsData m_tls;
};
static ThreadData s_threadIndex(0);
#elif !BGFX_CONFIG_MULTITHREADED
static uint32_t s_threadIndex(0);
#else
static BX_THREAD_LOCAL uint32_t s_threadIndex(0);
#endif
static Context* s_ctx = NULL;
static bool s_renderFrameCalled = false;
InternalData g_internalData;
PlatformData g_platformData;
bool g_platformDataChangedSinceReset = false;
static Handle::TypeName s_typeName[] =
{
{ "DIB", "DynamicIndexBuffer" },
{ "DVB", "DynamicVertexBuffer" },
{ "FB", "FrameBuffer" },
{ "IB", "IndexBuffer" },
{ "IndB", "IndirectBuffer" },
{ "OQ", "OcclusionQuery" },
{ "P", "Program" },
{ "S", "Shader" },
{ "T", "Texture" },
{ "U", "Uniform" },
{ "VB", "VertexBuffer" },
{ "VL", "VertexLayout" },
{ "?", "?" },
};
BX_STATIC_ASSERT(BX_COUNTOF(s_typeName) == Handle::Count+1, "");
const Handle::TypeName& Handle::getTypeName(Handle::Enum _enum)
{
BX_ASSERT(_enum < Handle::Count, "Invalid Handle::Enum %d!", _enum);
return s_typeName[bx::min(_enum, Handle::Count)];
}
void AllocatorStub::checkLeaks()
{
#if BGFX_CONFIG_MEMORY_TRACKING
// BK - CallbackStub will be deleted after printing this info, so there is always one
// leak if CallbackStub is used.
BX_WARN(uint32_t(NULL != s_callbackStub ? 1 : 0) == m_numBlocks
, "\n\n"
"\n########################################################"
"\n"
"\nMEMORY LEAK: Number of leaked blocks %d (Max blocks: %d)"
"\n"
"\n########################################################"
"\n\n"
, m_numBlocks
, m_maxBlocks
);
#endif // BGFX_CONFIG_MEMORY_TRACKING
}
void setPlatformData(const PlatformData& _data)
{
if (NULL != s_ctx)
{
BGFX_FATAL(true
&& g_platformData.ndt == _data.ndt
&& g_platformData.context == _data.context
, Fatal::UnableToInitialize
, "Only backbuffer pointer and native window handle can be changed after initialization!"
);
}
bx::memCopy(&g_platformData, &_data, sizeof(PlatformData) );
g_platformDataChangedSinceReset = true;
}
const InternalData* getInternalData()
{
return &g_internalData;
}
uintptr_t overrideInternal(TextureHandle _handle, uintptr_t _ptr)
{
BGFX_CHECK_RENDER_THREAD();
RendererContextI* rci = s_ctx->m_renderCtx;
if (0 == rci->getInternal(_handle) )
{
return 0;
}
rci->overrideInternal(_handle, _ptr);
return rci->getInternal(_handle);
}
uintptr_t overrideInternal(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips, TextureFormat::Enum _format, uint64_t _flags)
{
BGFX_CHECK_RENDER_THREAD();
RendererContextI* rci = s_ctx->m_renderCtx;
if (0 == rci->getInternal(_handle) )
{
return 0;
}
uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
Memory* mem = const_cast<Memory*>(alloc(size) );
bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
bx::write(&writer, magic, bx::ErrorAssert{});
TextureCreate tc;
tc.m_width = _width;
tc.m_height = _height;
tc.m_depth = 0;
tc.m_numLayers = 1;
tc.m_numMips = bx::max<uint8_t>(1, _numMips);
tc.m_format = _format;
tc.m_cubeMap = false;
tc.m_mem = NULL;
bx::write(&writer, tc, bx::ErrorAssert{});
rci->destroyTexture(_handle);
rci->createTexture(_handle, mem, _flags, 0);
release(mem);
return rci->getInternal(_handle);
}
void setGraphicsDebuggerPresent(bool _present)
{
BX_TRACE("Graphics debugger is %spresent.", _present ? "" : "not ");
s_graphicsDebuggerPresent = _present;
}
bool isGraphicsDebuggerPresent()
{
return s_graphicsDebuggerPresent;
}
void fatal(const char* _filePath, uint16_t _line, Fatal::Enum _code, const char* _format, ...)
{
va_list argList;
va_start(argList, _format);
char temp[8192];
char* out = temp;
int32_t len = bx::vsnprintf(out, sizeof(temp), _format, argList);
if ( (int32_t)sizeof(temp) < len)
{
out = (char*)alloca(len+1);
len = bx::vsnprintf(out, len, _format, argList);
}
out[len] = '\0';
if (BX_UNLIKELY(NULL == g_callback) )
{
bx::debugPrintf("%s(%d): BGFX FATAL 0x%08x: %s", _filePath, _line, _code, out);
abort();
}
else
{
g_callback->fatal(_filePath, _line, _code, out);
}
va_end(argList);
}
void trace(const char* _filePath, uint16_t _line, const char* _format, ...)
{
va_list argList;
va_start(argList, _format);
if (BX_UNLIKELY(NULL == g_callback) )
{
bx::debugPrintfVargs(_format, argList);
}
else
{
g_callback->traceVargs(_filePath, _line, _format, argList);
}
va_end(argList);
}
#include "vs_debugfont.bin.h"
#include "fs_debugfont.bin.h"
#include "vs_clear.bin.h"
#include "fs_clear0.bin.h"
#include "fs_clear1.bin.h"
#include "fs_clear2.bin.h"
#include "fs_clear3.bin.h"
#include "fs_clear4.bin.h"
#include "fs_clear5.bin.h"
#include "fs_clear6.bin.h"
#include "fs_clear7.bin.h"
static const EmbeddedShader s_embeddedShaders[] =
{
BGFX_EMBEDDED_SHADER(vs_debugfont),
BGFX_EMBEDDED_SHADER(fs_debugfont),
BGFX_EMBEDDED_SHADER(vs_clear),
BGFX_EMBEDDED_SHADER(fs_clear0),
BGFX_EMBEDDED_SHADER(fs_clear1),
BGFX_EMBEDDED_SHADER(fs_clear2),
BGFX_EMBEDDED_SHADER(fs_clear3),
BGFX_EMBEDDED_SHADER(fs_clear4),
BGFX_EMBEDDED_SHADER(fs_clear5),
BGFX_EMBEDDED_SHADER(fs_clear6),
BGFX_EMBEDDED_SHADER(fs_clear7),
BGFX_EMBEDDED_SHADER_END()
};
ShaderHandle createEmbeddedShader(const EmbeddedShader* _es, RendererType::Enum _type, const char* _name)
{
for (const EmbeddedShader* es = _es; NULL != es->name; ++es)
{
if (0 == bx::strCmp(_name, es->name) )
{
for (const EmbeddedShader::Data* esd = es->data; RendererType::Count != esd->type; ++esd)
{
if (_type == esd->type
&& 1 < esd->size)
{
ShaderHandle handle = createShader(makeRef(esd->data, esd->size) );
if (isValid(handle) )
{
setName(handle, _name);
}
return handle;
}
}
}
}
ShaderHandle handle = BGFX_INVALID_HANDLE;
return handle;
}
void dump(const VertexLayout& _layout)
{
if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
{
BX_TRACE("VertexLayout %08x (%08x), stride %d"
, _layout.m_hash
, bx::hash<bx::HashMurmur2A>(_layout.m_attributes)
, _layout.m_stride
);
for (uint32_t attr = 0; attr < Attrib::Count; ++attr)
{
if (UINT16_MAX != _layout.m_attributes[attr])
{
uint8_t num;
AttribType::Enum type;
bool normalized;
bool asInt;
_layout.decode(Attrib::Enum(attr), num, type, normalized, asInt);
BX_TRACE("\tattr %2d: %-20s num %d, type %d, norm [%c], asint [%c], offset %2d"
, attr
, getAttribName(Attrib::Enum(attr) )
, num
, type
, normalized ? 'x' : ' '
, asInt ? 'x' : ' '
, _layout.m_offset[attr]
);
}
}
}
}
#include "charset.h"
void charsetFillTexture(const uint8_t* _charset, uint8_t* _rgba, uint32_t _height, uint32_t _pitch, uint32_t _bpp)
{
for (uint32_t ii = 0; ii < 256; ++ii)
{
uint8_t* pix = &_rgba[ii*8*_bpp];
for (uint32_t yy = 0; yy < _height; ++yy)
{
for (uint32_t xx = 0; xx < 8; ++xx)
{
uint8_t bit = 1<<(7-xx);
bx::memSet(&pix[xx*_bpp], _charset[ii*_height+yy]&bit ? 255 : 0, _bpp);
}
pix += _pitch;
}
}
}
static uint8_t parseAttrTo(char*& _ptr, char _to, uint8_t _default)
{
const bx::StringView str = bx::strFind(_ptr, _to);
if (!str.isEmpty()
&& 3 > str.getPtr()-_ptr)
{
char tmp[4];
int32_t len = int32_t(str.getPtr()-_ptr);
bx::strCopy(tmp, sizeof(tmp), _ptr, len);
uint32_t attr;
bx::fromString(&attr, tmp);
_ptr += len+1;
return uint8_t(attr);
}
return _default;
}
static uint8_t parseAttr(char*& _ptr, uint8_t _default)
{
char* ptr = _ptr;
if (*ptr++ != '[')
{
return _default;
}
if (0 == bx::strCmp(ptr, "0m", 2) )
{
_ptr = ptr + 2;
return _default;
}
uint8_t fg = parseAttrTo(ptr, ';', _default & 0xf);
uint8_t bg = parseAttrTo(ptr, 'm', _default >> 4);
uint8_t attr = (bg<<4) | fg;
_ptr = ptr;
return attr;
}
void TextVideoMem::printfVargs(uint16_t _x, uint16_t _y, uint8_t _attr, const char* _format, va_list _argList)
{
if (_x < m_width && _y < m_height)
{
va_list argListCopy;
va_copy(argListCopy, _argList);
uint32_t num = bx::vsnprintf(NULL, 0, _format, argListCopy) + 1;
char* temp = (char*)alloca(num);
va_copy(argListCopy, _argList);
num = bx::vsnprintf(temp, num, _format, argListCopy);
uint8_t attr = _attr;
MemSlot* mem = &m_mem[_y*m_width+_x];
for (uint32_t ii = 0, xx = _x; ii < num && xx < m_width; ++ii)
{
char ch = temp[ii];
if (BX_UNLIKELY(ch == '\x1b') )
{
char* ptr = &temp[ii+1];
attr = parseAttr(ptr, _attr);
ii += uint32_t(ptr - &temp[ii+1]);
}
else
{
mem->character = ch;
mem->attribute = attr;
++mem;
++xx;
}
}
}
}
static const uint32_t numCharsPerBatch = 1024;
static const uint32_t numBatchVertices = numCharsPerBatch*4;
static const uint32_t numBatchIndices = numCharsPerBatch*6;
void TextVideoMemBlitter::init(uint8_t scale)
{
BGFX_CHECK_API_THREAD();
m_layout
.begin()
.add(Attrib::Position, 3, AttribType::Float)
.add(Attrib::Color0, 4, AttribType::Uint8, true)
.add(Attrib::Color1, 4, AttribType::Uint8, true)
.add(Attrib::TexCoord0, 2, AttribType::Float)
.end();
uint16_t width = 2048;
uint16_t height = 24;
uint8_t bpp = 1;
uint32_t pitch = width*bpp;
const Memory* mem;
mem = alloc(pitch*height);
uint8_t* rgba = mem->data;
charsetFillTexture(vga8x8, rgba, 8, pitch, bpp);
charsetFillTexture(vga8x16, &rgba[8*pitch], 16, pitch, bpp);
m_texture = createTexture2D(width, height, false, 1, TextureFormat::R8
, BGFX_SAMPLER_MIN_POINT
| BGFX_SAMPLER_MAG_POINT
| BGFX_SAMPLER_MIP_POINT
| BGFX_SAMPLER_U_CLAMP
| BGFX_SAMPLER_V_CLAMP
, mem
);
ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_debugfont");
ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "fs_debugfont");
BX_ASSERT(isValid(vsh) && isValid(fsh), "Failed to create embedded blit shaders");
m_program = createProgram(vsh, fsh, true);
m_vb = s_ctx->createTransientVertexBuffer(numBatchVertices*m_layout.m_stride, &m_layout);
m_ib = s_ctx->createTransientIndexBuffer(numBatchIndices*2);
m_scale = bx::max<uint8_t>(scale, 1);
}
void TextVideoMemBlitter::shutdown()
{
BGFX_CHECK_API_THREAD();
if (isValid(m_program) )
{
destroy(m_program);
}
destroy(m_texture);
s_ctx->destroyTransientVertexBuffer(m_vb);
s_ctx->destroyTransientIndexBuffer(m_ib);
}
static const uint32_t s_paletteSrgb[] =
{
0x0, // Black
0xffa46534, // Blue
0xff069a4e, // Green
0xff9a9806, // Cyan
0xff0000cc, // Red
0xff7b5075, // Magenta
0xff00a0c4, // Brown
0xffcfd7d3, // Light Gray
0xff535755, // Dark Gray
0xffcf9f72, // Light Blue
0xff34e28a, // Light Green
0xffe2e234, // Light Cyan
0xff2929ef, // Light Red
0xffa87fad, // Light Magenta
0xff4fe9fc, // Yellow
0xffeceeee, // White
};
BX_STATIC_ASSERT(BX_COUNTOF(s_paletteSrgb) == 16);
static const uint32_t s_paletteLinear[] =
{
0x0, // Black
0xff5e2108, // Blue
0xff005213, // Green
0xff525000, // Cyan
0xff000099, // Red
0xff32142d, // Magenta
0xff00598c, // Brown
0xff9fada6, // Light Gray
0xff161817, // Dark Gray
0xff9f582a, // Light Blue
0xff08c140, // Light Green
0xffc1c108, // Light Cyan
0xff0505dc, // Light Red
0xff63366a, // Light Magenta
0xff13cff8, // Yellow
0xffd5dada // White
};
BX_STATIC_ASSERT(BX_COUNTOF(s_paletteLinear) == 16);
void blit(RendererContextI* _renderCtx, TextVideoMemBlitter& _blitter, const TextVideoMem& _mem)
{
struct Vertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_fg;
uint32_t m_bg;
float m_u;
float m_v;
};
uint32_t yy = 0;
uint32_t xx = 0;
const float texelWidth = 1.0f/2048.0f;
const float texelHeight = 1.0f/24.0f;
const float utop = (_mem.m_small ? 0.0f : 8.0f)*texelHeight;
const float ubottom = (_mem.m_small ? 8.0f : 24.0f)*texelHeight;
const float fontHeight = (_mem.m_small ? 8.0f : 16.0f)*_blitter.m_scale;
const float fontWidth = 8.0f * _blitter.m_scale;
_renderCtx->blitSetup(_blitter);
const uint32_t* palette = 0 != (s_ctx->m_init.resolution.reset & BGFX_RESET_SRGB_BACKBUFFER)
? s_paletteLinear
: s_paletteSrgb
;
for (;yy < _mem.m_height;)
{
Vertex* vertex = (Vertex*)_blitter.m_vb->data;
uint16_t* indices = (uint16_t*)_blitter.m_ib->data;
uint32_t startVertex = 0;
uint32_t numIndices = 0;
for (; yy < _mem.m_height && numIndices < numBatchIndices; ++yy)
{
xx = xx < _mem.m_width ? xx : 0;
const TextVideoMem::MemSlot* line = &_mem.m_mem[yy*_mem.m_width+xx];
for (; xx < _mem.m_width && numIndices < numBatchIndices; ++xx)
{
uint32_t ch = line->character;
const uint8_t attr = line->attribute;
if (ch > 0xff)
{
ch = 0;
}
if (0 != (ch|attr)
&& (' ' != ch || 0 != (attr&0xf0) ) )
{
const uint32_t fg = palette[attr&0xf];
const uint32_t bg = palette[(attr>>4)&0xf];
Vertex vert[4] =
{
{ (xx )*fontWidth, (yy )*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth, utop },
{ (xx+1)*fontWidth, (yy )*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth, utop },
{ (xx+1)*fontWidth, (yy+1)*fontHeight, 0.0f, fg, bg, (ch+1)*8.0f*texelWidth, ubottom },
{ (xx )*fontWidth, (yy+1)*fontHeight, 0.0f, fg, bg, (ch )*8.0f*texelWidth, ubottom },
};
bx::memCopy(vertex, vert, sizeof(vert) );
vertex += 4;
indices[0] = uint16_t(startVertex+0);
indices[1] = uint16_t(startVertex+1);
indices[2] = uint16_t(startVertex+2);
indices[3] = uint16_t(startVertex+2);
indices[4] = uint16_t(startVertex+3);
indices[5] = uint16_t(startVertex+0);
startVertex += 4;
indices += 6;
numIndices += 6;
}
line++;
}
if (numIndices >= numBatchIndices)
{
break;
}
}
_renderCtx->blitRender(_blitter, numIndices);
}
}
void ClearQuad::init()
{
BGFX_CHECK_API_THREAD();
if (RendererType::Noop != g_caps.rendererType)
{
m_layout
.begin()
.add(Attrib::Position, 2, AttribType::Float)
.end();
ShaderHandle vsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, "vs_clear");
BX_ASSERT(isValid(vsh), "Failed to create clear quad embedded vertex shader \"vs_clear\"");
for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
{
char name[32];
bx::snprintf(name, BX_COUNTOF(name), "fs_clear%d", ii);
ShaderHandle fsh = createEmbeddedShader(s_embeddedShaders, g_caps.rendererType, name);
BX_ASSERT(isValid(fsh), "Failed to create clear quad embedded fragment shader \"%s\"", name);
m_program[ii] = createProgram(vsh, fsh);
BX_ASSERT(isValid(m_program[ii]), "Failed to create clear quad program.");
destroy(fsh);
}
destroy(vsh);
struct Vertex
{
float m_x;
float m_y;
};
const uint16_t stride = m_layout.m_stride;
const bgfx::Memory* mem = bgfx::alloc(4 * stride);
Vertex* vertex = (Vertex*)mem->data;
BX_ASSERT(stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", stride, sizeof(Vertex));
vertex->m_x = -1.0f;
vertex->m_y = -1.0f;
vertex++;
vertex->m_x = 1.0f;
vertex->m_y = -1.0f;
vertex++;
vertex->m_x = -1.0f;
vertex->m_y = 1.0f;
vertex++;
vertex->m_x = 1.0f;
vertex->m_y = 1.0f;
m_vb = s_ctx->createVertexBuffer(mem, m_layout, 0);
}
}
void ClearQuad::shutdown()
{
BGFX_CHECK_API_THREAD();
if (RendererType::Noop != g_caps.rendererType)
{
for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
{
if (isValid(m_program[ii]) )
{
destroy(m_program[ii]);
m_program[ii].idx = kInvalidHandle;
}
}
s_ctx->destroyVertexBuffer(m_vb);
}
}
const char* s_uniformTypeName[] =
{
"sampler1",
NULL,
"vec4",
"mat3",
"mat4",
};
BX_STATIC_ASSERT(UniformType::Count == BX_COUNTOF(s_uniformTypeName) );
const char* getUniformTypeName(UniformType::Enum _enum)
{
BX_ASSERT(_enum < UniformType::Count, "%d < UniformType::Count %d", _enum, UniformType::Count);
return s_uniformTypeName[_enum];
}
UniformType::Enum nameToUniformTypeEnum(const char* _name)
{
for (uint32_t ii = 0; ii < UniformType::Count; ++ii)
{
if (NULL != s_uniformTypeName[ii]
&& 0 == bx::strCmp(_name, s_uniformTypeName[ii]) )
{
return UniformType::Enum(ii);
}
}
return UniformType::Count;
}
static const char* s_predefinedName[PredefinedUniform::Count] =
{
"u_viewRect",
"u_viewTexel",
"u_view",
"u_invView",
"u_proj",
"u_invProj",
"u_viewProj",
"u_invViewProj",
"u_model",
"u_modelView",
"u_modelViewProj",
"u_alphaRef4",
};
const char* getPredefinedUniformName(PredefinedUniform::Enum _enum)
{
return s_predefinedName[_enum];
}
PredefinedUniform::Enum nameToPredefinedUniformEnum(const bx::StringView& _name)
{
for (uint32_t ii = 0; ii < PredefinedUniform::Count; ++ii)
{
if (0 == bx::strCmp(_name, s_predefinedName[ii]) )
{
return PredefinedUniform::Enum(ii);
}
}
return PredefinedUniform::Count;
}
void srtToMatrix4_x1(void* _dst, const void* _src)
{
Matrix4* mtx = reinterpret_cast< Matrix4*>(_dst);
const Srt* srt = reinterpret_cast<const Srt*>(_src);
const float rx = srt->rotate[0];