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 
6 
7 #include <algorithm>
8 #include <future>
9 #include <memory>
10 
11 #include "flutter/fml/logging.h"
12 #include "flutter/fml/make_copyable.h"
14 #include "impeller/core/formats.h"
18 #include "impeller/entity/runtime_effect.vert.h"
24 
25 namespace impeller {
26 
27 namespace {
28 constexpr char kPaddingType = 0;
29 constexpr char kFloatType = 1;
30 } // namespace
31 
32 // static
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(),
53 
54  return host_buffer.Emplace(
55  reinterpret_cast<const void*>(uniform_buffer.data()),
56  sizeof(float) * uniform_buffer.size(), alignment);
57 }
58 
60  std::shared_ptr<RuntimeStage> runtime_stage) {
61  runtime_stage_ = std::move(runtime_stage);
62 }
63 
65  std::shared_ptr<std::vector<uint8_t>> uniform_data) {
66  uniform_data_ = std::move(uniform_data);
67 }
68 
70  std::vector<TextureInput> texture_inputs) {
71  texture_inputs_ = std::move(texture_inputs);
72 }
73 
75  switch (type) {
76  case 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 
99  const ContentContext& renderer) const {
100  if (!RegisterShader(renderer)) {
101  return false;
102  }
103  ContentContextOptions options;
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(),
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(),
151  if (!function) {
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(),
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 
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;
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() !=
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());
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;
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() ==
296  ShaderUniformSlot uniform_slot;
297  uniform_slot.binding = uniform.location;
298  uniform_slot.name = uniform.name.c_str();
299 
300  pass.BindResource(
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
GLenum type
BufferView buffer_view
std::function< PipelineRef(ContentContextOptions)> PipelineBuilderCallback
std::function< bool(RenderPass &pass)> BindFragmentCallback
HostBuffer & GetTransientsBuffer() const
Retrieve the currnent host buffer for transient storage.
void ClearCachedRuntimeEffectPipeline(const std::string &unique_entrypoint_name) const
PipelineRef GetCachedRuntimeEffectPipeline(const std::string &unique_entrypoint_name, const ContentContextOptions &options, const std::function< std::shared_ptr< Pipeline< PipelineDescriptor >>()> &create_callback) const
std::shared_ptr< Context > GetContext() const
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
Render passes encode render commands directed as one specific render target into an underlying comman...
Definition: render_pass.h:30
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
virtual bool BindResource(ShaderStage stage, DescriptorType type, const ShaderUniformSlot &slot, const ShaderMetadata *metadata, BufferView view) override
Definition: render_pass.cc:225
bool Render(const ContentContext &renderer, const Entity &entity, RenderPass &pass) const override
bool BootstrapShader(const ContentContext &renderer) const
Load the runtime effect and ensure a default PSO is initialized.
void SetRuntimeStage(std::shared_ptr< RuntimeStage > runtime_stage)
void SetTextureInputs(std::vector< TextureInput > texture_inputs)
static BufferView EmplaceVulkanUniform(const std::shared_ptr< const std::vector< uint8_t >> &input_data, HostBuffer &host_buffer, const RuntimeUniformDescription &uniform)
void SetUniformData(std::shared_ptr< std::vector< uint8_t >> uniform_data)
A wrapper around a raw ptr that adds additional unopt mode only checks.
Definition: raw_ptr.h:15
constexpr ShaderStage ToShaderStage(RuntimeShaderStage stage)
Definition: shader_types.h:29
static std::unique_ptr< ShaderMetadata > MakeShaderMetadata(const RuntimeUniformDescription &uniform)
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99
static ShaderType GetShaderType(RuntimeUniformType type)
LinePipeline::VertexShader VS
constexpr size_t DefaultUniformAlignment()
Definition: platform.h:14
size_t GetSize() const
Computes the total number of bytes that this uniform requires.
Definition: runtime_types.cc:9
std::vector< uint8_t > struct_layout
Definition: runtime_types.h:50
Metadata required to bind a combined texture and sampler.
Definition: shader_types.h:98
size_t texture_index
ext_res_0 is the Metal binding value.
Definition: shader_types.h:103
const char * name
The name of the uniform slot.
Definition: shader_types.h:100
size_t binding
The Vulkan binding value.
Definition: shader_types.h:109
Metadata required to bind a buffer.
Definition: shader_types.h:81
size_t binding
The Vulkan binding value.
Definition: shader_types.h:92
size_t ext_res_0
ext_res_0 is the Metal binding value.
Definition: shader_types.h:86
const char * name
The name of the uniform slot.
Definition: shader_types.h:83
#define VALIDATION_LOG
Definition: validation.h:91