| Flutter Impeller |

runtime_effect_contents.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "impeller/entity/contents/runtime_effect_contents.h"
6
7 #include <algorithm>
8 #include <future>
9 #include <memory>
10
11 #include "flutter/fml/logging.h"
12 #include "flutter/fml/make_copyable.h"
13 #include "impeller/base/validation.h"
14 #include "impeller/core/formats.h"
15 #include "impeller/core/runtime_types.h"
16 #include "impeller/core/shader_types.h"
17 #include "impeller/entity/contents/content_context.h"
18 #include "impeller/entity/runtime_effect.vert.h"
19 #include "impeller/renderer/capabilities.h"
20 #include "impeller/renderer/pipeline_library.h"
21 #include "impeller/renderer/render_pass.h"
22 #include "impeller/renderer/shader_function.h"
23 #include "impeller/renderer/vertex_descriptor.h"
24
25 namespace impeller {
26
27 namespace {
28 constexpr char kPaddingType = 0;
29 constexpr char kFloatType = 1;
30 } // namespace
31
32 // static
33 BufferView RuntimeEffectContents::EmplaceVulkanUniform(
34 const std::shared_ptr<const std::vector<uint8_t>>& input_data,
35 HostBuffer& host_buffer,
36 const RuntimeUniformDescription& uniform) {
37 // TODO(jonahwilliams): rewrite this to emplace directly into
38 // HostBuffer.
39 std::vector<float> uniform_buffer;
40 uniform_buffer.reserve(uniform.struct_layout.size());
41 size_t uniform_byte_index = 0u;
42 for (char byte_type : uniform.struct_layout) {
43 if (byte_type == kPaddingType) {
44 uniform_buffer.push_back(0.f);
45 } else {
46 FML_DCHECK(byte_type == kFloatType);
47 uniform_buffer.push_back(reinterpret_cast<const float*>(
48 input_data->data())[uniform_byte_index++]);
49 }
50 }
51 size_t alignment = std::max(sizeof(float) * uniform_buffer.size(),
52 DefaultUniformAlignment());
53
54 return host_buffer.Emplace(
55 reinterpret_cast<const void*>(uniform_buffer.data()),
56 sizeof(float) * uniform_buffer.size(), alignment);
57 }
58
59 void RuntimeEffectContents::SetRuntimeStage(
60 std::shared_ptr<RuntimeStage> runtime_stage) {
61 runtime_stage_ = std::move(runtime_stage);
62 }
63
64 void RuntimeEffectContents::SetUniformData(
65 std::shared_ptr<std::vector<uint8_t>> uniform_data) {
66 uniform_data_ = std::move(uniform_data);
67 }
68
69 void RuntimeEffectContents::SetTextureInputs(
70 std::vector<TextureInput> texture_inputs) {
71 texture_inputs_ = std::move(texture_inputs);
72 }
73
74 static ShaderType GetShaderType(RuntimeUniformType type) {
75 switch (type) {
76 case kSampledImage:
77 return ShaderType::kSampledImage;
78 case kFloat:
79 return ShaderType::kFloat;
80 case kStruct:
81 return ShaderType::kStruct;
82 }
83 }
84
85 static std::unique_ptr<ShaderMetadata> MakeShaderMetadata(
86 const RuntimeUniformDescription& uniform) {
87 std::unique_ptr<ShaderMetadata> metadata = std::make_unique<ShaderMetadata>();
88 metadata->name = uniform.name;
89 metadata->members.emplace_back(ShaderStructMemberMetadata{
90 .type = GetShaderType(uniform.type),
91 .size = uniform.GetSize(),
92 .byte_length = uniform.bit_width / 8,
93 });
94
95 return metadata;
96 }
97
98 bool RuntimeEffectContents::BootstrapShader(
99 const ContentContext& renderer) const {
100 if (!RegisterShader(renderer)) {
101 return false;
102 }
103 ContentContextOptions options;
104 options.color_attachment_pixel_format =
105 renderer.GetContext()->GetCapabilities()->GetDefaultColorFormat();
106 CreatePipeline(renderer, options, /*async=*/true);
107 return true;
108 }
109
110 bool RuntimeEffectContents::RegisterShader(
111 const ContentContext& renderer) const {
112 const std::shared_ptr<Context>& context = renderer.GetContext();
113 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
114
115 std::shared_ptr<const ShaderFunction> function = library->GetFunction(
116 runtime_stage_->GetEntrypoint(), ShaderStage::kFragment);
117
118 //--------------------------------------------------------------------------
119 /// Resolve runtime stage function.
120 ///
121
122 if (function && runtime_stage_->IsDirty()) {
123 renderer.ClearCachedRuntimeEffectPipeline(runtime_stage_->GetEntrypoint());
124 context->GetPipelineLibrary()->RemovePipelinesWithEntryPoint(function);
125 library->UnregisterFunction(runtime_stage_->GetEntrypoint(),
126 ShaderStage::kFragment);
127
128 function = nullptr;
129 }
130
131 if (!function) {
132 std::promise<bool> promise;
133 auto future = promise.get_future();
134
135 library->RegisterFunction(
136 runtime_stage_->GetEntrypoint(),
137 ToShaderStage(runtime_stage_->GetShaderStage()),
138 runtime_stage_->GetCodeMapping(),
139 fml::MakeCopyable([promise = std::move(promise)](bool result) mutable {
140 promise.set_value(result);
141 }));
142
143 if (!future.get()) {
144 VALIDATION_LOG << "Failed to build runtime effect (entry point: "
145 << runtime_stage_->GetEntrypoint() << ")";
146 return false;
147 }
148
149 function = library->GetFunction(runtime_stage_->GetEntrypoint(),
150 ShaderStage::kFragment);
151 if (!function) {
152 VALIDATION_LOG
153 << "Failed to fetch runtime effect function immediately after "
154 "registering it (entry point: "
155 << runtime_stage_->GetEntrypoint() << ")";
156 return false;
157 }
158
159 runtime_stage_->SetClean();
160 }
161 return true;
162 }
163
164 std::shared_ptr<Pipeline<PipelineDescriptor>>
165 RuntimeEffectContents::CreatePipeline(const ContentContext& renderer,
166 ContentContextOptions options,
167 bool async) const {
168 const std::shared_ptr<Context>& context = renderer.GetContext();
169 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
170 const std::shared_ptr<const Capabilities>& caps = context->GetCapabilities();
171 const PixelFormat color_attachment_format = caps->GetDefaultColorFormat();
172 const PixelFormat stencil_attachment_format =
173 caps->GetDefaultDepthStencilFormat();
174
175 using VS = RuntimeEffectVertexShader;
176
177 PipelineDescriptor desc;
178 desc.SetLabel("Runtime Stage");
179 desc.AddStageEntrypoint(
180 library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
181 desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(),
182 ShaderStage::kFragment));
183
184 std::shared_ptr<VertexDescriptor> vertex_descriptor =
185 std::make_shared<VertexDescriptor>();
186 vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs,
187 VS::kInterleavedBufferLayout);
188 vertex_descriptor->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts);
189 vertex_descriptor->RegisterDescriptorSetLayouts(
190 runtime_stage_->GetDescriptorSetLayouts().data(),
191 runtime_stage_->GetDescriptorSetLayouts().size());
192 desc.SetVertexDescriptor(std::move(vertex_descriptor));
193 desc.SetColorAttachmentDescriptor(
194 0u, {.format = color_attachment_format, .blending_enabled = true});
195
196 desc.SetStencilAttachmentDescriptors(StencilAttachmentDescriptor{});
197 desc.SetStencilPixelFormat(stencil_attachment_format);
198
199 desc.SetDepthStencilAttachmentDescriptor(DepthAttachmentDescriptor{});
200 desc.SetDepthPixelFormat(stencil_attachment_format);
201
202 options.ApplyToPipelineDescriptor(desc);
203 if (async) {
204 context->GetPipelineLibrary()->GetPipeline(desc, async);
205 return nullptr;
206 }
207
208 auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc, async).Get();
209 if (!pipeline) {
210 VALIDATION_LOG << "Failed to get or create runtime effect pipeline.";
211 return nullptr;
212 }
213
214 return pipeline;
215 }
216
217 bool RuntimeEffectContents::Render(const ContentContext& renderer,
218 const Entity& entity,
219 RenderPass& pass) const {
220 const std::shared_ptr<Context>& context = renderer.GetContext();
221 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
222
223 //--------------------------------------------------------------------------
224 /// Get or register shader. Flutter will do this when the runtime effect
225 /// is first loaded, but this check is added to supporting testing of the
226 /// Aiks API and non-flutter usage of Impeller.
227 ///
228 if (!RegisterShader(renderer)) {
229 return false;
230 }
231
232 //--------------------------------------------------------------------------
233 /// Fragment stage uniforms.
234 ///
235 BindFragmentCallback bind_callback = [this, &renderer,
236 &context](RenderPass& pass) {
237 size_t buffer_index = 0;
238 size_t buffer_offset = 0;
239 size_t sampler_location = 0;
240 size_t buffer_location = 0;
241
242 // Uniforms are ordered in the IPLR according to their
243 // declaration and the uniform location reflects the correct offset to
244 // be mapped to - except that it may include all proceeding
245 // uniforms of a different type. For example, a texture sampler that comes
246 // after 4 float uniforms may have a location of 4. Since we know that
247 // the declarations are already ordered, we can track the uniform location
248 // ourselves.
249 for (const auto& uniform : runtime_stage_->GetUniforms()) {
250 std::unique_ptr<ShaderMetadata> metadata = MakeShaderMetadata(uniform);
251 switch (uniform.type) {
252 case kSampledImage: {
253 FML_DCHECK(sampler_location < texture_inputs_.size());
254 auto& input = texture_inputs_[sampler_location];
255
256 raw_ptr<const Sampler> sampler =
257 context->GetSamplerLibrary()->GetSampler(
258 input.sampler_descriptor);
259
260 SampledImageSlot image_slot;
261 image_slot.name = uniform.name.c_str();
262 image_slot.binding = uniform.binding;
263 image_slot.texture_index = sampler_location;
264 pass.BindDynamicResource(ShaderStage::kFragment,
265 DescriptorType::kSampledImage, image_slot,
266 std::move(metadata), input.texture, sampler);
267 sampler_location++;
268 break;
269 }
270 case kFloat: {
271 FML_DCHECK(renderer.GetContext()->GetBackendType() !=
272 Context::BackendType::kVulkan)
273 << "Uniform " << uniform.name
274 << " had unexpected type kFloat for Vulkan backend.";
275
276 size_t alignment =
277 std::max(uniform.bit_width / 8, DefaultUniformAlignment());
278 BufferView buffer_view = renderer.GetTransientsBuffer().Emplace(
279 uniform_data_->data() + buffer_offset, uniform.GetSize(),
280 alignment);
281
282 ShaderUniformSlot uniform_slot;
283 uniform_slot.name = uniform.name.c_str();
284 uniform_slot.ext_res_0 = buffer_location;
285 pass.BindDynamicResource(ShaderStage::kFragment,
286 DescriptorType::kUniformBuffer, uniform_slot,
287 std::move(metadata), std::move(buffer_view));
288 buffer_index++;
289 buffer_offset += uniform.GetSize();
290 buffer_location++;
291 break;
292 }
293 case kStruct: {
294 FML_DCHECK(renderer.GetContext()->GetBackendType() ==
295 Context::BackendType::kVulkan);
296 ShaderUniformSlot uniform_slot;
297 uniform_slot.binding = uniform.location;
298 uniform_slot.name = uniform.name.c_str();
299
300 pass.BindResource(
301 ShaderStage::kFragment, DescriptorType::kUniformBuffer,
302 uniform_slot, nullptr,
303 EmplaceVulkanUniform(uniform_data_,
304 renderer.GetTransientsBuffer(), uniform));
305 }
306 }
307 }
308
309 return true;
310 };
311
312 /// Now that the descriptor set layouts are known, get the pipeline.
313 using VS = RuntimeEffectVertexShader;
314
315 PipelineBuilderCallback pipeline_callback =
316 [&](ContentContextOptions options) {
317 // Pipeline creation callback for the cache handler to call.
318 return renderer.GetCachedRuntimeEffectPipeline(
319 runtime_stage_->GetEntrypoint(), options, [&]() {
320 return CreatePipeline(renderer, options, /*async=*/false);
321 });
322 };
323
324 return ColorSourceContents::DrawGeometry<VS>(renderer, entity, pass,
325 pipeline_callback,
326 VS::FrameInfo{}, bind_callback);
327 }
328
329 } // namespace impeller
type
GLenum type
Definition: blit_command_gles.cc:151
buffer_view
BufferView buffer_view
Definition: blit_command_gles.cc:152
capabilities.h
impeller::ColorSourceContents::PipelineBuilderCallback
std::function< PipelineRef(ContentContextOptions)> PipelineBuilderCallback
Definition: color_source_contents.h:42
impeller::ColorSourceContents::BindFragmentCallback
std::function< bool(RenderPass &pass)> BindFragmentCallback
Definition: color_source_contents.h:40
impeller::ContentContext
Definition: content_context.h:138
impeller::ContentContext::GetTransientsBuffer
HostBuffer & GetTransientsBuffer() const
Retrieve the currnent host buffer for transient storage.
Definition: content_context.h:296
impeller::ContentContext::ClearCachedRuntimeEffectPipeline
void ClearCachedRuntimeEffectPipeline(const std::string &unique_entrypoint_name) const
Definition: content_context.cc:934
impeller::ContentContext::GetCachedRuntimeEffectPipeline
PipelineRef GetCachedRuntimeEffectPipeline(const std::string &unique_entrypoint_name, const ContentContextOptions &options, const std::function< std::shared_ptr< Pipeline< PipelineDescriptor >>()> &create_callback) const
Definition: content_context.cc:921
impeller::ContentContext::GetContext
std::shared_ptr< Context > GetContext() const
Definition: content_context.cc:913
impeller::Context::BackendType::kVulkan
@ kVulkan
impeller::Entity
Definition: entity.h:20
impeller::HostBuffer
Definition: host_buffer.h:28
impeller::HostBuffer::Emplace
BufferView Emplace(const BufferType &buffer, size_t alignment=0)
Emplace non-uniform data (like contiguous vertices) onto the host buffer.
Definition: host_buffer.h:93
impeller::RenderPass
Render passes encode render commands directed as one specific render target into an underlying comman...
Definition: render_pass.h:30
impeller::RenderPass::BindDynamicResource
virtual bool BindDynamicResource(ShaderStage stage, DescriptorType type, const SampledImageSlot &slot, std::unique_ptr< ShaderMetadata > metadata, std::shared_ptr< const Texture > texture, raw_ptr< const Sampler >)
Bind with dynamically generated shader metadata.
Definition: render_pass.cc:270
impeller::RenderPass::BindResource
virtual bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot &slot, const ShaderMetadata *metadata, BufferView view) override
Definition: render_pass.cc:225
impeller::RuntimeEffectContents::Render
bool Render(const ContentContext &renderer, const Entity &entity, RenderPass &pass) const override
Definition: runtime_effect_contents.cc:217
impeller::RuntimeEffectContents::BootstrapShader
bool BootstrapShader(const ContentContext &renderer) const
Load the runtime effect and ensure a default PSO is initialized.
Definition: runtime_effect_contents.cc:98
impeller::RuntimeEffectContents::SetRuntimeStage
void SetRuntimeStage(std::shared_ptr< RuntimeStage > runtime_stage)
Definition: runtime_effect_contents.cc:59
impeller::RuntimeEffectContents::SetTextureInputs
void SetTextureInputs(std::vector< TextureInput > texture_inputs)
Definition: runtime_effect_contents.cc:69
impeller::RuntimeEffectContents::EmplaceVulkanUniform
static BufferView EmplaceVulkanUniform(const std::shared_ptr< const std::vector< uint8_t >> &input_data, HostBuffer &host_buffer, const RuntimeUniformDescription &uniform)
Definition: runtime_effect_contents.cc:33
impeller::RuntimeEffectContents::SetUniformData
void SetUniformData(std::shared_ptr< std::vector< uint8_t >> uniform_data)
Definition: runtime_effect_contents.cc:64
impeller::raw_ptr
A wrapper around a raw ptr that adds additional unopt mode only checks.
Definition: raw_ptr.h:15
content_context.h
formats.h
impeller
Definition: allocation.cc:12
impeller::ToShaderStage
constexpr ShaderStage ToShaderStage(RuntimeShaderStage stage)
Definition: shader_types.h:29
impeller::MakeShaderMetadata
static std::unique_ptr< ShaderMetadata > MakeShaderMetadata(const RuntimeUniformDescription &uniform)
Definition: runtime_effect_contents.cc:85
impeller::PixelFormat
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99
impeller::GetShaderType
static ShaderType GetShaderType(RuntimeUniformType type)
Definition: runtime_effect_contents.cc:74
impeller::ShaderStage::kFragment
@ kFragment
impeller::ShaderStage::kVertex
@ kVertex
impeller::VS
LinePipeline::VertexShader VS
Definition: line_contents.cc:13
impeller::ShaderType
ShaderType
Definition: shader_types.h:41
impeller::ShaderType::kStruct
@ kStruct
impeller::ShaderType::kFloat
@ kFloat
impeller::ShaderType::kSampledImage
@ kSampledImage
impeller::DescriptorType::kUniformBuffer
@ kUniformBuffer
impeller::DescriptorType::kSampledImage
@ kSampledImage
impeller::DefaultUniformAlignment
constexpr size_t DefaultUniformAlignment()
Definition: platform.h:14
impeller::RuntimeUniformType
RuntimeUniformType
Definition: runtime_types.h:24
impeller::kSampledImage
@ kSampledImage
Definition: runtime_types.h:26
impeller::kFloat
@ kFloat
Definition: runtime_types.h:25
impeller::kStruct
@ kStruct
Definition: runtime_types.h:27
pipeline_library.h
render_pass.h
runtime_effect_contents.h
runtime_types.h
shader_function.h
shader_types.h
impeller::BufferView
Definition: buffer_view.h:19
impeller::ContentContextOptions
Definition: content_context.h:40
impeller::ContentContextOptions::color_attachment_pixel_format
PixelFormat color_attachment_pixel_format
Definition: content_context.h:98
impeller::RuntimeUniformDescription
Definition: runtime_types.h:41
impeller::RuntimeUniformDescription::GetSize
size_t GetSize() const
Computes the total number of bytes that this uniform requires.
Definition: runtime_types.cc:9
impeller::RuntimeUniformDescription::struct_layout
std::vector< uint8_t > struct_layout
Definition: runtime_types.h:50
impeller::RuntimeUniformDescription::name
std::string name
Definition: runtime_types.h:42
impeller::RuntimeUniformDescription::type
RuntimeUniformType type
Definition: runtime_types.h:46
impeller::RuntimeUniformDescription::bit_width
size_t bit_width
Definition: runtime_types.h:48
impeller::SampledImageSlot
Metadata required to bind a combined texture and sampler.
Definition: shader_types.h:98
impeller::SampledImageSlot::texture_index
size_t texture_index
ext_res_0 is the Metal binding value.
Definition: shader_types.h:103
impeller::SampledImageSlot::name
const char * name
The name of the uniform slot.
Definition: shader_types.h:100
impeller::SampledImageSlot::binding
size_t binding
The Vulkan binding value.
Definition: shader_types.h:109
impeller::ShaderStructMemberMetadata
Definition: shader_types.h:63
impeller::ShaderStructMemberMetadata::type
ShaderType type
Definition: shader_types.h:64
impeller::ShaderUniformSlot
Metadata required to bind a buffer.
Definition: shader_types.h:81
impeller::ShaderUniformSlot::binding
size_t binding
The Vulkan binding value.
Definition: shader_types.h:92
impeller::ShaderUniformSlot::ext_res_0
size_t ext_res_0
ext_res_0 is the Metal binding value.
Definition: shader_types.h:86
impeller::ShaderUniformSlot::name
const char * name
The name of the uniform slot.
Definition: shader_types.h:83
validation.h
VALIDATION_LOG
#define VALIDATION_LOG
Definition: validation.h:91
vertex_descriptor.h