forked from BabylonJS/BabylonNative
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NativeEngine.cpp
1384 lines (1154 loc) · 58.6 KB
/
NativeEngine.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
#include "NativeEngine.h"
#include <napi/env.h>
#include <bgfx/bgfx.h>
#include <bgfx/platform.h>
#ifndef WIN32
#include <alloca.h>
#define alloca(size) __builtin_alloca(size)
#endif
// TODO: this needs to be fixed in bgfx
namespace bgfx
{
uint16_t attribToId(Attrib::Enum _attr);
}
#define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10) // Copy-pasta from bgfx_p.h
#define BGFX_UNIFORM_SAMPLERBIT UINT8_C(0x20) // Copy-pasta from bgfx_p.h
#define BGFX_RESET_FLAGS (BGFX_RESET_VSYNC | BGFX_RESET_MSAA_X4 | BGFX_RESET_MAXANISOTROPY)
#include <bimg/bimg.h>
#include <bimg/decode.h>
#include <bimg/encode.h>
#include <bx/math.h>
#include <bx/readerwriter.h>
#include <queue>
#include <regex>
#include <sstream>
namespace babylon
{
namespace
{
template<typename AppendageT>
inline void AppendBytes(std::vector<uint8_t>& bytes, const AppendageT appendage)
{
auto ptr = reinterpret_cast<const uint8_t*>(&appendage);
auto stride = static_cast<std::ptrdiff_t>(sizeof(AppendageT));
bytes.insert(bytes.end(), ptr, ptr + stride);
}
template<typename AppendageT = std::string&>
inline void AppendBytes(std::vector<uint8_t>& bytes, const std::string& string)
{
auto ptr = reinterpret_cast<const uint8_t*>(string.data());
auto stride = static_cast<std::ptrdiff_t>(string.length());
bytes.insert(bytes.end(), ptr, ptr + stride);
}
template<typename ElementT>
inline void AppendBytes(std::vector<uint8_t>& bytes, const gsl::span<ElementT>& data)
{
auto ptr = reinterpret_cast<const uint8_t*>(data.data());
auto stride = static_cast<std::ptrdiff_t>(data.size() * sizeof(ElementT));
bytes.insert(bytes.end(), ptr, ptr + stride);
}
void FlipYInImageBytes(gsl::span<uint8_t> bytes, size_t rowCount, size_t rowPitch)
{
std::vector<uint8_t> buffer{};
buffer.reserve(rowPitch);
for (size_t row = 0; row < rowCount / 2; row++)
{
auto frontPtr = bytes.data() + (row * rowPitch);
auto backPtr = bytes.data() + ((rowCount - row - 1) * rowPitch);
std::memcpy(buffer.data(), frontPtr, rowPitch);
std::memcpy(frontPtr, backPtr, rowPitch);
std::memcpy(backPtr, buffer.data(), rowPitch);
}
}
void AppendUniformBuffer(std::vector<uint8_t>& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::Resource& uniformBuffer, bool isFragment)
{
const uint8_t fragmentBit = (isFragment ? BGFX_UNIFORM_FRAGMENTBIT : 0);
const spirv_cross::SPIRType& type = compiler.get_type(uniformBuffer.base_type_id);
for (uint32_t index = 0; index < type.member_types.size(); ++index)
{
auto name = compiler.get_member_name(uniformBuffer.base_type_id, index);
auto offset = compiler.get_member_decoration(uniformBuffer.base_type_id, index, spv::DecorationOffset);
auto memberType = compiler.get_type(type.member_types[index]);
bgfx::UniformType::Enum bgfxType;
uint16_t regCount;
if (memberType.basetype != spirv_cross::SPIRType::Float)
{
throw std::exception(); // Not supported
}
if (memberType.columns == 1 && 1 <= memberType.vecsize && memberType.vecsize <= 4)
{
bgfxType = bgfx::UniformType::Vec4;
regCount = 1;
}
else if (memberType.columns == 4 && memberType.vecsize == 4)
{
bgfxType = bgfx::UniformType::Mat4;
regCount = 4;
}
else
{
throw std::exception();
}
for (const auto size : memberType.array)
{
regCount *= size;
}
AppendBytes(bytes, static_cast<uint8_t>(name.size()));
AppendBytes(bytes, name);
AppendBytes(bytes, static_cast<uint8_t>(bgfxType | fragmentBit));
AppendBytes(bytes, static_cast<uint8_t>(0)); // Value "num" not used by D3D11 pipeline.
AppendBytes(bytes, static_cast<uint16_t>(offset));
AppendBytes(bytes, static_cast<uint16_t>(regCount));
}
}
void AppendSamplers(std::vector<uint8_t>& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::SmallVector<spirv_cross::Resource>& samplers, bool isFragment, std::unordered_map<std::string, UniformInfo>& cache)
{
const uint8_t fragmentBit = (isFragment ? BGFX_UNIFORM_FRAGMENTBIT : 0);
for (const spirv_cross::Resource& sampler : samplers)
{
AppendBytes(bytes, static_cast<uint8_t>(sampler.name.size()));
AppendBytes(bytes, sampler.name);
AppendBytes(bytes, static_cast<uint8_t>(bgfx::UniformType::Sampler | BGFX_UNIFORM_SAMPLERBIT));
// TODO : These values (num, regIndex, regCount) are only used by Vulkan and should be set for that API
AppendBytes(bytes, static_cast<uint8_t>(0));
AppendBytes(bytes, static_cast<uint16_t>(0));
AppendBytes(bytes, static_cast<uint16_t>(0));
cache[sampler.name].Stage = compiler.get_decoration(sampler.id, spv::DecorationBinding);
}
}
void CacheUniformHandles(bgfx::ShaderHandle shader, std::unordered_map<std::string, UniformInfo>& cache)
{
const auto MAX_UNIFORMS = 256;
bgfx::UniformHandle uniforms[MAX_UNIFORMS];
auto numUniforms = bgfx::getShaderUniforms(shader, uniforms, MAX_UNIFORMS);
bgfx::UniformInfo info{};
for (uint8_t idx = 0; idx < numUniforms; idx++)
{
bgfx::getUniformInfo(uniforms[idx], info);
cache[info.name].Handle = uniforms[idx];
}
}
void GenerateMipmap(const uint8_t* const __restrict source, const int size, const int channels, uint8_t* __restrict dest)
{
int mipsize = size / 2;
for (int y = 0; y < mipsize; ++y)
{
for (int x = 0; x < mipsize; ++x)
{
for (int c = 0; c < channels; ++c)
{
int index = channels * ((y * 2) * size + (x * 2)) + c;
int sum_value = 4 >> 1;
sum_value += source[index + channels * (0 * size + 0)];
sum_value += source[index + channels * (0 * size + 1)];
sum_value += source[index + channels * (1 * size + 0)];
sum_value += source[index + channels * (1 * size + 1)];
dest[channels * (y * mipsize + x) + c] = (uint8_t)(sum_value / 4);
}
}
}
}
const bgfx::Memory* GenerateMipMaps(const bimg::ImageContainer& image)
{
bool widthIsPowerOf2 = ((image.m_width & (~image.m_width + 1)) == image.m_width);
bool supportedFormat = image.m_format == bimg::TextureFormat::RGB8 || image.m_format == bimg::TextureFormat::RGBA8 || image.m_format == bimg::TextureFormat::BGRA8;
if (image.m_width == image.m_height && image.m_width && widthIsPowerOf2 && supportedFormat)
{
auto channelCount = (image.m_format == bimg::TextureFormat::RGB8) ? 3 : 4;
auto mipMapCount = static_cast<uint32_t>(std::log2(image.m_width));
auto mipmapImageSize = image.m_size;
for (uint32_t i = 1; i <= mipMapCount; i++)
{
mipmapImageSize += image.m_size >> (2 * i);
}
auto imageDataRef = bgfx::alloc(mipmapImageSize);
uint8_t* destination = imageDataRef->data;
uint8_t* source = static_cast<uint8_t*>(image.m_data);
memcpy(destination, source, image.m_size);
destination += image.m_size;
auto mipmapSize = image.m_size;
for (uint32_t i = 0; i < mipMapCount; i++)
{
GenerateMipmap(source, image.m_width >> i, channelCount, destination);
source = destination;
mipmapSize >>= 2;
destination += mipmapSize;
}
return imageDataRef;
}
return nullptr;
}
enum class WebGLAttribType
{
BYTE = 5120,
UNSIGNED_BYTE = 5121,
SHORT = 5122,
UNSIGNED_SHORT = 5123,
INT = 5124,
UNSIGNED_INT = 5125,
FLOAT = 5126
};
bgfx::AttribType::Enum ConvertAttribType(WebGLAttribType type)
{
switch (type)
{
case WebGLAttribType::UNSIGNED_BYTE: return bgfx::AttribType::Uint8;
case WebGLAttribType::SHORT: return bgfx::AttribType::Int16;
case WebGLAttribType::FLOAT: return bgfx::AttribType::Float;
default: // avoid "warning: 4 enumeration values not handled"
throw std::exception();
break;
}
}
// Must match constants.ts in Babylon.js.
constexpr std::array<uint64_t, 11> ALPHA_MODE
{
// ALPHA_DISABLE
0x0,
// ALPHA_ADD: SRC ALPHA * SRC + DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_ONE),
// ALPHA_COMBINE: SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE),
// ALPHA_SUBTRACT: DEST - SRC * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_INV_SRC_COLOR, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE),
// ALPHA_MULTIPLY: SRC * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_DST_COLOR, BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE),
// ALPHA_MAXIMIZED: SRC ALPHA * SRC + (1 - SRC) * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_COLOR, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE),
// ALPHA_ONEONE: SRC + DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ZERO, BGFX_STATE_BLEND_ONE),
// ALPHA_PREMULTIPLIED: SRC + (1 - SRC ALPHA) * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE),
// ALPHA_PREMULTIPLIED_PORTERDUFF: SRC + (1 - SRC ALPHA) * DEST, (1 - SRC ALPHA) * DEST ALPHA
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA),
// ALPHA_INTERPOLATE: CST * SRC + (1 - CST) * DEST
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_FACTOR, BGFX_STATE_BLEND_INV_FACTOR, BGFX_STATE_BLEND_FACTOR, BGFX_STATE_BLEND_INV_FACTOR),
// ALPHA_SCREENMODE: SRC + (1 - SRC) * DEST, SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
BGFX_STATE_BLEND_FUNC_SEPARATE(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_COLOR, BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA),
};
constexpr std::array<bgfx::TextureFormat::Enum, 2> TEXTURE_FORMAT
{
bgfx::TextureFormat::RGBA8,
bgfx::TextureFormat::RGBA32F
};
}
Napi::FunctionReference NativeEngine::InitializeAndCreateConstructor(Napi::Env& env)
{
auto& window = RuntimeImpl::GetNativeWindowFromJavaScript(env);
// Initialize bgfx.
bgfx::Init init{};
init.platformData.nwh = window.GetWindowPtr();
bgfx::setPlatformData(init.platformData);
init.type = bgfx::RendererType::Direct3D11;
init.resolution.width = static_cast<uint32_t>(window.GetWidth());
init.resolution.height = static_cast<uint32_t>(window.GetHeight());
init.resolution.reset = BGFX_RESET_FLAGS;
bgfx::init(init);
bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x443355FF, 1.0f, 0);
bgfx::setViewRect(0, 0, 0, init.resolution.width, init.resolution.height);
bgfx::touch(0);
// Initialize the JavaScript side.
Napi::HandleScope scope{ env };
Napi::Function func = DefineClass(
env,
JS_CLASS_NAME,
{
InstanceMethod("getEngine", &NativeEngine::GetEngine),
InstanceMethod("requestAnimationFrame", &NativeEngine::RequestAnimationFrame),
InstanceMethod("createVertexArray", &NativeEngine::CreateVertexArray),
InstanceMethod("deleteVertexArray", &NativeEngine::DeleteVertexArray),
InstanceMethod("bindVertexArray", &NativeEngine::BindVertexArray),
InstanceMethod("createIndexBuffer", &NativeEngine::CreateIndexBuffer),
InstanceMethod("deleteIndexBuffer", &NativeEngine::DeleteIndexBuffer),
InstanceMethod("recordIndexBuffer", &NativeEngine::RecordIndexBuffer),
InstanceMethod("createVertexBuffer", &NativeEngine::CreateVertexBuffer),
InstanceMethod("deleteVertexBuffer", &NativeEngine::DeleteVertexBuffer),
InstanceMethod("recordVertexBuffer", &NativeEngine::RecordVertexBuffer),
InstanceMethod("createProgram", &NativeEngine::CreateProgram),
InstanceMethod("getUniforms", &NativeEngine::GetUniforms),
InstanceMethod("getAttributes", &NativeEngine::GetAttributes),
InstanceMethod("setProgram", &NativeEngine::SetProgram),
InstanceMethod("setState", &NativeEngine::SetState),
InstanceMethod("setZOffset", &NativeEngine::SetZOffset),
InstanceMethod("getZOffset", &NativeEngine::GetZOffset),
InstanceMethod("setDepthTest", &NativeEngine::SetDepthTest),
InstanceMethod("getDepthWrite", &NativeEngine::GetDepthWrite),
InstanceMethod("setDepthWrite", &NativeEngine::SetDepthWrite),
InstanceMethod("setColorWrite", &NativeEngine::SetColorWrite),
InstanceMethod("setBlendMode", &NativeEngine::SetBlendMode),
InstanceMethod("setMatrix", &NativeEngine::SetMatrix),
InstanceMethod("setInt", &NativeEngine::SetInt),
InstanceMethod("setIntArray", &NativeEngine::SetIntArray),
InstanceMethod("setIntArray2", &NativeEngine::SetIntArray2),
InstanceMethod("setIntArray3", &NativeEngine::SetIntArray3),
InstanceMethod("setIntArray4", &NativeEngine::SetIntArray4),
InstanceMethod("setFloatArray", &NativeEngine::SetFloatArray),
InstanceMethod("setFloatArray2", &NativeEngine::SetFloatArray2),
InstanceMethod("setFloatArray3", &NativeEngine::SetFloatArray3),
InstanceMethod("setFloatArray4", &NativeEngine::SetFloatArray4),
InstanceMethod("setMatrices", &NativeEngine::SetMatrices),
InstanceMethod("setMatrix3x3", &NativeEngine::SetMatrix3x3),
InstanceMethod("setMatrix2x2", &NativeEngine::SetMatrix2x2),
InstanceMethod("setFloat", &NativeEngine::SetFloat),
InstanceMethod("setFloat2", &NativeEngine::SetFloat2),
InstanceMethod("setFloat3", &NativeEngine::SetFloat3),
InstanceMethod("setFloat4", &NativeEngine::SetFloat4),
InstanceMethod("createTexture", &NativeEngine::CreateTexture),
InstanceMethod("loadTexture", &NativeEngine::LoadTexture),
InstanceMethod("loadCubeTexture", &NativeEngine::LoadCubeTexture),
InstanceMethod("getTextureWidth", &NativeEngine::GetTextureWidth),
InstanceMethod("getTextureHeight", &NativeEngine::GetTextureHeight),
InstanceMethod("setTextureSampling", &NativeEngine::SetTextureSampling),
InstanceMethod("setTextureWrapMode", &NativeEngine::SetTextureWrapMode),
InstanceMethod("setTextureAnisotropicLevel", &NativeEngine::SetTextureAnisotropicLevel),
InstanceMethod("setTexture", &NativeEngine::SetTexture),
InstanceMethod("deleteTexture", &NativeEngine::DeleteTexture),
InstanceMethod("createFramebuffer", &NativeEngine::CreateFrameBuffer),
InstanceMethod("deleteFramebuffer", &NativeEngine::DeleteFrameBuffer),
InstanceMethod("bindFramebuffer", &NativeEngine::BindFrameBuffer),
InstanceMethod("unbindFramebuffer", &NativeEngine::UnbindFrameBuffer),
InstanceMethod("drawIndexed", &NativeEngine::DrawIndexed),
InstanceMethod("draw", &NativeEngine::Draw),
InstanceMethod("clear", &NativeEngine::Clear),
InstanceMethod("clearColor", &NativeEngine::ClearColor),
InstanceMethod("clearDepth", &NativeEngine::ClearDepth),
InstanceMethod("clearStencil", &NativeEngine::ClearStencil),
InstanceMethod("getRenderWidth", &NativeEngine::GetRenderWidth),
InstanceMethod("getRenderHeight", &NativeEngine::GetRenderHeight),
InstanceMethod("setViewPort", &NativeEngine::SetViewPort),
InstanceMethod("decodeImage", &NativeEngine::DecodeImage),
InstanceMethod("getImageData", &NativeEngine::GetImageData),
InstanceMethod("encodeImage", &NativeEngine::EncodeImage),
});
return Napi::Persistent(func);
}
NativeEngine::NativeEngine(const Napi::CallbackInfo& info)
: NativeEngine(info, RuntimeImpl::GetNativeWindowFromJavaScript(info.Env()))
{}
NativeEngine::NativeEngine(const Napi::CallbackInfo& info, NativeWindow& nativeWindow)
: Napi::ObjectWrap<NativeEngine>{ info }
, m_runtimeImpl{ RuntimeImpl::GetRuntimeImplFromJavaScript(info.Env()) }
, m_currentProgram{ nullptr }
, m_engineState{ BGFX_STATE_DEFAULT }
, m_viewClearState{ 0 }
, m_resizeCallbackTicket{ nativeWindow.AddOnResizeCallback([this](size_t width, size_t height) { this->UpdateSize(width, height); }) }
{
UpdateSize(static_cast<uint32_t>(nativeWindow.GetWidth()), static_cast<uint32_t>(nativeWindow.GetHeight()));
}
void NativeEngine::UpdateSize(size_t width, size_t height)
{
const auto w = static_cast<uint16_t>(width);
const auto h = static_cast<uint16_t>(height);
auto bgfxStats = bgfx::getStats();
if (w != bgfxStats->width || h != bgfxStats->height)
{
bgfx::reset(w, h, BGFX_RESET_FLAGS);
bgfx::setViewRect(0, 0, 0, w, h);
bgfx::touch(0);
}
}
FrameBufferManager& NativeEngine::GetFrameBufferManager()
{
return m_frameBufferManager;
}
// NativeEngine definitions
Napi::Value NativeEngine::GetEngine(const Napi::CallbackInfo& info)
{
return Napi::External<NativeEngine>::New(info.Env(), this);
}
void NativeEngine::RequestAnimationFrame(const Napi::CallbackInfo& info)
{
DispatchAnimationFrameAsync(Napi::Persistent(info[0].As<Napi::Function>()));
}
Napi::Value NativeEngine::CreateVertexArray(const Napi::CallbackInfo& info)
{
return Napi::External<VertexArray>::New(info.Env(), new VertexArray{});
}
void NativeEngine::DeleteVertexArray(const Napi::CallbackInfo& info)
{
delete info[0].As<Napi::External<VertexArray>>().Data();
}
void NativeEngine::BindVertexArray(const Napi::CallbackInfo& info)
{
const auto& vertexArray = *(info[0].As<Napi::External<VertexArray>>().Data());
bgfx::setIndexBuffer(vertexArray.indexBuffer.handle);
const auto& vertexBuffers = vertexArray.vertexBuffers;
for (uint8_t index = 0; index < vertexBuffers.size(); ++index)
{
const auto& vertexBuffer = vertexBuffers[index];
bgfx::setVertexBuffer(index, vertexBuffer.handle, vertexBuffer.startVertex, UINT32_MAX, vertexBuffer.declHandle);
}
}
Napi::Value NativeEngine::CreateIndexBuffer(const Napi::CallbackInfo& info)
{
const Napi::TypedArray data = info[0].As<Napi::TypedArray>();
const bgfx::Memory* ref = bgfx::copy(data.As<Napi::Uint8Array>().Data(), static_cast<uint32_t>(data.ByteLength()));
const uint16_t flags = data.TypedArrayType() == napi_typedarray_type::napi_uint16_array ? 0 : BGFX_BUFFER_INDEX32;
const bgfx::IndexBufferHandle handle = bgfx::createIndexBuffer(ref, flags);
return Napi::Value::From(info.Env(), static_cast<uint32_t>(handle.idx));
}
void NativeEngine::DeleteIndexBuffer(const Napi::CallbackInfo& info)
{
const bgfx::IndexBufferHandle handle{ static_cast<uint16_t>(info[0].As<Napi::Number>().Uint32Value()) };
bgfx::destroy(handle);
}
void NativeEngine::RecordIndexBuffer(const Napi::CallbackInfo& info)
{
VertexArray& vertexArray = *(info[0].As<Napi::External<VertexArray>>().Data());
const bgfx::IndexBufferHandle handle{ static_cast<uint16_t>(info[1].As<Napi::Number>().Uint32Value()) };
vertexArray.indexBuffer.handle = handle;
}
Napi::Value NativeEngine::CreateVertexBuffer(const Napi::CallbackInfo& info)
{
const Napi::Uint8Array data = info[0].As<Napi::Uint8Array>();
// HACK: Create an empty valid vertex decl which will never be used. Consider fixing in bgfx.
bgfx::VertexDecl decl;
decl.begin();
decl.m_stride = 1;
decl.end();
const bgfx::Memory* ref = bgfx::copy(data.Data(), static_cast<uint32_t>(data.ByteLength()));
const bgfx::VertexBufferHandle handle = bgfx::createVertexBuffer(ref, decl);
return Napi::Value::From(info.Env(), static_cast<uint32_t>(handle.idx));
}
void NativeEngine::DeleteVertexBuffer(const Napi::CallbackInfo& info)
{
const bgfx::VertexBufferHandle handle{ static_cast<uint16_t>(info[0].As<Napi::Number>().Uint32Value()) };
bgfx::destroy(handle);
}
void NativeEngine::RecordVertexBuffer(const Napi::CallbackInfo& info)
{
VertexArray& vertexArray = *(info[0].As<Napi::External<VertexArray>>().Data());
const bgfx::VertexBufferHandle handle{ static_cast<uint16_t>(info[1].As<Napi::Number>().Uint32Value()) };
const uint32_t location = info[2].As<Napi::Number>().Uint32Value();
const uint32_t byteOffset = info[3].As<Napi::Number>().Uint32Value();
const uint32_t byteStride = info[4].As<Napi::Number>().Uint32Value();
const uint32_t numElements = info[5].As<Napi::Number>().Uint32Value();
const uint32_t type = info[6].As<Napi::Number>().Uint32Value();
const bool normalized = info[7].As<Napi::Boolean>().Value();
bgfx::VertexDecl decl;
decl.begin();
const bgfx::Attrib::Enum attrib = static_cast<bgfx::Attrib::Enum>(location);
const bgfx::AttribType::Enum attribType = ConvertAttribType(static_cast<WebGLAttribType>(type));
decl.add(attrib, numElements, attribType, normalized);
decl.m_stride = static_cast<uint16_t>(byteStride);
decl.end();
vertexArray.vertexBuffers.push_back({ std::move(handle), byteOffset / byteStride, bgfx::createVertexDecl(decl) });
}
Napi::Value NativeEngine::CreateProgram(const Napi::CallbackInfo& info)
{
const auto vertexSource = info[0].As<Napi::String>().Utf8Value();
// TODO: This is a HACK to account for the fact that DirectX and OpenGL disagree about the vertical orientation of screen space.
// Remove this ASAP when we have a more long-term plan to account for this behavior.
const auto fragmentSource = std::regex_replace(info[1].As<Napi::String>().Utf8Value(), std::regex("dFdy\\("), "-dFdy(");
auto programData = new ProgramData();
std::vector<uint8_t> vertexBytes{};
std::vector<uint8_t> fragmentBytes{};
std::unordered_map<std::string, uint32_t> attributeLocations;
m_shaderCompiler.Compile(vertexSource, fragmentSource, [&](ShaderCompiler::ShaderInfo vertexShaderInfo, ShaderCompiler::ShaderInfo fragmentShaderInfo)
{
constexpr uint8_t BGFX_SHADER_BIN_VERSION = 6;
// These hashes are generated internally by BGFX's custom shader compilation pipeline,
// which we don't have access to. Fortunately, however, they aren't used for anything
// crucial; they just have to match.
constexpr uint32_t vertexOutputsHash = 0xBAD1DEA;
constexpr uint32_t fragmentInputsHash = vertexOutputsHash;
{
const spirv_cross::Compiler& compiler = *vertexShaderInfo.Compiler;
const spirv_cross::ShaderResources resources = compiler.get_shader_resources();
assert(resources.uniform_buffers.size() == 1);
const spirv_cross::Resource& uniformBuffer = resources.uniform_buffers[0];
const spirv_cross::SmallVector<spirv_cross::Resource>& samplers = resources.separate_samplers;
size_t numUniforms = compiler.get_type(uniformBuffer.base_type_id).member_types.size() + samplers.size();
AppendBytes(vertexBytes, BX_MAKEFOURCC('V', 'S', 'H', BGFX_SHADER_BIN_VERSION));
AppendBytes(vertexBytes, vertexOutputsHash);
AppendBytes(vertexBytes, fragmentInputsHash);
AppendBytes(vertexBytes, static_cast<uint16_t>(numUniforms));
AppendUniformBuffer(vertexBytes, compiler, uniformBuffer, false);
AppendSamplers(vertexBytes, compiler, samplers, false, programData->VertexUniformNameToInfo);
AppendBytes(vertexBytes, static_cast<uint32_t>(vertexShaderInfo.Bytes.size()));
AppendBytes(vertexBytes, vertexShaderInfo.Bytes);
AppendBytes(vertexBytes, static_cast<uint8_t>(0));
AppendBytes(vertexBytes, static_cast<uint8_t>(resources.stage_inputs.size()));
for (const spirv_cross::Resource& stageInput : resources.stage_inputs)
{
const uint32_t location = compiler.get_decoration(stageInput.id, spv::DecorationLocation);
AppendBytes(vertexBytes, bgfx::attribToId(static_cast<bgfx::Attrib::Enum>(location)));
std::string attributeName = stageInput.name;
if (attributeName == "a_position")
attributeName = "position";
else if (attributeName == "a_normal")
attributeName = "normal";
else if (attributeName == "a_tangent")
attributeName = "tangent";
else if (attributeName == "a_color")
attributeName = "color";
else if (attributeName == "a_index")
attributeName = "matricesIndices";
else if (attributeName == "a_weight")
attributeName = "matricesWeights";
attributeLocations[attributeName] = location;
}
AppendBytes(vertexBytes, static_cast<uint16_t>(compiler.get_declared_struct_size(compiler.get_type(uniformBuffer.base_type_id))));
}
{
const spirv_cross::Compiler& compiler = *fragmentShaderInfo.Compiler;
const spirv_cross::ShaderResources resources = compiler.get_shader_resources();
assert(resources.uniform_buffers.size() == 1);
const spirv_cross::Resource& uniformBuffer = resources.uniform_buffers[0];
const spirv_cross::SmallVector<spirv_cross::Resource>& samplers = resources.separate_samplers;
size_t numUniforms = compiler.get_type(uniformBuffer.base_type_id).member_types.size() + samplers.size();
AppendBytes(fragmentBytes, BX_MAKEFOURCC('F', 'S', 'H', BGFX_SHADER_BIN_VERSION));
AppendBytes(fragmentBytes, vertexOutputsHash);
AppendBytes(fragmentBytes, fragmentInputsHash);
AppendBytes(fragmentBytes, static_cast<uint16_t>(numUniforms));
AppendUniformBuffer(fragmentBytes, compiler, uniformBuffer, true);
AppendSamplers(fragmentBytes, compiler, samplers, true, programData->FragmentUniformNameToInfo);
AppendBytes(fragmentBytes, static_cast<uint32_t>(fragmentShaderInfo.Bytes.size()));
AppendBytes(fragmentBytes, fragmentShaderInfo.Bytes);
AppendBytes(fragmentBytes, static_cast<uint8_t>(0));
// Fragment shaders don't have attributes.
AppendBytes(fragmentBytes, static_cast<uint8_t>(0));
AppendBytes(fragmentBytes, static_cast<uint16_t>(compiler.get_declared_struct_size(compiler.get_type(uniformBuffer.base_type_id))));
}
});
auto vertexShader = bgfx::createShader(bgfx::copy(vertexBytes.data(), static_cast<uint32_t>(vertexBytes.size())));
CacheUniformHandles(vertexShader, programData->VertexUniformNameToInfo);
programData->AttributeLocations = std::move(attributeLocations);
auto fragmentShader = bgfx::createShader(bgfx::copy(fragmentBytes.data(), static_cast<uint32_t>(fragmentBytes.size())));
CacheUniformHandles(fragmentShader, programData->FragmentUniformNameToInfo);
programData->Program = bgfx::createProgram(vertexShader, fragmentShader, true);
auto finalizer = [](Napi::Env, ProgramData* data)
{
delete data;
};
return Napi::External<ProgramData>::New(info.Env(), programData, finalizer);
}
Napi::Value NativeEngine::GetUniforms(const Napi::CallbackInfo& info)
{
const auto program = info[0].As<Napi::External<ProgramData>>().Data();
const auto names = info[1].As<Napi::Array>();
auto length = names.Length();
auto uniforms = Napi::Array::New(info.Env(), length);
for (uint32_t index = 0; index < length; ++index)
{
const auto name = names[index].As<Napi::String>().Utf8Value();
auto vertexFound = program->VertexUniformNameToInfo.find(name);
auto fragmentFound = program->FragmentUniformNameToInfo.find(name);
if (vertexFound != program->VertexUniformNameToInfo.end())
{
uniforms[index] = Napi::External<UniformInfo>::New(info.Env(), &vertexFound->second);
}
else if (fragmentFound != program->FragmentUniformNameToInfo.end())
{
uniforms[index] = Napi::External<UniformInfo>::New(info.Env(), &fragmentFound->second);
}
else
{
uniforms[index] = info.Env().Null();
}
}
return uniforms;
}
Napi::Value NativeEngine::GetAttributes(const Napi::CallbackInfo& info)
{
const auto program = info[0].As<Napi::External<ProgramData>>().Data();
const auto names = info[1].As<Napi::Array>();
const auto& attributeLocations = program->AttributeLocations;
auto length = names.Length();
auto attributes = Napi::Array::New(info.Env(), length);
for (uint32_t index = 0; index < length; ++index)
{
const auto name = names[index].As<Napi::String>().Utf8Value();
const auto it = attributeLocations.find(name);
int location = (it == attributeLocations.end() ? -1 : gsl::narrow_cast<int>(it->second));
attributes[index] = Napi::Value::From(info.Env(), location);
}
return attributes;
}
void NativeEngine::SetProgram(const Napi::CallbackInfo& info)
{
auto program = info[0].As<Napi::External<ProgramData>>().Data();
m_currentProgram = program;
}
void NativeEngine::SetState(const Napi::CallbackInfo& info)
{
const auto culling = info[0].As<Napi::Boolean>().Value();
const auto reverseSide = info[2].As<Napi::Boolean>().Value();
m_engineState &= ~BGFX_STATE_CULL_MASK;
if (reverseSide)
{
m_engineState &= ~BGFX_STATE_FRONT_CCW;
if (culling)
{
m_engineState |= BGFX_STATE_CULL_CW;
}
}
else
{
m_engineState |= BGFX_STATE_FRONT_CCW;
if (culling)
{
m_engineState |= BGFX_STATE_CULL_CCW;
}
}
// TODO: zOffset
const auto zOffset = info[1].As<Napi::Number>().FloatValue();
}
void NativeEngine::SetZOffset(const Napi::CallbackInfo& info)
{
const auto zOffset = info[0].As<Napi::Number>().FloatValue();
// STUB: Stub.
}
Napi::Value NativeEngine::GetZOffset(const Napi::CallbackInfo& info)
{
// STUB: Stub.
return{};
}
void NativeEngine::SetDepthTest(const Napi::CallbackInfo& info)
{
const auto enable = info[0].As<Napi::Boolean>().Value();
m_engineState &= ~BGFX_STATE_DEPTH_TEST_MASK;
m_engineState |= enable ? BGFX_STATE_DEPTH_TEST_LESS : BGFX_STATE_DEPTH_TEST_ALWAYS;
}
Napi::Value NativeEngine::GetDepthWrite(const Napi::CallbackInfo& info)
{
return Napi::Value::From(info.Env(), !!(m_engineState & BGFX_STATE_WRITE_Z));
}
void NativeEngine::SetDepthWrite(const Napi::CallbackInfo& info)
{
const auto enable = info[0].As<Napi::Boolean>().Value();
m_engineState &= ~BGFX_STATE_WRITE_Z;
m_engineState |= enable ? BGFX_STATE_WRITE_Z : 0;
}
void NativeEngine::SetColorWrite(const Napi::CallbackInfo& info)
{
const auto enable = info[0].As<Napi::Boolean>().Value();
m_engineState &= ~(BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A);
m_engineState |= enable ? (BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A) : 0;
}
void NativeEngine::SetBlendMode(const Napi::CallbackInfo& info)
{
const auto blendMode = info[0].As<Napi::Number>().Int32Value();
m_engineState &= ~BGFX_STATE_BLEND_MASK;
m_engineState |= ALPHA_MODE[blendMode];
}
void NativeEngine::SetInt(const Napi::CallbackInfo& info)
{
const auto uniformData = info[0].As<Napi::External<UniformInfo>>().Data();
const auto value = info[1].As<Napi::Number>().FloatValue();
m_currentProgram->SetUniform(uniformData->Handle, gsl::make_span(&value, 1));
}
template<int size, typename arrayType> void NativeEngine::SetTypeArrayN(const Napi::CallbackInfo& info)
{
const auto uniformData = info[0].As<Napi::External<UniformInfo>>().Data();
const auto array = info[1].As<arrayType>();
size_t elementLength = array.ElementLength();
m_scratch.clear();
for (size_t index = 0; index < elementLength; index += size)
{
const float values[] = {
static_cast<float>(array[index])
, (size > 1) ? static_cast<float>(array[index + 1]) : 0.f
, (size > 2) ? static_cast<float>(array[index + 2]) : 0.f
, (size > 3) ? static_cast<float>(array[index + 3]) : 0.f };
m_scratch.insert(m_scratch.end(), values, values + 4);
}
m_currentProgram->SetUniform(uniformData->Handle, m_scratch, elementLength / size);
}
template<int size> void NativeEngine::SetFloatN(const Napi::CallbackInfo& info)
{
const auto uniformData = info[0].As<Napi::External<UniformInfo>>().Data();
const float values[] = {
info[1].As<Napi::Number>().FloatValue(),
(size > 1) ? info[2].As<Napi::Number>().FloatValue() : 0.f,
(size > 2) ? info[3].As<Napi::Number>().FloatValue() : 0.f,
(size > 3) ? info[4].As<Napi::Number>().FloatValue() : 0.f };
m_currentProgram->SetUniform(uniformData->Handle, values);
}
template<int size> void NativeEngine::SetMatrixN(const Napi::CallbackInfo& info)
{
const auto uniformData = info[0].As<Napi::External<UniformInfo>>().Data();
const auto matrix = info[1].As<Napi::Float32Array>();
const size_t elementLength = matrix.ElementLength();
assert(elementLength == size * size);
if (size < 4)
{
std::array<float, 16> matrixValues{};
size_t index = 0;
for (int line = 0; line < size; line++)
{
for (int col = 0; col < size; col++)
{
matrixValues[line * 4 + col] = matrix[index++];
}
}
m_currentProgram->SetUniform(uniformData->Handle, gsl::make_span(matrixValues.data(), 16));
}
else
{
m_currentProgram->SetUniform(uniformData->Handle, gsl::make_span(matrix.Data(), elementLength));
}
}
void NativeEngine::SetIntArray(const Napi::CallbackInfo& info)
{
SetTypeArrayN<1, Napi::Int32Array>(info);
}
void NativeEngine::SetIntArray2(const Napi::CallbackInfo& info)
{
SetTypeArrayN<2, Napi::Int32Array>(info);
}
void NativeEngine::SetIntArray3(const Napi::CallbackInfo& info)
{
SetTypeArrayN<3, Napi::Int32Array>(info);
}
void NativeEngine::SetIntArray4(const Napi::CallbackInfo& info)
{
SetTypeArrayN<4, Napi::Int32Array>(info);
}
void NativeEngine::SetFloatArray(const Napi::CallbackInfo& info)
{
SetTypeArrayN<1, Napi::Float32Array>(info);
}
void NativeEngine::SetFloatArray2(const Napi::CallbackInfo& info)
{
SetTypeArrayN<2, Napi::Float32Array>(info);
}
void NativeEngine::SetFloatArray3(const Napi::CallbackInfo& info)
{
SetTypeArrayN<3, Napi::Float32Array>(info);
}
void NativeEngine::SetFloatArray4(const Napi::CallbackInfo& info)
{
SetTypeArrayN<4, Napi::Float32Array>(info);
}
void NativeEngine::SetMatrices(const Napi::CallbackInfo& info)
{
const auto uniformData = info[0].As<Napi::External<UniformInfo>>().Data();
const auto matricesArray = info[1].As<Napi::Float32Array>();
const size_t elementLength = matricesArray.ElementLength();
assert(elementLength % 16 == 0);
m_currentProgram->SetUniform(uniformData->Handle, gsl::span(matricesArray.Data(), elementLength), elementLength / 16);
}
void NativeEngine::SetMatrix2x2(const Napi::CallbackInfo& info)
{
SetMatrixN<2>(info);
}
void NativeEngine::SetMatrix3x3(const Napi::CallbackInfo& info)
{
SetMatrixN<3>(info);
}
void NativeEngine::SetMatrix(const Napi::CallbackInfo& info)
{
SetMatrixN<4>(info);
}
void NativeEngine::SetFloat(const Napi::CallbackInfo& info)
{
SetFloatN<1>(info);
}
void NativeEngine::SetFloat2(const Napi::CallbackInfo& info)
{
SetFloatN<2>(info);
}
void NativeEngine::SetFloat3(const Napi::CallbackInfo& info)
{
SetFloatN<3>(info);
}
void NativeEngine::SetFloat4(const Napi::CallbackInfo& info)
{
SetFloatN<4>(info);
}
Napi::Value NativeEngine::CreateTexture(const Napi::CallbackInfo& info)
{
return Napi::External<TextureData>::New(info.Env(), new TextureData());
}
Napi::Value NativeEngine::DecodeImage(const Napi::CallbackInfo& info)
{
auto imageData = new ImageData();
const auto buffer = info[0].As<Napi::ArrayBuffer>();
imageData->Image.reset(bimg::imageParse(&m_allocator, buffer.Data(), static_cast<uint32_t>(buffer.ByteLength())));
return Napi::External<ImageData>::New(info.Env(), imageData);
}
Napi::Value NativeEngine::GetImageData(const Napi::CallbackInfo& info)
{
const auto imageData = info[0].As<Napi::External<ImageData>>().Data();
if (!imageData->Image || !imageData->Image->m_size)
{
return info.Env().Undefined();
}
auto data = Napi::Int8Array::New(info.Env(), imageData->Image->m_size);
const auto ptr = static_cast<uint8_t*>(imageData->Image->m_data);
memcpy(data.Data(), ptr, imageData->Image->m_size);
return data;
}
Napi::Value NativeEngine::EncodeImage(const Napi::CallbackInfo& info)
{
const auto imageData = info[0].As<Napi::External<ImageData>>().Data();
if (!imageData->Image || !imageData->Image->m_size)
{
return info.Env().Undefined();
}
const auto image = imageData->Image.get();
bx::MemoryBlock mb(&m_allocator);
bx::MemoryWriter writer(&mb);
bimg::imageWritePng(&writer, image->m_width, image->m_height, image->m_size/image->m_height, image->m_data, image->m_format, false);
auto data = Napi::Int8Array::New(info.Env(), mb.getSize());
memcpy(data.Data(), static_cast<uint8_t*>(mb.more()), imageData->Image->m_size);
return data;
}
Napi::Value NativeEngine::LoadTexture(const Napi::CallbackInfo& info)
{
const auto textureData = info[0].As<Napi::External<TextureData>>().Data();
const auto buffer = info[1].As<Napi::ArrayBuffer>();
const auto mipMap = info[2].As<Napi::Boolean>().Value();
const auto invertY = info[3].As<Napi::Boolean>().Value();
textureData->Images.push_back(bimg::imageParse(&m_allocator, buffer.Data(), static_cast<uint32_t>(buffer.ByteLength())));
auto& image = *textureData->Images.front();
bool useMipMap = false;
if (invertY)
{
FlipYInImageBytes(gsl::make_span(static_cast<uint8_t*>(image.m_data), image.m_size), image.m_height, image.m_size / image.m_height);
}
auto imageDataRef{ bgfx::makeRef(image.m_data, image.m_size) };
if (mipMap)
{
auto imageDataRefMipMap = GenerateMipMaps(image);
if (imageDataRefMipMap)
{
imageDataRef = imageDataRefMipMap;
useMipMap = true;
}
// TODO: log a warning message: "Could not generate mipmap for texture"
}
textureData->Texture = bgfx::createTexture2D(
image.m_width,
image.m_height,
useMipMap,
1,
static_cast<bgfx::TextureFormat::Enum>(image.m_format),
0,
imageDataRef);
return Napi::Value::From(info.Env(), bgfx::isValid(textureData->Texture));
}