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