-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathMRTSession.cpp
506 lines (432 loc) · 18.5 KB
/
MRTSession.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
/*
* 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 <cmath>
#include <igl/NameHandle.h>
#include <IGLU/simdtypes/SimdTypes.h>
#include <igl/CommandBuffer.h>
#include <igl/RenderPipelineState.h>
#include <igl/SamplerState.h>
#include <igl/ShaderCreator.h>
#include <igl/VertexInputState.h>
#include <igl/opengl/Device.h>
#include <igl/opengl/GLIncludes.h>
#include <shell/renderSessions/MRTSession.h>
#include <shell/shared/renderSession/ShellParams.h>
namespace igl::shell {
struct VertexPosUv {
iglu::simdtypes::float3 position; // SIMD 128b aligned
iglu::simdtypes::float2 uv; // SIMD 128b aligned
};
static VertexPosUv vertexData0[] = {
{{-0.9f, 0.9f, 0.0}, {0.0, 1.0}},
{{-0.05f, 0.9f, 0.0}, {1.0, 1.0}},
{{-0.9f, -0.9f, 0.0}, {0.0, 0.0}},
{{-0.05f, -0.9f, 0.0}, {1.0, 0.0}},
};
static VertexPosUv vertexData1[] = {
{{0.05f, 0.9f, 0.0}, {0.0, 1.0}},
{{0.90f, 0.9f, 0.0}, {1.0, 1.0}},
{{0.05f, -0.9f, 0.0}, {0.0, 0.0}},
{{0.90f, -0.9f, 0.0}, {1.0, 0.0}},
};
static uint16_t indexData[] = {
0,
1,
2,
1,
3,
2,
};
enum class ShaderPrecision { Low, Medium, High };
static std::string getPrecisionProlog(ShaderPrecision precision) {
#if IGL_OPENGL_ES
switch (precision) {
case ShaderPrecision::Low:
return {"precision lowp float;"};
case ShaderPrecision::Medium:
return {"precision mediump float;"};
case ShaderPrecision::High:
return {"precision highp float;"};
}
#else
return std::string();
#endif
}
static std::string getVersionProlog() {
#if IGL_OPENGL_ES
return {"#version 300 es\n"};
#else
return std::string("#version 410\n");
#endif
}
static std::string getMetalShaderSource(int metalShaderIdx) {
switch (metalShaderIdx) {
case 0:
return R"(
#include <metal_stdlib>
#include <simd/simd.h>
#line 0
using namespace metal;
struct VertexIn {
float3 position [[attribute(0)]];
float2 uv [[attribute(1)]];
};
struct VertexOut {
float4 position [[position]];
float2 uv;
};
vertex VertexOut vertexShader(
uint vid [[vertex_id]], constant VertexIn * vertices [[buffer(0)]]) {
VertexOut out;
out.position = float4(vertices[vid].position, 1.0);
out.uv = vertices[vid].uv;
return out;
}
struct FragmentOutput {
float4 colorOutGreen [[color(0)]];
float4 colorOutRed [[color(1)]];
};
fragment FragmentOutput fragmentShader(VertexOut IN [[stage_in]],
texture2d<float> diffuseTex
[[texture(0)]]) {
constexpr sampler linearSampler(mag_filter::linear,
min_filter::linear);
FragmentOutput f;
float4 c = diffuseTex.sample(linearSampler, IN.uv);
f.colorOutRed.r = c.r;
f.colorOutRed.g = 0.0;
f.colorOutRed.b = 0.0;
f.colorOutRed.a = 1.0;
f.colorOutGreen.r = 0.0;
f.colorOutGreen.g = c.g;
f.colorOutGreen.b = 0.0;
f.colorOutGreen.a = 1.0;
return f;
})";
default:
return R"(
#include <metal_stdlib>
#include <simd/simd.h>
#line 0
using namespace metal;
struct VertexIn {
float3 position [[attribute(0)]];
float2 uv [[attribute(1)]];
};
struct VertexOut {
float4 position [[position]];
float2 uv;
};
vertex VertexOut vertexShader(
uint vid [[vertex_id]], constant VertexIn * vertices [[buffer(0)]]) {
VertexOut out;
out.position = float4(vertices[vid].position, 1.0);
out.uv = vertices[vid].uv;
return out;
}
fragment float4 fragmentShader(VertexOut IN [[stage_in]],
texture2d<float> greenTex [[texture(0)]],
texture2d<float> redTex [[texture(1)]]) {
constexpr sampler linearSampler(mag_filter::linear,
min_filter::linear);
float4 c = greenTex.sample(linearSampler, IN.uv) +
redTex.sample(linearSampler, IN.uv);
return c;
})";
}
}
static std::string getOpenGLVertexShaderSource() {
return getVersionProlog() + getPrecisionProlog(ShaderPrecision::High) + R"(
in vec3 position;
in vec2 uv_in;
out vec2 uv;
void main() {
gl_Position = vec4(position, 1.0);
uv = uv_in;
})";
}
static std::string getOpenGLFragmentShaderSource(int programIndex) {
if (programIndex == 0) {
return getVersionProlog() + getPrecisionProlog(ShaderPrecision::High) + R"(
uniform sampler2D inputImage;
in vec2 uv;
layout(location = 0) out vec4 colorGreen;
layout(location = 1) out vec4 colorRed;
void main() {
vec4 c = texture(inputImage, uv);
colorGreen = vec4(0., c.g, 0., 1.0);
colorRed = vec4(c.r, 0., 0., 1.0);
})";
} else {
return getVersionProlog() + getPrecisionProlog(ShaderPrecision::High) + R"(
uniform sampler2D colorRed;
uniform sampler2D colorGreen;
in vec2 uv;
out vec4 colorOut;
void main() {
colorOut = texture(colorRed, uv) + texture(colorGreen, uv);
})";
}
}
static std::string getVulkanVertexShaderSource() {
return getPrecisionProlog(ShaderPrecision::High) + R"(
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 uv_in;
layout(location = 0) out vec2 uv;
void main() {
gl_Position = vec4(position, 1.0);
uv = uv_in;
})";
}
static std::string getVulkanFragmentShaderSource(int programIndex) {
if (programIndex == 0) {
return getPrecisionProlog(ShaderPrecision::High) + R"(
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 colorGreen;
layout(location = 1) out vec4 colorRed;
layout(set = 0, binding = 0) uniform sampler2D in_texture;
void main() {
vec4 c = texture(in_texture, uv);
colorGreen = vec4(0., c.g, 0., 1.0);
colorRed = vec4(c.r, 0., 0., 1.0);
})";
} else {
return getPrecisionProlog(ShaderPrecision::High) + R"(
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 out_FragColor;
layout(set = 0, binding = 0) uniform sampler2D in_texture_green;
layout(set = 0, binding = 1) uniform sampler2D in_texture_red;
void main() {
vec2 uv1 = vec2(uv.x, 1.0-uv.y);
out_FragColor = texture(in_texture_green, uv1) + texture(in_texture_red, uv1);
})";
}
}
static std::unique_ptr<IShaderStages> createShaderStagesForBackend(const IDevice& device,
int programIndex) {
switch (device.getBackendType()) {
case igl::BackendType::Invalid:
IGL_DEBUG_ASSERT_NOT_REACHED();
return nullptr;
case igl::BackendType::Vulkan:
return igl::ShaderStagesCreator::fromModuleStringInput(
device,
getVulkanVertexShaderSource().c_str(),
"main",
"",
getVulkanFragmentShaderSource(programIndex).c_str(),
"main",
"",
nullptr);
// @fb-only
// @fb-only
// @fb-only
case igl::BackendType::OpenGL:
return igl::ShaderStagesCreator::fromModuleStringInput(
device,
getOpenGLVertexShaderSource().c_str(),
"main",
"",
getOpenGLFragmentShaderSource(programIndex).c_str(),
"main",
"",
nullptr);
case igl::BackendType::Metal:
return igl::ShaderStagesCreator::fromLibraryStringInput(
device,
getMetalShaderSource(programIndex).c_str(),
"vertexShader",
"fragmentShader",
"",
nullptr);
}
IGL_UNREACHABLE_RETURN(nullptr)
}
static bool isDeviceCompatible(IDevice& device) noexcept {
return device.hasFeature(DeviceFeatures::MultipleRenderTargets);
}
void MRTSession::initialize() noexcept {
auto& device = getPlatform().getDevice();
if (!isDeviceCompatible(device)) {
return;
}
// Vertex buffer, Index buffer and Vertex Input
const BufferDesc vb0Desc =
BufferDesc(BufferDesc::BufferTypeBits::Vertex, vertexData0, sizeof(vertexData0));
vb0_ = device.createBuffer(vb0Desc, nullptr);
const BufferDesc vb1Desc =
BufferDesc(BufferDesc::BufferTypeBits::Vertex, vertexData1, sizeof(vertexData1));
vb1_ = device.createBuffer(vb1Desc, nullptr);
const BufferDesc ibDesc =
BufferDesc(BufferDesc::BufferTypeBits::Index, indexData, sizeof(indexData));
ib0_ = device.createBuffer(ibDesc, nullptr);
VertexInputStateDesc inputDesc;
inputDesc.numAttributes = 2;
inputDesc.attributes[0] = VertexAttribute(
0, VertexAttributeFormat::Float3, offsetof(VertexPosUv, position), "position", 0);
inputDesc.attributes[1] =
VertexAttribute(0, VertexAttributeFormat::Float2, offsetof(VertexPosUv, uv), "uv_in", 1);
inputDesc.numInputBindings = 1;
inputDesc.inputBindings[0].stride = sizeof(VertexPosUv);
vertexInput_ = device.createVertexInputState(inputDesc, nullptr);
// Sampler & Texture
SamplerStateDesc samplerDesc;
samplerDesc.minFilter = samplerDesc.magFilter = SamplerMinMagFilter::Linear;
samplerDesc.debugName = "Sampler: linear";
samp0_ = device.createSamplerState(samplerDesc, nullptr);
tex0_ = getPlatform().loadTexture("igl.png");
{
shaderStagesMRT_ = createShaderStagesForBackend(device, 0);
shaderStagesDisplayLast_ = createShaderStagesForBackend(device, 1);
}
// Command queue: backed by different types of GPU HW queues
const CommandQueueDesc desc{};
commandQueue_ = device.createCommandQueue(desc, nullptr);
tex0_->generateMipmap(*commandQueue_);
renderPassMRT_.colorAttachments.resize(2);
renderPassMRT_.colorAttachments[0].loadAction = LoadAction::Clear;
renderPassMRT_.colorAttachments[0].storeAction = StoreAction::Store;
renderPassMRT_.colorAttachments[0].clearColor = getPreferredClearColor();
renderPassMRT_.colorAttachments[1].loadAction = LoadAction::Clear;
renderPassMRT_.colorAttachments[1].storeAction = StoreAction::Store;
renderPassMRT_.colorAttachments[1].clearColor = getPreferredClearColor();
renderPassDisplayLast_.colorAttachments.resize(1);
renderPassDisplayLast_.colorAttachments[0].loadAction = LoadAction::Clear;
renderPassDisplayLast_.colorAttachments[0].storeAction = StoreAction::Store;
renderPassDisplayLast_.colorAttachments[0].clearColor = getPreferredClearColor();
}
void MRTSession::update(const igl::SurfaceTextures surfaceTextures) noexcept {
auto& device = getPlatform().getDevice();
if (!isDeviceCompatible(device)) {
return;
}
createOrUpdateFramebufferMRT(surfaceTextures);
const size_t textureUnit = 0;
// Graphics pipeline: state batch that fully configures GPU for rendering
if (pipelineStateMRT_ == nullptr) {
RenderPipelineDesc graphicsDesc;
graphicsDesc.vertexInputState = vertexInput_;
graphicsDesc.shaderStages = shaderStagesMRT_;
graphicsDesc.targetDesc.colorAttachments.resize(2);
graphicsDesc.targetDesc.colorAttachments[0].textureFormat =
surfaceTextures.color->getProperties().format;
graphicsDesc.targetDesc.colorAttachments[0].blendEnabled = true;
graphicsDesc.targetDesc.colorAttachments[0].rgbBlendOp = BlendOp::Add;
graphicsDesc.targetDesc.colorAttachments[0].alphaBlendOp = BlendOp::Add;
graphicsDesc.targetDesc.colorAttachments[0].srcRGBBlendFactor = BlendFactor::SrcAlpha;
graphicsDesc.targetDesc.colorAttachments[0].srcAlphaBlendFactor = BlendFactor::SrcAlpha;
graphicsDesc.targetDesc.colorAttachments[0].dstRGBBlendFactor = BlendFactor::OneMinusSrcAlpha;
graphicsDesc.targetDesc.colorAttachments[0].dstAlphaBlendFactor = BlendFactor::OneMinusSrcAlpha;
graphicsDesc.targetDesc.colorAttachments[1].textureFormat =
surfaceTextures.color->getProperties().format;
graphicsDesc.targetDesc.colorAttachments[1].blendEnabled = true;
graphicsDesc.targetDesc.colorAttachments[1].rgbBlendOp = BlendOp::Add;
graphicsDesc.targetDesc.colorAttachments[1].alphaBlendOp = BlendOp::Add;
graphicsDesc.targetDesc.colorAttachments[1].srcRGBBlendFactor = BlendFactor::SrcAlpha;
graphicsDesc.targetDesc.colorAttachments[1].srcAlphaBlendFactor = BlendFactor::SrcAlpha;
graphicsDesc.targetDesc.colorAttachments[1].dstRGBBlendFactor = BlendFactor::OneMinusSrcAlpha;
graphicsDesc.targetDesc.colorAttachments[1].dstAlphaBlendFactor = BlendFactor::OneMinusSrcAlpha;
graphicsDesc.fragmentUnitSamplerMap[textureUnit] = IGL_NAMEHANDLE("inputImage");
graphicsDesc.cullMode = igl::CullMode::Back;
graphicsDesc.frontFaceWinding = igl::WindingMode::Clockwise;
pipelineStateMRT_ = device.createRenderPipeline(graphicsDesc, nullptr);
}
// Command buffers (1-N per thread): create, submit and forget
const CommandBufferDesc cbDesc;
const std::shared_ptr<ICommandBuffer> buffer =
commandQueue_->createCommandBuffer(cbDesc, nullptr);
auto commands = buffer->createRenderCommandEncoder(renderPassMRT_, framebufferMRT_);
commands->bindIndexBuffer(*ib0_, IndexFormat::UInt16);
// Draw call 0
// clang-format off
commands->bindVertexBuffer(0, *vb0_);
commands->bindRenderPipelineState(pipelineStateMRT_);
commands->bindTexture(textureUnit, BindTarget::kFragment, tex0_.get());
commands->bindSamplerState(textureUnit, BindTarget::kFragment, samp0_.get());
commands->drawIndexed(6);
// clang-format on
// Draw call 1
// clang-format off
commands->bindVertexBuffer(0, *vb1_);
commands->drawIndexed(6);
// clang-format on
commands->endEncoding();
createOrUpdateFramebufferDisplayLast(surfaceTextures);
if (pipelineStateLastDisplay_ == nullptr) {
RenderPipelineDesc graphicsDesc;
graphicsDesc.vertexInputState = vertexInput_;
graphicsDesc.shaderStages = shaderStagesDisplayLast_;
graphicsDesc.targetDesc.colorAttachments.resize(1);
graphicsDesc.targetDesc.colorAttachments[0].textureFormat =
surfaceTextures.color->getProperties().format;
graphicsDesc.fragmentUnitSamplerMap[textureUnit] = IGL_NAMEHANDLE("colorRed");
graphicsDesc.fragmentUnitSamplerMap[textureUnit + 1] = IGL_NAMEHANDLE("colorGreen");
graphicsDesc.cullMode = igl::CullMode::Back;
graphicsDesc.frontFaceWinding = igl::WindingMode::Clockwise;
pipelineStateLastDisplay_ = device.createRenderPipeline(graphicsDesc, nullptr);
}
// Command buffers (1-N per thread): create, submit and forget
commands = buffer->createRenderCommandEncoder(renderPassDisplayLast_, framebufferDisplayLast_);
commands->bindIndexBuffer(*ib0_, IndexFormat::UInt16);
// Draw call 0
// clang-format off
commands->bindRenderPipelineState(pipelineStateLastDisplay_);
auto green = framebufferMRT_->getColorAttachment(0);
commands->bindTexture(textureUnit, BindTarget::kFragment, green.get());
commands->bindSamplerState(textureUnit, BindTarget::kFragment, samp0_.get());
auto red = framebufferMRT_->getColorAttachment(1);
commands->bindTexture(textureUnit+1, BindTarget::kFragment, red.get());
commands->bindSamplerState(textureUnit+1, BindTarget::kFragment, samp0_.get());
commands->bindVertexBuffer(0, *vb0_);
commands->drawIndexed(6);
commands->bindVertexBuffer(0, *vb1_);
commands->drawIndexed(6);
// clang-format on
commands->endEncoding();
if (shellParams().shouldPresent) {
buffer->present(surfaceTextures.color);
}
commandQueue_->submit(*buffer); // Guarantees ordering between command buffers
}
std::shared_ptr<ITexture> MRTSession::createTexture2D(const std::shared_ptr<ITexture>& tex) {
const auto dimensions = tex->getDimensions();
TextureDesc desc = TextureDesc::new2D(tex->getProperties().format,
dimensions.width,
dimensions.height,
TextureDesc::TextureUsageBits::Attachment |
TextureDesc::TextureUsageBits::Sampled);
desc.debugName = "shell/renderSessions/MRTSession.cpp:MRTSession::createTexture2D()";
return getPlatform().getDevice().createTexture(desc, nullptr);
}
void MRTSession::createOrUpdateFramebufferDisplayLast(const igl::SurfaceTextures& surfaceTextures) {
if (framebufferDisplayLast_) {
framebufferDisplayLast_->updateDrawable(surfaceTextures.color);
return;
}
// Framebuffer & Texture
FramebufferDesc framebufferDesc;
framebufferDesc.colorAttachments[0].texture = surfaceTextures.color;
framebufferDisplayLast_ = getPlatform().getDevice().createFramebuffer(framebufferDesc, nullptr);
}
void MRTSession::createOrUpdateFramebufferMRT(const igl::SurfaceTextures& surfaceTextures) {
if (framebufferMRT_) {
return;
}
if (tex1_ == nullptr) {
tex1_ = createTexture2D(surfaceTextures.color);
}
if (tex2_ == nullptr) {
tex2_ = createTexture2D(surfaceTextures.color);
}
// Framebuffer & Texture
FramebufferDesc framebufferDesc;
framebufferDesc.colorAttachments[0].texture = tex1_;
framebufferDesc.colorAttachments[1].texture = tex2_;
framebufferMRT_ = getPlatform().getDevice().createFramebuffer(framebufferDesc, nullptr);
}
} // namespace igl::shell