Loading...
Searching...
No Matches
GpuComputeNode.hpp
1#pragma once
2
3#if SCORE_PLUGIN_GFX
4#include <Process/ExecutionContext.hpp>
5
6#include <Crousti/Concepts.hpp>
7#include <Crousti/GpuUtils.hpp>
8#include <Crousti/Metadatas.hpp>
9#include <Gfx/GfxExecNode.hpp>
10#include <Gfx/Graph/NodeRenderer.hpp>
11#include <Gfx/Graph/RenderList.hpp>
12#include <Gfx/Graph/Uniforms.hpp>
13
14namespace oscr
15{
16// Compute nodes that do not have any texture output so that they can get pulled
17// must drive things internally instead
18template <typename Node_T>
19using ComputeNodeBaseType = std::conditional_t<
20 avnd::gpu_image_output_introspection<Node_T>::size != 0, CustomGpuNodeBase,
21 CustomGpuOutputNodeBase>;
22template <typename Node_T>
23using ComputeRendererBaseType = std::conditional_t<
24 avnd::gpu_image_output_introspection<Node_T>::size != 0, score::gfx::NodeRenderer,
26
27template <typename Node_T>
28struct GpuComputeNode final : ComputeNodeBaseType<Node_T>
29{
30 GpuComputeNode(
31 std::weak_ptr<Execution::ExecutionCommandQueue> q, Gfx::exec_controls ctls, int id,
32 const score::DocumentContext& ctx)
33 : ComputeNodeBaseType<Node_T>{std::move(q), std::move(ctls), ctx}
34 {
35 this->instance = id;
36
37 initGfxPorts<Node_T>(this, this->input, this->output);
38 using layout = typename Node_T::layout;
39 static constexpr auto lay = layout{};
40
41 gpp::qrhi::generate_shaders gen;
42 this->compute
43 = QString::fromStdString(gen.compute_shader(lay) + Node_T{}.compute().data());
44 }
45
47 createRenderer(score::gfx::RenderList& r) const noexcept override;
48};
49
50template <typename Node_T>
51struct GpuComputeRenderer final : ComputeRendererBaseType<Node_T>
52{
53 using texture_inputs = avnd::gpu_image_input_introspection<Node_T>;
54 using texture_outputs = avnd::gpu_image_output_introspection<Node_T>;
55 Node_T state;
56 score::gfx::Message m_last_message{};
57 ossia::small_flat_map<const score::gfx::Port*, score::gfx::TextureRenderTarget, 2>
58 m_rts;
59
60 ossia::time_value m_last_time{-1};
61
62 QRhiShaderResourceBindings* m_srb{};
63 QRhiComputePipeline* m_pipeline{};
64
65 bool m_createdPipeline{};
66
67 int sampler_k = 0;
68 int ubo_k = 0;
69 ossia::flat_map<int, QRhiBuffer*> createdUbos;
70 ossia::flat_map<int, QRhiTexture*> createdTexs;
71
72#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
73 std::vector<QRhiBufferReadbackResult*> bufReadbacks;
74 void addReadback(QRhiBufferReadbackResult* r) { bufReadbacks.push_back(r); }
75#endif
76
77 std::vector<QRhiReadbackResult*> texReadbacks;
78 void addReadback(QRhiReadbackResult* r) { texReadbacks.push_back(r); }
79
80 const GpuComputeNode<Node_T>& node() const noexcept
81 {
82 return static_cast<const GpuComputeNode<Node_T>&>(score::gfx::NodeRenderer::node);
83 }
84
85 GpuComputeRenderer(const GpuComputeNode<Node_T>& p)
86 : ComputeRendererBaseType<Node_T>{p}
87 {
88 prepareNewState(state, p);
89 }
90
92 renderTargetForInput(const score::gfx::Port& p) override
93 {
94 auto it = m_rts.find(&p);
95 SCORE_ASSERT(it != m_rts.end());
96 return it->second;
97 }
98
99 QRhiTexture* createInput(
100 score::gfx::RenderList& renderer, int k, QRhiTexture::Format fmt, QSize size)
101 {
102 auto& parent = node();
103 auto port = parent.input[k];
104 static constexpr auto flags
105 = QRhiTexture::RenderTarget | QRhiTexture::UsedWithLoadStore;
106 auto texture = renderer.state.rhi->newTexture(fmt, size, 1, flags);
107 SCORE_ASSERT(texture->create());
108 m_rts[port]
109 = score::gfx::createRenderTarget(renderer.state, texture, renderer.samples());
110 return texture;
111 }
112
113 template <typename F>
114 QRhiShaderResourceBinding initBinding(score::gfx::RenderList& renderer, F field)
115 {
116 static constexpr auto bindingStages = QRhiShaderResourceBinding::ComputeStage;
117 if constexpr(requires { F::ubo; })
118 {
119 auto it = createdUbos.find(F::binding());
120 QRhiBuffer* buffer = it != createdUbos.end() ? it->second : nullptr;
121 return QRhiShaderResourceBinding::uniformBuffer(
122 F::binding(), bindingStages, buffer);
123 }
124 else if constexpr(requires { F::image2D; })
125 {
126 auto tex_it = createdTexs.find(F::binding());
127 QRhiTexture* tex
128 = tex_it != createdTexs.end() ? tex_it->second : &renderer.emptyTexture();
129
130 if constexpr(
131 requires { F::load; } && requires { F::store; })
132 return QRhiShaderResourceBinding::imageLoadStore(
133 F::binding(), bindingStages, tex, 0);
134 else if constexpr(requires { F::readonly; })
135 return QRhiShaderResourceBinding::imageLoad(F::binding(), bindingStages, tex, 0);
136 else if constexpr(requires { F::writeonly; })
137 return QRhiShaderResourceBinding::imageStore(
138 F::binding(), bindingStages, tex, 0);
139 else
140 static_assert(F::load || F::store);
141 }
142 else if constexpr(requires { F::buffer; })
143 {
144 auto it = createdUbos.find(F::binding());
145 QRhiBuffer* buf = it != createdUbos.end() ? it->second : nullptr;
146
147 if constexpr(
148 requires { F::load; } && requires { F::store; })
149 return QRhiShaderResourceBinding::bufferLoadStore(
150 F::binding(), bindingStages, buf);
151 else if constexpr(requires { F::load; })
152 return QRhiShaderResourceBinding::bufferLoad(F::binding(), bindingStages, buf);
153 else if constexpr(requires { F::store; })
154 return QRhiShaderResourceBinding::bufferStore(F::binding(), bindingStages, buf);
155 else
156 static_assert(F::load || F::store);
157 }
158 else
159 {
160 static_assert(F::nope);
161 throw;
162 }
163 }
164
165 auto initBindings(score::gfx::RenderList& renderer)
166 {
167 auto& rhi = *renderer.state.rhi;
168 // Shader resource bindings
169 auto srb = rhi.newShaderResourceBindings();
170 SCORE_ASSERT(srb);
171
172 QVarLengthArray<QRhiShaderResourceBinding, 8> bindings;
173
174 using bindings_type = decltype(Node_T::layout::bindings);
175 boost::pfr::for_each_field(
176 bindings_type{}, [&](auto f) { bindings.push_back(initBinding(renderer, f)); });
177
178 srb->setBindings(bindings.begin(), bindings.end());
179 return srb;
180 }
181
182 QRhiComputePipeline* createComputePipeline(score::gfx::RenderList& renderer)
183 {
184 auto& parent = node();
185 auto& rhi = *renderer.state.rhi;
186 auto compute = rhi.newComputePipeline();
187 auto cs = score::gfx::makeCompute(renderer.state, parent.compute);
188 compute->setShaderStage(QRhiShaderStage(QRhiShaderStage::Compute, cs));
189
190 return compute;
191 }
192
193 void init_input(score::gfx::RenderList& renderer, auto field)
194 {
195 //using input_type = std::decay_t<F>;
196 }
197
198 template <std::size_t Idx, typename F>
199 requires avnd::image_port<F>
200 void init_input(score::gfx::RenderList& renderer, avnd::field_reflection<Idx, F> field)
201 {
202 using bindings_type = decltype(Node_T::layout::bindings);
203 using image_type = std::decay_t<decltype(bindings_type{}.*F::image())>;
204 auto tex = createInput(
205 renderer, sampler_k++, gpp::qrhi::textureFormat<image_type>(),
206 renderer.state.renderSize);
207
208 using sampler_type = typename avnd::member_reflection<F::image()>::member_type;
209 createdTexs[sampler_type::binding()] = tex;
210 }
211
212 template <std::size_t Idx, typename F>
213 requires avnd::uniform_port<F>
214 void init_input(score::gfx::RenderList& renderer, avnd::field_reflection<Idx, F> field)
215 {
216 using ubo_type = typename avnd::member_reflection<F::uniform()>::class_type;
217
218 // We must mark the UBO to construct.
219 if(createdUbos.find(ubo_type::binding()) != createdUbos.end())
220 return;
221
222 auto ubo = renderer.state.rhi->newBuffer(
223 QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, gpp::std140_size<ubo_type>());
224 ubo->create();
225
226 createdUbos[ubo_type::binding()] = ubo;
227 }
228
229 void init(score::gfx::RenderList& renderer, QRhiResourceUpdateBatch& res) override
230 {
231 auto& parent = node();
232 if constexpr(requires { state.prepare(); })
233 {
234 parent.processControlIn(
235 *this, state, m_last_message, parent.last_message, parent.m_ctx);
236 state.prepare();
237 }
238
239 // Create the global shared inputs
240 avnd::input_introspection<Node_T>::for_all(
241 [this, &renderer](auto f) { init_input(renderer, f); });
242
243 m_srb = initBindings(renderer);
244 m_pipeline = createComputePipeline(renderer);
245 m_pipeline->setShaderResourceBindings(m_srb);
246
247 // No update step: we can directly create the pipeline here
248 if constexpr(!requires { &Node_T::update; })
249 {
250 SCORE_ASSERT(m_srb->create());
251 SCORE_ASSERT(m_pipeline->create());
252 m_createdPipeline = true;
253 }
254 }
255
256 std::vector<QRhiShaderResourceBinding> tmp;
257 void update(
258 score::gfx::RenderList& renderer, QRhiResourceUpdateBatch& res,
259 score::gfx::Edge* edge) override
260 {
261 // First copy all the "public" uniforms to their space in memory
262 avnd::gpu_uniform_introspection<Node_T>::for_all(
263 avnd::get_inputs<Node_T>(state), [&]<avnd::uniform_port F>(const F& t) {
264 using uniform_type =
265 typename avnd::member_reflection<F::uniform()>::member_type;
266 using ubo_type = typename avnd::member_reflection<F::uniform()>::class_type;
267
268 auto ubo = this->createdUbos.at(ubo_type::binding());
269
270 static constexpr int offset = gpp::std140_offset<F::uniform()>();
271 static constexpr int size = sizeof(uniform_type::value);
272 res.updateDynamicBuffer(ubo, offset, size, &t.value);
273 });
274
275 // Then run the update loop, which is a bit complicated
276 // as we have to take into account that buffers could be allocated, freed, etc.
277 // and thus updated in the shader resource bindings
278
279 if constexpr(requires { &Node_T::update; })
280 {
281 bool srb_touched{false};
282 tmp.assign(m_srb->cbeginBindings(), m_srb->cendBindings());
283 for(auto& promise : state.update())
284 {
285 using ret_type = decltype(promise.feedback_value);
286 gpp::qrhi::handle_update<GpuComputeRenderer, ret_type> handler{
287 *this, *renderer.state.rhi, res, tmp, srb_touched};
288 promise.feedback_value = visit(handler, promise.current_command);
289 }
290
291 if(srb_touched)
292 {
293 if(m_createdPipeline)
294 m_srb->destroy();
295 m_srb->setBindings(tmp.begin(), tmp.end());
296 }
297
298 /*
299 qDebug() << srb_touched << m_createdPipeline;
300 for(auto& b : tmp) {
301 const QRhiShaderResourceBinding::Data& dat = *b.data();
302 switch(dat.type) {
303 case QRhiShaderResourceBinding::UniformBuffer:
304 qDebug() << "ubo: " << dat.binding << (void*) dat.u.ubuf.buf;
305 break;
306 case QRhiShaderResourceBinding::ImageLoad:
307 case QRhiShaderResourceBinding::ImageStore:
308 case QRhiShaderResourceBinding::ImageLoadStore:
309 qDebug() << "image: " << dat.binding << (void*) dat.u.simage.tex;
310 break;
311 case QRhiShaderResourceBinding::BufferLoad:
312 case QRhiShaderResourceBinding::BufferStore:
313 case QRhiShaderResourceBinding::BufferLoadStore:
314 qDebug() << "buffer: " << dat.binding << (void*) dat.u.sbuf.buf;
315 break;
316 default:
317 qDebug() << "WRTF: " << dat.binding;
318 }
319 }
320 */
321
322 if(!m_createdPipeline)
323 {
324 SCORE_ASSERT(m_srb->create());
325 SCORE_ASSERT(m_pipeline->create());
326 m_createdPipeline = true;
327 }
328 tmp.clear();
329 }
330 }
331
332 void release(score::gfx::RenderList& r) override
333 {
334 m_createdPipeline = false;
335
336 // Release the object's internal states
337 if constexpr(requires { &Node_T::release; })
338 {
339 for(auto& promise : state.release())
340 {
341 gpp::qrhi::handle_release handler{*r.state.rhi};
342 visit(handler, promise.current_command);
343 }
344 state.release();
345 }
346
347 // Release the allocated textures
348 for(auto& [id, tex] : this->createdTexs)
349 tex->deleteLater();
350 this->createdTexs.clear();
351
352 // Release the allocated ubos
353 for(auto& [id, ubo] : this->createdUbos)
354 ubo->deleteLater();
355 this->createdUbos.clear();
356
357 // Release the allocated rts
358 // TODO investigate why reference does not work here:
359 // for(auto [port, rt] : m_rts)
360 // rt.release();
361 m_rts.clear();
362
363 // Release the allocated pipelines
364 if(m_srb)
365 m_srb->deleteLater();
366 if(m_pipeline)
367 m_pipeline->deleteLater();
368 m_srb = nullptr;
369 m_pipeline = nullptr;
370
371 m_createdPipeline = false;
372
373 sampler_k = 0;
374 ubo_k = 0;
375 }
376
377 void runCompute(
378 score::gfx::RenderList& renderer, QRhiCommandBuffer& cb,
379 QRhiResourceUpdateBatch*& res)
380 {
381 auto& parent = node();
382 // If we are paused, we don't run the processor implementation.
383 // if(parent.last_message.token.date == m_last_time) {
384 // return;
385 // }
386 // m_last_time = parent.last_message.token.date;
387
388 // Apply the controls
389 parent.processControlIn(
390 *this, this->state, m_last_message, parent.last_message, parent.m_ctx);
391
392 // Run the compute shader
393 {
394 SCORE_ASSERT(this->m_pipeline);
395 SCORE_ASSERT(this->m_pipeline->shaderResourceBindings());
396 for(auto& promise : this->state.dispatch())
397 {
398 using ret_type = decltype(promise.feedback_value);
399 gpp::qrhi::handle_dispatch<GpuComputeRenderer, ret_type> handler{
400 *this, *renderer.state.rhi, cb, res, *this->m_pipeline};
401 promise.feedback_value = visit(handler, promise.current_command);
402 }
403 }
404
405 // Clear the readbacks
406#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
407 for(auto rb : this->bufReadbacks)
408 delete rb;
409 this->bufReadbacks.clear();
410#endif
411 for(auto rb : this->texReadbacks)
412 delete rb;
413 this->texReadbacks.clear();
414
415 // Copy the data to the model node
416 parent.processControlOut(this->state);
417 }
418
419 void runInitialPasses(
420 score::gfx::RenderList& renderer, QRhiCommandBuffer& cb,
421 QRhiResourceUpdateBatch*& res, score::gfx::Edge& edge) override
422 {
423 runCompute(renderer, cb, res);
424 }
425
426 void runRenderPass(
427 score::gfx::RenderList& renderer, QRhiCommandBuffer& commands,
428 score::gfx::Edge& edge) override
429 {
430 }
431};
432
433template <typename Node_T>
435GpuComputeNode<Node_T>::createRenderer(score::gfx::RenderList& r) const noexcept
436{
437 return new GpuComputeRenderer<Node_T>{*this};
438};
439
440}
441#endif
Renderer for a given node.
Definition NodeRenderer.hpp:11
Definition OutputNode.hpp:11
List of nodes to be rendered to an output.
Definition RenderList.hpp:19
RenderState & state
RenderState corresponding to this RenderList.
Definition RenderList.hpp:89
QRhiTexture & emptyTexture() const noexcept
Texture to use when a texture is missing.
Definition RenderList.hpp:112
Definition Factories.hpp:19
QShader makeCompute(const RenderState &v, QString compute)
Compile a compute shader.
Definition score-plugin-gfx/Gfx/Graph/Utils.cpp:399
TextureRenderTarget createRenderTarget(const RenderState &state, QRhiTexture *tex, int samples)
Create a render target from a texture.
Definition score-plugin-gfx/Gfx/Graph/Utils.cpp:10
Definition DocumentContext.hpp:18
Connection between two score::gfx::Port.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:66
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:50
Port of a score::gfx::Node.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:48
Useful abstraction for storing all the data related to a render target.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:111