Repository navigation
Expand file tree
/
Copy pathDrawInstancedSession.cpp
More file actions
377 lines (337 loc) · 12.9 KB
/
Copy pathDrawInstancedSession.cpp
File metadata and controls
377 lines (337 loc) · 12.9 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @fb-only
#include <shell/renderSessions/DrawInstancedSession.h>
#include <shell/shared/renderSession/ShellParams.h>
#include <igl/RenderCommandEncoder.h>
#if IGL_BACKEND_OPENGL
#include <igl/opengl/Device.h>
#endif
namespace igl::shell {
namespace {
[[maybe_unused]] void stringReplaceAll(std::string& s,
const std::string& searchString,
const std::string& replaceString) {
size_t pos = 0;
while ((pos = s.find(searchString, pos)) != std::string::npos) {
s.replace(pos, searchString.length(), replaceString);
}
}
const char* getMetalShaderSource() {
return R"(
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
constant float2 pos[6] = {
float2(-0.05f, 0.05f),
float2( 0.05f, -0.05f),
float2( -0.05f, -0.05f),
float2(-0.05f, 0.05f),
float2(0.05f, -0.05f),
float2(0.05f, 0.05f)
};
constant float3 col[6] = {
float3(1.0, 0.0, 0.0),
float3(0.0, 1.0, 0.0),
float3(0.0, 0.0, 1.0),
float3(1.0, 0.0, 0.0),
float3(0.0, 1.0, 0.0),
float3(0.0, 0.0, 1.0)
};
struct VertexIn{
float2 offset [[attribute(0)]];
};
struct VertexOut {
float4 position [[position]];
float3 uvw;
};
vertex VertexOut vertexShader(uint vid [[vertex_id]], constant VertexIn * vertices [[buffer(1)]],
VertexIn in [[stage_in]]) {
VertexOut out;
out.position = float4(pos[vid] + in.offset, 0.0, 1.0);
out.uvw = col[vid];
return out;
}
fragment float4 fragmentShader(
VertexOut in[[stage_in]]) {
float4 tex = float4(in.uvw,1.0);
return tex;
}
)";
}
const char* getVulkanVertexShaderSource() {
return R"(#version 460
layout (location=0) in vec2 offset;
layout (location=0) out vec3 color;
const vec2 pos[6] = vec2[6](
vec2(-0.05f, 0.05f),
vec2( 0.05f, -0.05f),
vec2( -0.05f, -0.05f),
vec2(-0.05f, 0.05f),
vec2(0.05f, -0.05f),
vec2(0.05f, 0.05f)
);
const vec3 col[6] = vec3[6](
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0),
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
void main() {
gl_Position = vec4(pos[gl_VertexIndex] + offset , 0.0, 1.0);
color = col[gl_VertexIndex];
}
)";
}
const char* getVulkanFragmentShaderSource() {
return R"(#version 460
precision mediump float;
precision highp int;
layout (location=0) in vec3 color;
layout (location=0) out vec4 out_FragColor;
void main() {
out_FragColor = vec4(color, 1.0);
}
)";
}
const char* getWgslShaderSource() {
return R"(
var<private> pos : array<vec2f, 6> = array<vec2f, 6>(
vec2f(-0.05, 0.05), vec2f(0.05, -0.05), vec2f(-0.05, -0.05),
vec2f(-0.05, 0.05), vec2f(0.05, -0.05), vec2f(0.05, 0.05));
var<private> col : array<vec3f, 6> = array<vec3f, 6>(
vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0),
vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));
struct VertexOut {
@builtin(position) position : vec4f,
@location(0) color : vec3f,
};
@vertex
fn vertexShader(@builtin(vertex_index) vid : u32, @location(0) offset : vec2f) -> VertexOut {
return VertexOut(vec4f(pos[vid] + offset, 0.0, 1.0), col[vid]);
}
@fragment
fn fragmentShader(v : VertexOut) -> @location(0) vec4f {
return vec4f(v.color, 1.0);
}
)";
}
std::unique_ptr<IShaderStages> getShaderStagesForBackend(IDevice& device) {
switch (device.getBackendType()) {
case igl::BackendType::Invalid:
case igl::BackendType::Custom:
IGL_DEBUG_ASSERT_NOT_REACHED();
return nullptr;
case igl::BackendType::WebGPU:
return igl::ShaderStagesCreator::fromLibraryStringInput(
device, getWgslShaderSource(), "vertexShader", "fragmentShader", "", nullptr);
case igl::BackendType::Vulkan:
return igl::ShaderStagesCreator::fromModuleStringInput(device,
getVulkanVertexShaderSource(),
"main",
"",
getVulkanFragmentShaderSource(),
"main",
"",
nullptr);
// @fb-only
// @fb-only
// @fb-only
case igl::BackendType::Metal:
return igl::ShaderStagesCreator::fromLibraryStringInput(
device, getMetalShaderSource(), "vertexShader", "fragmentShader", "", nullptr);
case igl::BackendType::OpenGL: {
#if IGL_BACKEND_OPENGL
auto glVersion =
static_cast<igl::opengl::Device&>(device).getContext().deviceFeatures().getGLVersion();
if (glVersion > igl::opengl::GLVersion::v2_1) {
auto usesOpenGLES = igl::opengl::DeviceFeatureSet::usesOpenGLES();
std::string codeVS(getVulkanVertexShaderSource());
stringReplaceAll(codeVS, "gl_VertexIndex", "gl_VertexID");
stringReplaceAll(codeVS, "460", usesOpenGLES ? "300 es" : "410");
std::string codeFS(getVulkanFragmentShaderSource());
stringReplaceAll(codeFS, "460", usesOpenGLES ? "300 es" : "410");
if (usesOpenGLES) {
stringReplaceAll(codeVS, "layout (location=0) out", "out");
stringReplaceAll(codeFS, "layout (location=0) out", "out");
stringReplaceAll(codeFS, "layout (location=0) in", "in");
}
return igl::ShaderStagesCreator::fromModuleStringInput(
device, codeVS.c_str(), "main", "", codeFS.c_str(), "main", "", nullptr);
} else {
IGL_LOG_INFO("DrawInstancedSession: needs OpenGL 3.0 / OpenGL ES 3.0; skipping\n");
return nullptr;
}
#else
return nullptr;
#endif // IGL_BACKEND_OPENGL
}
case igl::BackendType::D3D12: {
// D3D12 instanced drawing shader
// Note: D3D12 clip space Y is flipped vs Vulkan, so we negate Y to match Vulkan behavior
static const char* kVS = R"(
static const float2 pos[6] = {
float2(-0.05f, 0.05f), float2( 0.05f, -0.05f), float2(-0.05f, -0.05f),
float2(-0.05f, 0.05f), float2( 0.05f, -0.05f), float2( 0.05f, 0.05f)
};
static const float3 col[6] = {
float3(1.0, 0.0, 0.0), float3(0.0, 1.0, 0.0), float3(0.0, 0.0, 1.0),
float3(1.0, 0.0, 0.0), float3(0.0, 1.0, 0.0), float3(0.0, 0.0, 1.0)
};
struct VSIn { float2 offset : TEXCOORD0; };
struct VSOut { float4 position : SV_POSITION; float3 color : TEXCOORD0; };
VSOut main(VSIn v, uint vid : SV_VertexID) {
VSOut o;
float2 p = pos[vid] + v.offset;
o.position = float4(p.x, -p.y, 0.0, 1.0); // Flip Y for D3D12 clip space
o.color = col[vid];
return o;
}
)";
static const char* kPS = R"(
struct PSIn { float4 position : SV_POSITION; float3 color : TEXCOORD0; };
float4 main(PSIn i) : SV_TARGET { return float4(i.color, 1.0); }
)";
return igl::ShaderStagesCreator::fromModuleStringInput(
device, kVS, "main", "", kPS, "main", "", nullptr);
}
}
IGL_UNREACHABLE_RETURN(nullptr)
}
} // namespace
// NOLINTNEXTLINE(bugprone-exception-escape)
void DrawInstancedSession::initialize() noexcept {
// Command queue: backed by different types of GPU HW queues
commandQueue_ = getPlatform().getDevice().createCommandQueue({}, nullptr);
renderPass_.colorAttachments = {{
.loadAction = LoadAction::Clear,
.storeAction = StoreAction::Store,
.clearColor = getPreferredClearColor(),
}};
renderPass_.depthAttachment = {.loadAction = LoadAction::DontCare};
// Create Index Buffer
const int16_t indexes[6] = {0, 1, 2, 3, 4, 5};
indexBuffer_ = getPlatform().getDevice().createBuffer(
BufferDesc{
.type = BufferDesc::BufferTypeBits::Index, .data = &indexes, .length = sizeof(indexes)},
nullptr);
IGL_DEBUG_ASSERT(indexBuffer_);
shaderStages_ = getShaderStagesForBackend(getPlatform().getDevice());
}
// NOLINTNEXTLINE(bugprone-exception-escape)
void DrawInstancedSession::update(SurfaceTextures surfaceTextures) noexcept {
// Per IGL guidelines, surfaceTextures.color may be null on some platforms
// before the surface is ready (e.g., during window resize on Android/iOS).
if (!surfaceTextures.color) {
return;
}
const auto dimensions = surfaceTextures.color->getDimensions();
framebuffer_ = getPlatform().getDevice().createFramebuffer(
FramebufferDesc{.colorAttachments = {{.texture = surfaceTextures.color}}}, nullptr);
IGL_DEBUG_ASSERT(framebuffer_);
if (!renderPipelineStateTriangle_ && shaderStages_) {
const VertexInputStateDesc inputDesc = {
.numAttributes = 1,
.attributes =
{
{
.bufferIndex = 1,
.format = VertexAttributeFormat::Float2,
.offset = 0,
.name = "offset",
.location = 0,
},
},
.numInputBindings = 1,
.inputBindings =
{
{},
{
.stride = sizeof(float) * 2,
.sampleFunction = igl::VertexSampleFunction::Instance,
},
},
};
auto vertexInput0 = getPlatform().getDevice().createVertexInputState(inputDesc, nullptr);
IGL_DEBUG_ASSERT(vertexInput0 != nullptr);
const RenderPipelineDesc desc = {
.vertexInputState = vertexInput0,
.shaderStages = shaderStages_,
.targetDesc =
{
.colorAttachments =
{
{
.textureFormat =
framebuffer_->getColorAttachment(0)
? framebuffer_->getColorAttachment(0)->getProperties().format
: TextureFormat::Invalid,
},
},
.depthAttachmentFormat =
framebuffer_->getDepthAttachment()
? framebuffer_->getDepthAttachment()->getProperties().format
: TextureFormat::Invalid,
},
};
renderPipelineStateTriangle_ = getPlatform().getDevice().createRenderPipeline(desc, nullptr);
IGL_DEBUG_ASSERT(renderPipelineStateTriangle_);
}
if (!vertexBuffer_) {
glm::vec2 translations[100];
int index = 0;
const float offset = 0.1f;
for (int y = -10; y < 10; y += 2) {
for (int x = -10; x < 10; x += 2) {
glm::vec2 translation;
translation.x = static_cast<float>(x) / 10.0f + offset;
translation.y = static_cast<float>(y) / 10.0f + offset;
translations[index++] = translation;
}
}
vertexBuffer_ = getPlatform().getDevice().createBuffer(
BufferDesc{.type = BufferDesc::BufferTypeBits::Vertex,
.data = translations,
.length = sizeof(glm::vec2) * 100},
nullptr);
IGL_DEBUG_ASSERT(vertexBuffer_);
}
framebuffer_->updateDrawable(surfaceTextures.color);
// Command buffers (1-N per thread): create, submit and forget
const std::shared_ptr<ICommandBuffer> buffer = commandQueue_->createCommandBuffer({}, nullptr);
const Viewport viewport = {.x = 0.0f,
.y = 0.0f,
.width = static_cast<float>(dimensions.width),
.height = static_cast<float>(dimensions.height),
.minDepth = 0.0f,
.maxDepth = +1.0f};
const ScissorRect scissor = {.x = 0,
.y = 0,
.width = static_cast<uint32_t>(dimensions.width),
.height = static_cast<uint32_t>(dimensions.height)};
// This will clear the framebuffer
const auto commands = buffer->createRenderCommandEncoder(renderPass_, framebuffer_);
if (renderPipelineStateTriangle_) {
commands->bindRenderPipelineState(renderPipelineStateTriangle_);
commands->bindViewport(viewport);
commands->bindScissorRect(scissor);
commands->pushDebugGroupLabel("Render Triangle", Color(1, 0, 0));
commands->bindVertexBuffer(1, *vertexBuffer_);
commands->bindIndexBuffer(*indexBuffer_, IndexFormat::UInt16);
commands->drawIndexed(6, 100);
commands->popDebugGroupLabel();
}
commands->endEncoding();
if (shellParams().shouldPresent) {
buffer->present(surfaceTextures.color);
}
commandQueue_->submit(*buffer);
RenderSession::update(surfaceTextures);
}
} // namespace igl::shell