| Flutter Impeller |

context.h
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 #ifndef FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
6 #define FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
7
8 #include <memory>
9 #include <string>
10
11 #include "fml/closure.h"
12 #include "impeller/base/flags.h"
13 #include "impeller/core/allocator.h"
14 #include "impeller/core/formats.h"
15 #include "impeller/renderer/capabilities.h"
16 #include "impeller/renderer/command_queue.h"
17 #include "impeller/renderer/sampler_library.h"
18
19 namespace impeller {
20
21 class ShaderLibrary;
22 class CommandBuffer;
23 class PipelineLibrary;
24
25 //------------------------------------------------------------------------------
26 /// @brief To do anything rendering related with Impeller, you need a
27 /// context.
28 ///
29 /// Contexts are expensive to construct and typically you only need
30 /// one in the process. The context represents a connection to a
31 /// graphics or compute accelerator on the device.
32 ///
33 /// If there are multiple context in a process, it would typically
34 /// be for separation of concerns (say, use with multiple engines in
35 /// Flutter), talking to multiple accelerators, or talking to the
36 /// same accelerator using different client APIs (Metal, Vulkan,
37 /// OpenGL ES, etc..).
38 ///
39 /// Contexts are thread-safe. They may be created, used, and
40 /// collected (though not from a thread used by an internal pool) on
41 /// any thread. They may also be accessed simultaneously from
42 /// multiple threads.
43 ///
44 /// Contexts are abstract and a concrete instance must be created
45 /// using one of the subclasses of `Context` in
46 /// `//impeller/renderer/backend`.
47 class Context {
48 public:
49 enum class BackendType {
50 kMetal,
51 kOpenGLES,
52 kVulkan,
53 };
54
55 /// The maximum number of tasks that should ever be stored for
56 /// `StoreTaskForGPU`.
57 ///
58 /// This number was arbitrarily chosen. The idea is that this is a somewhat
59 /// rare situation where tasks happen to get executed in that tiny amount of
60 /// time while an app is being backgrounded but still executing.
61 static constexpr int32_t kMaxTasksAwaitingGPU = 64;
62
63 //----------------------------------------------------------------------------
64 /// @brief Destroys an Impeller context.
65 ///
66 virtual ~Context();
67
68 //----------------------------------------------------------------------------
69 /// @brief Get the graphics backend of an Impeller context.
70 ///
71 /// This is useful for cases where a renderer needs to track and
72 /// lookup backend-specific resources, like shaders or uniform
73 /// layout information.
74 ///
75 /// It's not recommended to use this as a substitute for
76 /// per-backend capability checking. Instead, check for specific
77 /// capabilities via `GetCapabilities()`.
78 ///
79 /// @return The graphics backend of the `Context`.
80 ///
81 virtual BackendType GetBackendType() const = 0;
82
83 // TODO(129920): Refactor and move to capabilities.
84 virtual std::string DescribeGpuModel() const = 0;
85
86 //----------------------------------------------------------------------------
87 /// @brief Determines if a context is valid. If the caller ever receives
88 /// an invalid context, they must discard it and construct a new
89 /// context. There is no recovery mechanism to repair a bad
90 /// context.
91 ///
92 /// It is convention in Impeller to never return an invalid
93 /// context from a call that returns an pointer to a context. The
94 /// call implementation performs validity checks itself and return
95 /// a null context instead of a pointer to an invalid context.
96 ///
97 /// How a context goes invalid is backend specific. It could
98 /// happen due to device loss, or any other unrecoverable error.
99 ///
100 /// @return If the context is valid.
101 ///
102 virtual bool IsValid() const = 0;
103
104 //----------------------------------------------------------------------------
105 /// @brief Get the capabilities of Impeller context. All optionally
106 /// supported feature of the platform, client-rendering API, and
107 /// device can be queried using the `Capabilities`.
108 ///
109 /// @return The capabilities. Can never be `nullptr` for a valid context.
110 ///
111 virtual const std::shared_ptr<const Capabilities>& GetCapabilities()
112 const = 0;
113
114 // TODO(129920): Refactor and move to capabilities.
115 virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format);
116
117 //----------------------------------------------------------------------------
118 /// @brief Returns the allocator used to create textures and buffers on
119 /// the device.
120 ///
121 /// @return The resource allocator. Can never be `nullptr` for a valid
122 /// context.
123 ///
124 virtual std::shared_ptr<Allocator> GetResourceAllocator() const = 0;
125
126 //----------------------------------------------------------------------------
127 /// @brief Returns the library of shaders used to specify the
128 /// programmable stages of a pipeline.
129 ///
130 /// @return The shader library. Can never be `nullptr` for a valid
131 /// context.
132 ///
133 virtual std::shared_ptr<ShaderLibrary> GetShaderLibrary() const = 0;
134
135 //----------------------------------------------------------------------------
136 /// @brief Returns the library of combined image samplers used in
137 /// shaders.
138 ///
139 /// @return The sampler library. Can never be `nullptr` for a valid
140 /// context.
141 ///
142 virtual std::shared_ptr<SamplerLibrary> GetSamplerLibrary() const = 0;
143
144 //----------------------------------------------------------------------------
145 /// @brief Returns the library of pipelines used by render or compute
146 /// commands.
147 ///
148 /// @return The pipeline library. Can never be `nullptr` for a valid
149 /// context.
150 ///
151 virtual std::shared_ptr<PipelineLibrary> GetPipelineLibrary() const = 0;
152
153 //----------------------------------------------------------------------------
154 /// @brief Create a new command buffer. Command buffers can be used to
155 /// encode graphics, blit, or compute commands to be submitted to
156 /// the device.
157 ///
158 /// A command buffer can only be used on a single thread.
159 /// Multi-threaded render, blit, or compute passes must create a
160 /// new command buffer on each thread.
161 ///
162 /// @return A new command buffer.
163 ///
164 virtual std::shared_ptr<CommandBuffer> CreateCommandBuffer() const = 0;
165
166 /// @brief Return the graphics queue for submitting command buffers.
167 virtual std::shared_ptr<CommandQueue> GetCommandQueue() const = 0;
168
169 //----------------------------------------------------------------------------
170 /// @brief Force all pending asynchronous work to finish. This is
171 /// achieved by deleting all owned concurrent message loops.
172 ///
173 virtual void Shutdown() = 0;
174
175 /// Stores a task on the `ContextMTL` that is awaiting access for the GPU.
176 ///
177 /// The task will be executed in the event that the GPU access has changed to
178 /// being available or that the task has been canceled. The task should
179 /// operate with the `SyncSwitch` to make sure the GPU is accessible.
180 ///
181 /// If the queue of pending tasks is cleared without GPU access, then the
182 /// failure callback will be invoked and the primary task function will not
183 ///
184 /// Threadsafe.
185 ///
186 /// `task` will be executed on the platform thread.
187 virtual void StoreTaskForGPU(const fml::closure& task,
188 const fml::closure& failure) {
189 FML_CHECK(false && "not supported in this context");
190 }
191
192 /// Run backend specific additional setup and create common shader variants.
193 ///
194 /// This bootstrap is intended to improve the performance of several
195 /// first frame benchmarks that are tracked in the flutter device lab.
196 /// The workload includes initializing commonly used but not default
197 /// shader variants, as well as forcing driver initialization.
198 virtual void InitializeCommonlyUsedShadersIfNeeded() const {}
199
200 /// Dispose resources that are cached on behalf of the current thread.
201 ///
202 /// Some backends such as Vulkan may cache resources that can be reused while
203 /// executing a rendering operation. This API can be called after the
204 /// operation completes in order to clear the cache.
205 virtual void DisposeThreadLocalCachedResources() {}
206
207 /// @brief Enqueue command_buffer for submission by the end of the frame.
208 ///
209 /// Certain backends may immediately flush the command buffer if batch
210 /// submission is not supported. This functionality is not thread safe
211 /// and should only be used via the ContentContext for rendering a
212 /// 2D workload.
213 ///
214 /// Returns true if submission has succeeded. If the buffer is enqueued
215 /// then no error may be returned until FlushCommandBuffers is called.
216 [[nodiscard]] virtual bool EnqueueCommandBuffer(
217 std::shared_ptr<CommandBuffer> command_buffer);
218
219 /// @brief Flush all pending command buffers.
220 ///
221 /// Returns whether or not submission was successful. This functionality
222 /// is not threadsafe and should only be used via the ContentContext for
223 /// rendering a 2D workload.
224 [[nodiscard]] virtual bool FlushCommandBuffers();
225
226 virtual bool AddTrackingFence(const std::shared_ptr<Texture>& texture) const;
227
228 virtual std::shared_ptr<const IdleWaiter> GetIdleWaiter() const;
229
230 //----------------------------------------------------------------------------
231 /// Resets any thread local state that may interfere with embedders.
232 ///
233 /// Today, only the OpenGL backend can trample on thread local state that the
234 /// embedder can access. This call puts the GL state in a sane "clean" state.
235 ///
236 /// Impeller itself is resilient to a dirty thread local state table.
237 ///
238 virtual void ResetThreadLocalState() const;
239
240 /// @brief Retrieve the runtime stage for this context type.
241 ///
242 /// This is used by the engine shell and other subsystems for loading the
243 /// correct shader types.
244 virtual RuntimeStageBackend GetRuntimeStageBackend() const = 0;
245
246 /// @brief Submit the command buffer that renders to the onscreen surface.
247 virtual bool SubmitOnscreen(std::shared_ptr<CommandBuffer> cmd_buffer);
248
249 const Flags& GetFlags() const { return flags_; }
250
251 protected:
252 explicit Context(const Flags& flags);
253
254 Flags flags_;
255 std::vector<std::function<void()>> per_frame_task_;
256
257 private:
258 Context(const Context&) = delete;
259
260 Context& operator=(const Context&) = delete;
261 };
262
263 } // namespace impeller
264
265 #endif // FLUTTER_IMPELLER_RENDERER_CONTEXT_H_
allocator.h
capabilities.h
impeller::Context
To do anything rendering related with Impeller, you need a context.
Definition: context.h:47
impeller::Context::GetIdleWaiter
virtual std::shared_ptr< const IdleWaiter > GetIdleWaiter() const
Definition: context.cc:28
impeller::Context::AddTrackingFence
virtual bool AddTrackingFence(const std::shared_ptr< Texture > &texture) const
Definition: context.cc:36
impeller::Context::GetSamplerLibrary
virtual std::shared_ptr< SamplerLibrary > GetSamplerLibrary() const =0
Returns the library of combined image samplers used in shaders.
impeller::Context::CreateCommandBuffer
virtual std::shared_ptr< CommandBuffer > CreateCommandBuffer() const =0
Create a new command buffer. Command buffers can be used to encode graphics, blit,...
impeller::Context::GetPipelineLibrary
virtual std::shared_ptr< PipelineLibrary > GetPipelineLibrary() const =0
Returns the library of pipelines used by render or compute commands.
impeller::Context::SubmitOnscreen
virtual bool SubmitOnscreen(std::shared_ptr< CommandBuffer > cmd_buffer)
Submit the command buffer that renders to the onscreen surface.
Definition: context.cc:40
impeller::Context::GetShaderLibrary
virtual std::shared_ptr< ShaderLibrary > GetShaderLibrary() const =0
Returns the library of shaders used to specify the programmable stages of a pipeline.
impeller::Context::GetFlags
const Flags & GetFlags() const
Definition: context.h:249
impeller::Context::kMaxTasksAwaitingGPU
static constexpr int32_t kMaxTasksAwaitingGPU
Definition: context.h:61
impeller::Context::GetCapabilities
virtual const std::shared_ptr< const Capabilities > & GetCapabilities() const =0
Get the capabilities of Impeller context. All optionally supported feature of the platform,...
impeller::Context::per_frame_task_
std::vector< std::function< void()> > per_frame_task_
Definition: context.h:255
impeller::Context::UpdateOffscreenLayerPixelFormat
virtual bool UpdateOffscreenLayerPixelFormat(PixelFormat format)
Definition: context.cc:15
impeller::Context::GetBackendType
virtual BackendType GetBackendType() const =0
Get the graphics backend of an Impeller context.
impeller::Context::Shutdown
virtual void Shutdown()=0
Force all pending asynchronous work to finish. This is achieved by deleting all owned concurrent mess...
impeller::Context::Context
Context(const Flags &flags)
Definition: context.cc:13
impeller::Context::DisposeThreadLocalCachedResources
virtual void DisposeThreadLocalCachedResources()
Definition: context.h:205
impeller::Context::FlushCommandBuffers
virtual bool FlushCommandBuffers()
Flush all pending command buffers.
Definition: context.cc:24
impeller::Context::GetCommandQueue
virtual std::shared_ptr< CommandQueue > GetCommandQueue() const =0
Return the graphics queue for submitting command buffers.
impeller::Context::GetRuntimeStageBackend
virtual RuntimeStageBackend GetRuntimeStageBackend() const =0
Retrieve the runtime stage for this context type.
impeller::Context::StoreTaskForGPU
virtual void StoreTaskForGPU(const fml::closure &task, const fml::closure &failure)
Definition: context.h:187
impeller::Context::InitializeCommonlyUsedShadersIfNeeded
virtual void InitializeCommonlyUsedShadersIfNeeded() const
Definition: context.h:198
impeller::Context::GetResourceAllocator
virtual std::shared_ptr< Allocator > GetResourceAllocator() const =0
Returns the allocator used to create textures and buffers on the device.
impeller::Context::DescribeGpuModel
virtual std::string DescribeGpuModel() const =0
impeller::Context::~Context
virtual ~Context()
Destroys an Impeller context.
impeller::Context::IsValid
virtual bool IsValid() const =0
Determines if a context is valid. If the caller ever receives an invalid context, they must discard i...
impeller::Context::flags_
Flags flags_
Definition: context.h:254
impeller::Context::BackendType
BackendType
Definition: context.h:49
impeller::Context::BackendType::kOpenGLES
@ kOpenGLES
impeller::Context::BackendType::kMetal
@ kMetal
impeller::Context::BackendType::kVulkan
@ kVulkan
impeller::Context::ResetThreadLocalState
virtual void ResetThreadLocalState() const
Definition: context.cc:32
impeller::Context::EnqueueCommandBuffer
virtual bool EnqueueCommandBuffer(std::shared_ptr< CommandBuffer > command_buffer)
Enqueue command_buffer for submission by the end of the frame.
Definition: context.cc:19
command_queue.h
formats.h
flags.h
impeller
Definition: allocation.cc:12
impeller::RuntimeStageBackend
RuntimeStageBackend
Definition: runtime_types.h:16
impeller::PixelFormat
PixelFormat
The Pixel formats supported by Impeller. The naming convention denotes the usage of the component,...
Definition: formats.h:99
sampler_library.h
impeller::Flags
Definition: flags.h:9