| 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 auto color_attachment_format = caps->GetDefaultColorFormat();
172 const auto stencil_attachment_format = caps->GetDefaultDepthStencilFormat();
173
174 using VS = RuntimeEffectVertexShader;
175
176 PipelineDescriptor desc;
177 desc.SetLabel("Runtime Stage");
178 desc.AddStageEntrypoint(
179 library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
180 desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(),
181 ShaderStage::kFragment));
182
183 std::shared_ptr<VertexDescriptor> vertex_descriptor =
184 std::make_shared<VertexDescriptor>();
185 vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs,
186 VS::kInterleavedBufferLayout);
187 vertex_descriptor->RegisterDescriptorSetLayouts(VS::kDescriptorSetLayouts);
188 vertex_descriptor->RegisterDescriptorSetLayouts(
189 runtime_stage_->GetDescriptorSetLayouts().data(),
190 runtime_stage_->GetDescriptorSetLayouts().size());
191 desc.SetVertexDescriptor(std::move(vertex_descriptor));
192 desc.SetColorAttachmentDescriptor(
193 0u, {.format = color_attachment_format, .blending_enabled = true});
194
195 desc.SetStencilAttachmentDescriptors(StencilAttachmentDescriptor{});
196 desc.SetStencilPixelFormat(stencil_attachment_format);
197
198 desc.SetDepthStencilAttachmentDescriptor(DepthAttachmentDescriptor{});
199 desc.SetDepthPixelFormat(stencil_attachment_format);
200
201 options.ApplyToPipelineDescriptor(desc);
202 if (async) {
203 context->GetPipelineLibrary()->GetPipeline(desc, async);
204 return nullptr;
205 }
206
207 auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc, async).Get();
208 if (!pipeline) {
209 VALIDATION_LOG << "Failed to get or create runtime effect pipeline.";
210 return nullptr;
211 }
212
213 return pipeline;
214 }
215
216 bool RuntimeEffectContents::Render(const ContentContext& renderer,
217 const Entity& entity,
218 RenderPass& pass) const {
219 const std::shared_ptr<Context>& context = renderer.GetContext();
220 const std::shared_ptr<ShaderLibrary>& library = context->GetShaderLibrary();
221
222 //--------------------------------------------------------------------------
223 /// Get or register shader. Flutter will do this when the runtime effect
224 /// is first loaded, but this check is added to supporting testing of the
225 /// Aiks API and non-flutter usage of Impeller.
226 ///
227 if (!RegisterShader(renderer)) {
228 return false;
229 }
230
231 //--------------------------------------------------------------------------
232 /// Fragment stage uniforms.
233 ///
234 BindFragmentCallback bind_callback = [this, &renderer,
235 &context](RenderPass& pass) {
236 size_t minimum_sampler_index = 100000000;
237 size_t buffer_index = 0;
238 size_t buffer_offset = 0;
239
240 for (const auto& uniform : runtime_stage_->GetUniforms()) {
241 std::unique_ptr<ShaderMetadata> metadata = MakeShaderMetadata(uniform);
242 switch (uniform.type) {
243 case kSampledImage: {
244 // Sampler uniforms are ordered in the IPLR according to their
245 // declaration and the uniform location reflects the correct offset to
246 // be mapped to - except that it may include all proceeding float
247 // uniforms. For example, a float sampler that comes after 4 float
248 // uniforms may have a location of 4. To convert to the actual offset
249 // we need to find the largest location assigned to a float uniform
250 // and then subtract this from all uniform locations. This is more or
251 // less the same operation we previously performed in the shader
252 // compiler.
253 minimum_sampler_index =
254 std::min(minimum_sampler_index, uniform.location);
255 break;
256 }
257 case kFloat: {
258 FML_DCHECK(renderer.GetContext()->GetBackendType() !=
259 Context::BackendType::kVulkan)
260 << "Uniform " << uniform.name
261 << " had unexpected type kFloat for Vulkan backend.";
262
263 size_t alignment =
264 std::max(uniform.bit_width / 8, DefaultUniformAlignment());
265 BufferView buffer_view = renderer.GetTransientsBuffer().Emplace(
266 uniform_data_->data() + buffer_offset, uniform.GetSize(),
267 alignment);
268
269 ShaderUniformSlot uniform_slot;
270 uniform_slot.name = uniform.name.c_str();
271 uniform_slot.ext_res_0 = uniform.location;
272 pass.BindDynamicResource(ShaderStage::kFragment,
273 DescriptorType::kUniformBuffer, uniform_slot,
274 std::move(metadata), std::move(buffer_view));
275 buffer_index++;
276 buffer_offset += uniform.GetSize();
277 break;
278 }
279 case kStruct: {
280 FML_DCHECK(renderer.GetContext()->GetBackendType() ==
281 Context::BackendType::kVulkan);
282 ShaderUniformSlot uniform_slot;
283 uniform_slot.binding = uniform.location;
284 uniform_slot.name = uniform.name.c_str();
285
286 pass.BindResource(
287 ShaderStage::kFragment, DescriptorType::kUniformBuffer,
288 uniform_slot, nullptr,
289 EmplaceVulkanUniform(uniform_data_,
290 renderer.GetTransientsBuffer(), uniform));
291 }
292 }
293 }
294
295 size_t sampler_index = 0;
296 for (const auto& uniform : runtime_stage_->GetUniforms()) {
297 std::unique_ptr<ShaderMetadata> metadata = MakeShaderMetadata(uniform);
298
299 switch (uniform.type) {
300 case kSampledImage: {
301 FML_DCHECK(sampler_index < texture_inputs_.size());
302 auto& input = texture_inputs_[sampler_index];
303
304 raw_ptr<const Sampler> sampler =
305 context->GetSamplerLibrary()->GetSampler(
306 input.sampler_descriptor);
307
308 SampledImageSlot image_slot;
309 image_slot.name = uniform.name.c_str();
310 image_slot.binding = uniform.binding;
311 image_slot.texture_index = uniform.location - minimum_sampler_index;
312 pass.BindDynamicResource(ShaderStage::kFragment,
313 DescriptorType::kSampledImage, image_slot,
314 std::move(metadata), input.texture, sampler);
315
316 sampler_index++;
317 break;
318 }
319 default:
320 continue;
321 }
322 }
323 return true;
324 };
325
326 /// Now that the descriptor set layouts are known, get the pipeline.
327 using VS = RuntimeEffectVertexShader;
328
329 PipelineBuilderCallback pipeline_callback =
330 [&](ContentContextOptions options) {
331 // Pipeline creation callback for the cache handler to call.
332 return renderer.GetCachedRuntimeEffectPipeline(
333 runtime_stage_->GetEntrypoint(), options, [&]() {
334 return CreatePipeline(renderer, options, /*async=*/false);
335 });
336 };
337
338 return ColorSourceContents::DrawGeometry<VS>(renderer, entity, pass,
339 pipeline_callback,
340 VS::FrameInfo{}, bind_callback);
341 }
342
343 } // 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:105
impeller::ColorSourceContents::BindFragmentCallback
std::function< bool(RenderPass &pass)> BindFragmentCallback
Definition: color_source_contents.h:103
impeller::ContentContext
Definition: content_context.h:371
impeller::ContentContext::GetTransientsBuffer
HostBuffer & GetTransientsBuffer() const
Retrieve the currnent host buffer for transient storage.
Definition: content_context.h:866
impeller::ContentContext::ClearCachedRuntimeEffectPipeline
void ClearCachedRuntimeEffectPipeline(const std::string &unique_entrypoint_name) const
Definition: content_context.cc:638
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:625
impeller::ContentContext::GetContext
std::shared_ptr< Context > GetContext() const
Definition: content_context.cc:613
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:216
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::VS
GlyphAtlasPipeline::VertexShader VS
Definition: text_contents.cc:25
impeller::MakeShaderMetadata
static std::unique_ptr< ShaderMetadata > MakeShaderMetadata(const RuntimeUniformDescription &uniform)
Definition: runtime_effect_contents.cc:85
impeller::GetShaderType
static ShaderType GetShaderType(RuntimeUniformType type)
Definition: runtime_effect_contents.cc:74
impeller::ShaderStage::kFragment
@ kFragment
impeller::ShaderStage::kVertex
@ kVertex
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:279
impeller::ContentContextOptions::color_attachment_pixel_format
PixelFormat color_attachment_pixel_format
Definition: content_context.h:337
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