/
thin3d.h
675 lines (565 loc) · 15.7 KB
/
thin3d.h
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
// Very thin API wrapper, suitable for porting UI code (like the native/ui framework) and similar but not real rendering.
// Does not involve context creation etc, that should be handled separately - only does drawing.
// The goals may change in the future though.
// MIT licensed, by Henrik Rydgård 2014.
#pragma once
#include <stdint.h>
#include <cstddef>
#include <vector>
#include <string>
#include "base/logging.h"
#include "DataFormat.h"
class Matrix4x4;
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <d3dcommon.h>
struct IDirect3DDevice9;
struct IDirect3D9;
struct IDirect3DDevice9Ex;
struct IDirect3D9Ex;
struct ID3D11Device;
struct ID3D11DeviceContext;
struct ID3D11Device1;
struct ID3D11DeviceContext1;
#endif
class VulkanContext;
namespace Draw {
// Useful in UBOs
typedef int bool32;
enum class Comparison : int {
NEVER,
LESS,
EQUAL,
LESS_EQUAL,
GREATER,
NOT_EQUAL,
GREATER_EQUAL,
ALWAYS,
};
// Had to prefix with LOGIC, too many clashes
enum class LogicOp : int {
LOGIC_CLEAR,
LOGIC_SET,
LOGIC_COPY,
LOGIC_COPY_INVERTED,
LOGIC_NOOP,
LOGIC_INVERT,
LOGIC_AND,
LOGIC_NAND,
LOGIC_OR,
LOGIC_NOR,
LOGIC_XOR,
LOGIC_EQUIV,
LOGIC_AND_REVERSE,
LOGIC_AND_INVERTED,
LOGIC_OR_REVERSE,
LOGIC_OR_INVERTED,
};
enum class BlendOp : int {
ADD,
SUBTRACT,
REV_SUBTRACT,
MIN,
MAX,
};
enum class BlendFactor : uint8_t {
ZERO,
ONE,
SRC_COLOR,
ONE_MINUS_SRC_COLOR,
DST_COLOR,
ONE_MINUS_DST_COLOR,
SRC_ALPHA,
ONE_MINUS_SRC_ALPHA,
DST_ALPHA,
ONE_MINUS_DST_ALPHA,
CONSTANT_COLOR,
ONE_MINUS_CONSTANT_COLOR,
CONSTANT_ALPHA,
ONE_MINUS_CONSTANT_ALPHA,
SRC1_COLOR,
ONE_MINUS_SRC1_COLOR,
SRC1_ALPHA,
ONE_MINUS_SRC1_ALPHA,
};
enum class StencilOp {
KEEP = 0,
ZERO = 1,
REPLACE = 2,
INCREMENT_AND_CLAMP = 3,
DECREMENT_AND_CLAMP = 4,
INVERT = 5,
INCREMENT_AND_WRAP = 6,
DECREMENT_AND_WRAP = 7,
};
enum class TextureFilter : int {
NEAREST = 0,
LINEAR = 1,
};
enum BufferUsageFlag : int {
VERTEXDATA = 1,
INDEXDATA = 2,
GENERIC = 4,
UNIFORM = 8,
DYNAMIC = 16,
};
enum Semantic : int {
SEM_POSITION,
SEM_COLOR0,
SEM_TEXCOORD0,
SEM_TEXCOORD1,
SEM_NORMAL,
SEM_TANGENT,
SEM_BINORMAL, // really BITANGENT
SEM_MAX,
};
enum class Primitive {
POINT_LIST,
LINE_LIST,
LINE_STRIP,
TRIANGLE_LIST,
TRIANGLE_STRIP,
TRIANGLE_FAN,
// Tesselation shader only
PATCH_LIST,
// These are for geometry shaders only.
LINE_LIST_ADJ,
LINE_STRIP_ADJ,
TRIANGLE_LIST_ADJ,
TRIANGLE_STRIP_ADJ,
UNDEFINED,
};
enum VertexShaderPreset : int {
VS_COLOR_2D,
VS_TEXTURE_COLOR_2D,
VS_MAX_PRESET,
};
enum FragmentShaderPreset : int {
FS_COLOR_2D,
FS_TEXTURE_COLOR_2D,
FS_MAX_PRESET,
};
enum class TextureType : uint8_t {
UNKNOWN,
LINEAR1D,
LINEAR2D,
LINEAR3D,
CUBE,
ARRAY1D,
ARRAY2D,
};
enum class ShaderStage {
VERTEX,
FRAGMENT,
GEOMETRY,
CONTROL, // HULL
EVALUATION, // DOMAIN
COMPUTE,
};
enum class CullMode : uint8_t {
NONE,
FRONT,
BACK,
FRONT_AND_BACK, // Not supported on D3D9
};
enum class Facing {
CCW,
CW,
};
enum BorderColor {
DONT_CARE,
TRANSPARENT_BLACK,
OPAQUE_BLACK,
OPAQUE_WHITE,
};
enum {
COLOR_MASK_R = 1,
COLOR_MASK_G = 2,
COLOR_MASK_B = 4,
COLOR_MASK_A = 8,
};
enum class TextureAddressMode {
REPEAT = 0,
REPEAT_MIRROR,
CLAMP_TO_EDGE,
CLAMP_TO_BORDER,
};
enum class ShaderLanguage {
GLSL_ES_200 = 1,
GLSL_ES_300 = 2,
GLSL_410 = 4,
GLSL_VULKAN = 8,
SPIRV_VULKAN = 16,
HLSL_D3D9 = 32,
HLSL_D3D11 = 64,
HLSL_D3D9_BYTECODE = 128,
HLSL_D3D11_BYTECODE = 256,
METAL = 512,
METAL_BYTECODE = 1024,
};
enum FormatSupport {
FMT_RENDERTARGET = 1,
FMT_TEXTURE = 2,
FMT_INPUTLAYOUT = 4,
FMT_DEPTHSTENCIL = 8,
FMT_AUTOGEN_MIPS = 16,
};
enum InfoField {
APINAME,
APIVERSION,
VENDORSTRING,
VENDOR,
SHADELANGVERSION,
DRIVER,
};
enum class NativeObject {
CONTEXT,
CONTEXT_EX,
DEVICE,
DEVICE_EX,
BACKBUFFER_COLOR_VIEW,
BACKBUFFER_DEPTH_VIEW,
BACKBUFFER_COLOR_TEX,
BACKBUFFER_DEPTH_TEX,
FEATURE_LEVEL,
COMPATIBLE_RENDERPASS,
BACKBUFFER_RENDERPASS,
FRAMEBUFFER_RENDERPASS,
INIT_COMMANDBUFFER,
BOUND_TEXTURE0_IMAGEVIEW,
BOUND_TEXTURE1_IMAGEVIEW,
RENDER_MANAGER,
};
enum FBColorDepth {
FBO_8888,
FBO_565,
FBO_4444,
FBO_5551,
};
enum FBChannel {
FB_COLOR_BIT = 1,
FB_DEPTH_BIT = 2,
FB_STENCIL_BIT = 4,
// Implementation specific
FB_SURFACE_BIT = 32, // Used in conjunction with the others in D3D9 to get surfaces through get_api_texture
FB_VIEW_BIT = 64, // Used in conjunction with the others in D3D11 to get shader resource views through get_api_texture
FB_FORMAT_BIT = 128, // Actually retrieves the native format instead. D3D11 only.
};
enum FBBlitFilter {
FB_BLIT_NEAREST = 0,
FB_BLIT_LINEAR = 1,
};
enum UpdateBufferFlags {
UPDATE_DISCARD = 1,
};
enum class Event {
// These happen on D3D resize. Only the backbuffer needs to be resized.
LOST_BACKBUFFER,
GOT_BACKBUFFER,
// These are a bit more serious...
LOST_DEVICE,
GOT_DEVICE,
RESIZED,
PRESENTED,
};
struct FramebufferDesc {
int width;
int height;
int depth;
int numColorAttachments;
bool z_stencil;
FBColorDepth colorDepth;
};
// Binary compatible with D3D11 viewport.
struct Viewport {
float TopLeftX;
float TopLeftY;
float Width;
float Height;
float MinDepth;
float MaxDepth;
};
class RefCountedObject {
public:
RefCountedObject() : refcount_(1) {}
virtual ~RefCountedObject() {}
void AddRef() { refcount_++; }
bool Release();
private:
int refcount_;
};
class BlendState : public RefCountedObject {
public:
};
class SamplerState : public RefCountedObject {
public:
};
class DepthStencilState : public RefCountedObject {
public:
};
class Framebuffer : public RefCountedObject {
public:
};
class Buffer : public RefCountedObject {
public:
};
class Texture : public RefCountedObject {
public:
int Width() { return width_; }
int Height() { return height_; }
int Depth() { return depth_; }
protected:
int width_, height_, depth_;
};
struct BindingDesc {
int stride;
bool instanceRate;
};
struct AttributeDesc {
int binding;
int location; // corresponds to semantic
DataFormat format;
int offset;
};
struct InputLayoutDesc {
std::vector<BindingDesc> bindings;
std::vector<AttributeDesc> attributes;
};
class InputLayout : public RefCountedObject { };
enum class UniformType : int8_t {
FLOAT4,
MATRIX4X4,
};
// For emulation of uniform buffers on D3D9/GL
struct UniformDesc {
const char *name; // For GL
int16_t vertexReg; // For D3D
int16_t fragmentReg; // For D3D
UniformType type;
int16_t offset;
// TODO: Support array elements etc.
};
struct UniformBufferDesc {
size_t uniformBufferSize;
std::vector<UniformDesc> uniforms;
};
class ShaderModule : public RefCountedObject {
public:
virtual ShaderStage GetStage() const = 0;
};
class Pipeline : public RefCountedObject {
public:
virtual ~Pipeline() {}
virtual bool RequiresBuffer() = 0;
};
class RasterState : public RefCountedObject {};
struct StencilSide {
StencilOp failOp;
StencilOp passOp;
StencilOp depthFailOp;
Comparison compareOp;
uint8_t compareMask;
uint8_t writeMask;
uint8_t reference;
};
struct DepthStencilStateDesc {
bool depthTestEnabled;
bool depthWriteEnabled;
Comparison depthCompare;
bool stencilEnabled;
StencilSide front;
StencilSide back;
};
struct BlendStateDesc {
bool enabled;
int colorMask;
BlendFactor srcCol;
BlendFactor dstCol;
BlendOp eqCol;
BlendFactor srcAlpha;
BlendFactor dstAlpha;
BlendOp eqAlpha;
bool logicEnabled;
LogicOp logicOp;
};
struct SamplerStateDesc {
TextureFilter magFilter;
TextureFilter minFilter;
TextureFilter mipFilter;
float maxAniso;
TextureAddressMode wrapU;
TextureAddressMode wrapV;
TextureAddressMode wrapW;
float maxLod;
bool shadowCompareEnabled;
Comparison shadowCompareFunc;
BorderColor borderColor;
};
struct RasterStateDesc {
CullMode cull;
Facing frontFace;
};
struct PipelineDesc {
Primitive prim;
std::vector<ShaderModule *> shaders;
InputLayout *inputLayout;
DepthStencilState *depthStencil;
BlendState *blend;
RasterState *raster;
const UniformBufferDesc *uniformDesc;
};
struct DeviceCaps {
DataFormat preferredDepthBufferFormat;
DataFormat preferredShadowMapFormatLow;
DataFormat preferredShadowMapFormatHigh;
bool anisoSupported;
bool depthRangeMinusOneToOne; // OpenGL style depth
bool geometryShaderSupported;
bool tesselationShaderSupported;
bool multiViewport;
bool dualSourceBlend;
bool logicOpSupported;
bool framebufferCopySupported;
bool framebufferBlitSupported;
bool framebufferDepthCopySupported;
bool framebufferDepthBlitSupported;
};
struct TextureDesc {
TextureType type;
DataFormat format;
int width;
int height;
int depth;
int mipLevels;
bool generateMips;
std::vector<uint8_t *> initData;
};
enum class RPAction {
DONT_CARE,
CLEAR,
KEEP,
};
struct RenderPassInfo {
RPAction color;
RPAction depth;
uint32_t clearColor;
float clearDepth;
uint8_t clearStencil;
};
class DrawContext {
public:
virtual ~DrawContext();
bool CreatePresets();
virtual const DeviceCaps &GetDeviceCaps() const = 0;
virtual uint32_t GetDataFormatSupport(DataFormat fmt) const = 0;
virtual std::vector<std::string> GetFeatureList() const { return std::vector<std::string>(); }
virtual std::vector<std::string> GetExtensionList() const { return std::vector<std::string>(); }
virtual uint32_t GetSupportedShaderLanguages() const = 0;
// Partial pipeline state, used to create pipelines. (in practice, in d3d11 they'll use the native state objects directly).
virtual DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) = 0;
virtual BlendState *CreateBlendState(const BlendStateDesc &desc) = 0;
virtual SamplerState *CreateSamplerState(const SamplerStateDesc &desc) = 0;
virtual RasterState *CreateRasterState(const RasterStateDesc &desc) = 0;
// virtual ComputePipeline CreateComputePipeline(const ComputePipelineDesc &desc) = 0
virtual InputLayout *CreateInputLayout(const InputLayoutDesc &desc) = 0;
// Note that these DO NOT AddRef so you must not ->Release presets unless you manually AddRef them.
ShaderModule *GetVshaderPreset(VertexShaderPreset preset) { return fsPresets_[preset]; }
ShaderModule *GetFshaderPreset(FragmentShaderPreset preset) { return vsPresets_[preset]; }
// Resources
virtual Buffer *CreateBuffer(size_t size, uint32_t usageFlags) = 0;
virtual Texture *CreateTexture(const TextureDesc &desc) = 0;
// On some hardware, you might get a 24-bit depth buffer even though you only wanted a 16-bit one.
virtual Framebuffer *CreateFramebuffer(const FramebufferDesc &desc) = 0;
virtual ShaderModule *CreateShaderModule(ShaderStage stage, ShaderLanguage language, const uint8_t *data, size_t dataSize) = 0;
virtual Pipeline *CreateGraphicsPipeline(const PipelineDesc &desc) = 0;
// Copies data from the CPU over into the buffer, at a specific offset. This does not change the size of the buffer and cannot write outside it.
virtual void UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset, size_t size, UpdateBufferFlags flags) = 0;
virtual void CopyFramebufferImage(Framebuffer *src, int level, int x, int y, int z, Framebuffer *dst, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth, int channelBits) = 0;
virtual bool BlitFramebuffer(Framebuffer *src, int srcX1, int srcY1, int srcX2, int srcY2, Framebuffer *dst, int dstX1, int dstY1, int dstX2, int dstY2, int channelBits, FBBlitFilter filter) = 0;
virtual bool CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride) {
return false;
}
// These functions should be self explanatory.
// Binding a zero render target means binding the backbuffer.
virtual void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp) = 0;
// color must be 0, for now.
virtual void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) = 0;
virtual uintptr_t GetFramebufferAPITexture(Framebuffer *fbo, int channelBits, int attachment) = 0;
virtual void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) = 0;
// Useful in OpenGL ES to give hints about framebuffers on tiler GPUs.
virtual void InvalidateFramebuffer(Framebuffer *fbo) {}
// Dynamic state
virtual void SetScissorRect(int left, int top, int width, int height) = 0;
virtual void SetViewports(int count, Viewport *viewports) = 0;
virtual void SetBlendFactor(float color[4]) = 0;
virtual void BindSamplerStates(int start, int count, SamplerState **state) = 0;
virtual void BindTextures(int start, int count, Texture **textures) = 0;
virtual void BindVertexBuffers(int start, int count, Buffer **buffers, int *offsets) = 0;
virtual void BindIndexBuffer(Buffer *indexBuffer, int offset) = 0;
// Only supports a single dynamic uniform buffer, for maximum compatibility with the old APIs and ease of emulation.
// More modern methods will be added later.
virtual void UpdateDynamicUniformBuffer(const void *ub, size_t size) = 0;
void BindTexture(int stage, Texture *texture) {
BindTextures(stage, 1, &texture);
} // from sampler 0 and upwards
// Call this with 0 to signal that you have been drawing on your own, and need the state reset on the next pipeline bind.
virtual void BindPipeline(Pipeline *pipeline) = 0;
// TODO: Add more sophisticated draws with buffer offsets, and multidraws.
virtual void Draw(int vertexCount, int offset) = 0;
virtual void DrawIndexed(int vertexCount, int offset) = 0;
virtual void DrawUP(const void *vdata, int vertexCount) = 0;
// Frame management (for the purposes of sync and resource management, necessary with modern APIs). Default implementations here.
virtual void BeginFrame() {}
virtual void EndFrame() {}
virtual void WipeQueue() {}
// This should be avoided as much as possible, in favor of clearing when binding a render target, which is native
// on Vulkan.
virtual void Clear(int mask, uint32_t colorval, float depthVal, int stencilVal) = 0;
// Necessary to correctly flip scissor rectangles etc for OpenGL.
void SetTargetSize(int w, int h) {
targetWidth_ = w;
targetHeight_ = h;
}
virtual std::string GetInfoString(InfoField info) const = 0;
virtual uintptr_t GetNativeObject(NativeObject obj) = 0;
virtual void HandleEvent(Event ev, int width, int height, void *param1 = nullptr, void *param2 = nullptr) = 0;
// This flushes command buffers and waits for execution at the point of the end of the last
// renderpass that wrote to the requested framebuffer. This is needed before trying to read it back
// on modern APIs like Vulkan. Ifr the framebuffer is currently being rendered to, we'll just end the render pass.
// The next draw call will automatically start up a new one.
// APIs like OpenGL won't need to implement this one.
virtual void WaitRenderCompletion(Framebuffer *fbo) {}
// Flush state like scissors etc so the caller can do its own custom drawing.
virtual void FlushState() {}
protected:
ShaderModule *vsPresets_[VS_MAX_PRESET];
ShaderModule *fsPresets_[FS_MAX_PRESET];
int targetWidth_;
int targetHeight_;
};
size_t DataFormatSizeInBytes(DataFormat fmt);
bool DataFormatIsDepthStencil(DataFormat fmt);
inline bool DataFormatIsColor(DataFormat fmt) {
return !DataFormatIsDepthStencil(fmt);
}
DrawContext *T3DCreateGLContext();
extern const UniformBufferDesc UBPresetDesc;
#ifdef _WIN32
DrawContext *T3DCreateDX9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, IDirect3DDevice9 *device, IDirect3DDevice9Ex *deviceEx);
DrawContext *T3DCreateD3D11Context(ID3D11Device *device, ID3D11DeviceContext *context, ID3D11Device1 *device1, ID3D11DeviceContext1 *context1, D3D_FEATURE_LEVEL featureLevel, HWND hWnd);
#endif
DrawContext *T3DCreateVulkanContext(VulkanContext *context);
// UBs for the preset shaders
struct VsTexColUB {
float WorldViewProj[16];
};
extern const UniformBufferDesc vsTexColBufDesc;
struct VsColUB {
float WorldViewProj[16];
};
extern const UniformBufferDesc vsColBufDesc;
} // namespace Draw