3#include <avnd/introspection/gfx.hpp>
5#include <Process/ExecutionContext.hpp>
7#include <Crousti/File.hpp>
8#include <Crousti/GppCoroutines.hpp>
9#include <Crousti/GppShaders.hpp>
10#include <Crousti/MessageBus.hpp>
11#include <Crousti/SceneConcepts.hpp>
12#include <Crousti/TextureConversion.hpp>
13#include <Crousti/TextureFormat.hpp>
14#include <Crousti/WorkerBinding.hpp>
15#include <Gfx/GfxExecNode.hpp>
16#include <Gfx/Graph/Node.hpp>
17#include <Gfx/Graph/OutputNode.hpp>
18#include <Gfx/Graph/RenderList.hpp>
19#include <Gfx/Graph/RenderState.hpp>
20#include <Gfx/Graph/RowOrder.hpp>
22#include <score/tools/ThreadPool.hpp>
24#include <ossia/detail/hash_map.hpp>
25#include <ossia/detail/lockfree_queue.hpp>
26#include <ossia/detail/small_flat_map.hpp>
27#include <ossia/detail/small_vector.hpp>
29#include <ossia-qt/invoke.hpp>
31#include <QCoreApplication>
33#include <QtGui/private/qrhi_p.h>
35#include <avnd/binding/ossia/metadatas.hpp>
36#include <avnd/binding/ossia/port_run_postprocess.hpp>
37#include <avnd/binding/ossia/port_run_preprocess.hpp>
38#include <avnd/binding/ossia/soundfiles.hpp>
39#include <avnd/concepts/parameter.hpp>
40#include <avnd/introspection/input.hpp>
41#include <avnd/introspection/output.hpp>
42#include <fmt/format.h>
43#include <gpp/layout.hpp>
44#include <halp/texture.hpp>
46#include <score_plugin_avnd_export.h>
71 std::function<void()> apply;
73 ossia::mpmc_queue<Result> queue;
74 std::atomic<uint64_t> pushed{};
75 std::atomic<int> inflight{};
77 void push(std::function<
void()> f)
79 queue.enqueue(Result{pushed.fetch_add(1, std::memory_order_relaxed), std::move(f)});
84 ossia::small_vector<Result, 4> batch;
86 while(queue.try_dequeue(r))
87 batch.push_back(std::move(r));
88 std::ranges::sort(batch, {}, &Result::order);
89 for(
auto& res : batch)
99 for(
int n = inflight.load(); n > 0; n = inflight.load())
101 if(queue.size_approx() == 0)
112 std::weak_ptr<WorkerResults> results;
116 std::weak_ptr<WorkerResults> results;
117 explicit Job(std::weak_ptr<WorkerResults> r) noexcept
118 : results{std::move(r)}
120 if(
auto p = results.lock())
121 p->inflight.fetch_add(1);
123 Job(Job&& other)
noexcept =
default;
124 Job& operator=(Job&&) =
delete;
127 if(
auto p = results.lock())
129 p->inflight.fetch_sub(1);
130 p->inflight.notify_all();
134 template <
typename F>
135 void operator()(F&& apply)
137 auto r = results.lock();
140 r->push(std::forward<F>(apply));
141 ossia::qt::run_async(QCoreApplication::instance(), [wr = results] {
142 if(
auto r = wr.lock())
147 Job begin() const noexcept {
return Job{results}; }
152 void drainWorker(
bool settle =
false)
const
157 m_workerResults->settle();
159 m_workerResults->drain();
162 template <
typename T>
163 void initWorker(
this auto& self, std::shared_ptr<T>& state)
noexcept
165 if constexpr(avnd::has_worker<T>)
167 if(!self.m_workerResults)
168 self.m_workerResults = std::make_shared<WorkerResults>();
170 bind_worker(*state, std::weak_ptr{state}, Delivery{self.m_workerResults});
174 mutable std::shared_ptr<WorkerResults> m_workerResults;
177#if defined(OSCR_HAS_MMAP_FILE_STORAGE)
184struct GpuRendererFiles
186 template <std::
size_t N, std::
size_t NField>
188 T& state,
const std::shared_ptr<oscr::raw_file_data>& hdl,
189 avnd::predicate_index<N> pred, avnd::field_index<NField> field)
191 m_rawfiles[&state].load(state, hdl, pred, field);
194 void releaseFiles() noexcept { m_rawfiles.clear(); }
197 ossia::hash_map<const T*, oscr::raw_file_storage<T>> m_rawfiles;
201 requires(avnd::raw_file_input_introspection<T>::size == 0)
202struct GpuRendererFiles<T>
204 void releaseFiles() noexcept { }
208struct GpuRendererFiles
210 void releaseFiles() noexcept { }
221struct SCORE_PLUGIN_AVND_EXPORT GpuMessageState
224 std::vector<uint32_t> generation;
229template <
typename GpuNodeRenderer,
typename Node>
233 GpuNodeRenderer& gpu, Node& state,
const GpuMessageState& prev,
237 , prev_mess{prev.message}
239 , prev_gen{prev.generation}
240 , gen{cur.generation}
245 GpuNodeRenderer& gpu;
249 const std::vector<uint32_t>& prev_gen;
250 const std::vector<uint32_t>& gen;
253 bool can_process_message(std::size_t N)
255 if(mess.input.size() <= N)
258 if(prev_mess.input.size() == mess.input.size())
260 auto& prev = prev_mess.input[N];
261 auto& next = mess.input[N];
262 if(prev.index() == 1 && next.index() == 1)
264 if(ossia::get<ossia::value>(prev) == ossia::get<ossia::value>(next))
276 bool received_event(std::size_t N)
const noexcept
278 if(mess.input.size() <= N || gen.size() <= N)
280 return prev_gen.size() <= N || prev_gen[N] != gen[N];
283 template <avnd::parameter_port Field, std::
size_t NField>
284 void operator()(Field& t, avnd::field_index<NField> field_index)
286 if constexpr(avnd::optional_ish<
decltype(Field::value)>)
289 if(!received_event(NField))
292 else if(!can_process_message(field_index))
297 if(
auto val = ossia::get_if<ossia::value>(&mess.input[field_index]))
299 oscr::from_ossia_value(t, *val, t.value);
300 if_possible(t.update(state));
304#if OSCR_HAS_MMAP_FILE_STORAGE
305 template <avnd::raw_file_port Field, std::
size_t NField>
306 void operator()(Field& t, avnd::field_index<NField> field_index)
309 using file_ports = avnd::raw_file_input_introspection<Node>;
311 if(!can_process_message(field_index))
314 auto val = ossia::get_if<ossia::value>(&mess.input[field_index]);
318 static constexpr bool has_text =
requires {
decltype(Field::file)::text; };
319 static constexpr bool has_mmap =
requires {
decltype(Field::file)::mmap; };
322 if(
auto hdl = loadRawfile(*val, ctx, has_text, has_mmap))
324 static constexpr auto N = file_ports::field_index_to_index(NField);
325 if constexpr(avnd::port_can_process<Field>)
329 auto func = executePortPreprocess<Field>(*hdl);
331 state, hdl, avnd::predicate_index<N>{}, avnd::field_index<NField>{});
338 state, hdl, avnd::predicate_index<N>{}, avnd::field_index<NField>{});
344 template <avnd::buffer_port Field, std::
size_t NField>
345 void operator()(Field& t, avnd::field_index<NField> field_index)
347 if(!can_process_message(field_index))
350 using node_type = std::remove_cvref_t<
decltype(gpu.node())>;
351 auto& node =
const_cast<node_type&
>(gpu.node());
352 if(field_index >= mess.input.size())
354 auto val = ossia::get_if<ossia::render_target_spec>(&mess.input[field_index]);
360 template <avnd::texture_port Field, std::
size_t NField>
361 void operator()(Field& t, avnd::field_index<NField> field_index)
363 if(!can_process_message(field_index))
366 using node_type = std::remove_cvref_t<
decltype(gpu.node())>;
367 auto& node =
const_cast<node_type&
>(gpu.node());
368 if(field_index >= mess.input.size())
370 auto val = ossia::get_if<ossia::render_target_spec>(&mess.input[field_index]);
376 template <avnd::geometry_port Field, std::
size_t NField>
377 void operator()(Field& t, avnd::field_index<NField> field_index)
386 template <scene_port Field, std::
size_t NField>
387 void operator()(Field& t, avnd::field_index<NField> field_index)
393 void operator()(
auto& t,
auto field_index) =
delete;
398 template <
typename Self,
typename Node_T>
399 static void processControlIn(
400 Self& self, Node_T& state, GpuMessageState& renderer_mess,
404 avnd::input_introspection<Node_T>::for_all_n(
405 avnd::get_inputs<Node_T>(state),
406 GpuProcessIns<Self, Node_T>{self, state, renderer_mess, mess, ctx});
407 renderer_mess = mess;
413 template <
typename Node_T>
414 static void clearControlIn(Node_T& state)
noexcept
416 avnd::parameter_input_introspection<Node_T>::for_all(
417 avnd::get_inputs<Node_T>(state), []<
typename Field>(Field& t) {
418 if constexpr(avnd::optional_ish<
decltype(Field::value)>)
426 std::weak_ptr<Execution::ExecutionCommandQueue> queue;
427 Gfx::exec_controls control_outs;
440 for(
const auto& [rl, renderer] : n.renderedNodes)
442 if(!rl->output.preview)
447 return !first || first == &r;
450 template <
typename Node_T>
451 void processControlOut(
455 if(!this->control_outs.empty() && drivesControlOuts(r, n))
457 auto q = this->queue.lock();
462 avnd::parameter_output_introspection<Node_T>::for_all(
463 avnd::get_outputs(state), [&]<avnd::parameter_port T>(
const T& t) {
464 qq.enqueue([v = oscr::to_ossia_value(t, t.value),
465 port = control_outs[parm_k]]()
mutable {
466 std::swap(port->value, v);
467 port->changed = true;
477struct SCORE_PLUGIN_AVND_EXPORT GpuNodeElements
479 [[no_unique_address]] oscr::soundfile_storage<T> soundfiles;
481 [[no_unique_address]] oscr::midifile_storage<T> midifiles;
489 :
score::gfx::NodeModel{}
493 virtual ~CustomGfxNodeBase();
495 GpuMessageState last_message;
501 virtual ~CustomGfxOutputNodeBase();
503 GpuMessageState last_message;
506struct SCORE_PLUGIN_AVND_EXPORT CustomGpuNodeBase
513 std::weak_ptr<Execution::ExecutionCommandQueue>&& q, Gfx::exec_controls&& ctls,
515 : GpuControlOuts{
std::move(q),
std::move(ctls)}
520 virtual ~CustomGpuNodeBase() =
default;
523 QString vertex, fragment, compute;
524 GpuMessageState last_message;
528struct SCORE_PLUGIN_AVND_EXPORT CustomGpuOutputNodeBase
537 static constexpr QSize defaultRenderSize{200, 200};
539 CustomGpuOutputNodeBase(
540 std::weak_ptr<Execution::ExecutionCommandQueue> q, Gfx::exec_controls&& ctls,
542 virtual ~CustomGpuOutputNodeBase();
545 std::weak_ptr<score::gfx::RenderList> m_renderer{};
546 std::shared_ptr<score::gfx::RenderState> m_renderState{};
548 QString vertex, fragment, compute;
549 GpuMessageState last_message;
553 void setRenderer(std::shared_ptr<score::gfx::RenderList>)
override;
556 void startRendering()
override;
557 void render()
override;
558 void stopRendering()
override;
559 bool canRender()
const override;
560 void onRendererChange()
override;
564 void destroyOutput()
override;
565 std::shared_ptr<score::gfx::RenderState> renderState()
const override;
567 Configuration configuration() const noexcept override;
570template <typename Node_T, typename Node>
571void prepareNewState(
std::shared_ptr<Node_T>& eff, const Node& parent)
573 if constexpr(avnd::has_worker<Node_T>)
575 parent.initWorker(eff);
577 if constexpr(avnd::has_processor_to_gui_bus<Node_T>)
579 eff->send_message = [ptr = parent.processModel](
auto&& b)
mutable {
583 if(ptr && ptr->to_ui)
584 MessageBusSender{ptr->to_ui}(std::move(b));
591 avnd::init_controls(*eff);
594 if constexpr(
requires { eff->monitor; parent.processModel; })
596 using monitor_type =
typename decltype(Node_T::monitor)::element_type;
597 if(parent.processModel)
598 if(
auto m = std::dynamic_pointer_cast<monitor_type>(parent.processModel->monitor()))
599 eff->monitor = std::move(m);
602 if constexpr(avnd::can_prepare<Node_T>)
604 if constexpr(avnd::function_reflection<&Node_T::prepare>::count == 1)
606 using prepare_type = avnd::first_argument<&Node_T::prepare>;
608 if_possible(t.instance = parent.instance);
618struct port_to_type_enum
620 template <std::
size_t I, avnd::buffer_port F>
621 constexpr auto operator()(avnd::field_reflection<I, F> p)
623 return score::gfx::Types::Buffer;
626 template <std::
size_t I, avnd::cpu_texture_port F>
627 constexpr auto operator()(avnd::field_reflection<I, F> p)
629 using texture_type = std::remove_cvref_t<
decltype(F::texture)>;
630 return (avnd::cpu_fixed_format_texture<texture_type> || avnd::cpu_dynamic_format_texture<texture_type>)
631 ? score::gfx::Types::Image
632 : score::gfx::Types::Buffer;
635 template <std::
size_t I, avnd::gpu_texture_port F>
636 constexpr auto operator()(avnd::field_reflection<I, F> p)
638 return score::gfx::Types::Image;
641 template <std::
size_t I, avnd::sampler_port F>
642 constexpr auto operator()(avnd::field_reflection<I, F> p)
644 return score::gfx::Types::Image;
646 template <std::
size_t I, avnd::image_port F>
647 constexpr auto operator()(avnd::field_reflection<I, F> p)
649 return score::gfx::Types::Image;
651 template <std::
size_t I, avnd::attachment_port F>
652 constexpr auto operator()(avnd::field_reflection<I, F> p)
654 return score::gfx::Types::Image;
656 template <std::
size_t I, avnd::gpu_render_target_output_port F>
657 constexpr auto operator()(avnd::field_reflection<I, F> p)
659 return score::gfx::Types::Image;
662 template <std::
size_t I, avnd::geometry_port F>
663 constexpr auto operator()(avnd::field_reflection<I, F> p)
665 return score::gfx::Types::Geometry;
668 template <std::
size_t I, scene_port F>
669 requires(!avnd::geometry_port<F>)
670 constexpr auto operator()(avnd::field_reflection<I, F> p)
672 return score::gfx::Types::Geometry;
674 template <std::
size_t I, avnd::mono_audio_port F>
675 constexpr auto operator()(avnd::field_reflection<I, F> p)
677 return score::gfx::Types::Audio;
679 template <std::
size_t I, avnd::poly_audio_port F>
680 constexpr auto operator()(avnd::field_reflection<I, F> p)
682 return score::gfx::Types::Audio;
684 template <std::
size_t I, avnd::
int_parameter F>
685 constexpr auto operator()(avnd::field_reflection<I, F> p)
687 return score::gfx::Types::Int;
689 template <std::
size_t I, avnd::enum_parameter F>
690 constexpr auto operator()(avnd::field_reflection<I, F> p)
692 return score::gfx::Types::Int;
694 template <std::
size_t I, avnd::
float_parameter F>
695 constexpr auto operator()(avnd::field_reflection<I, F> p)
697 return score::gfx::Types::Float;
699 template <std::
size_t I, avnd::parameter_port F>
700 constexpr auto operator()(avnd::field_reflection<I, F> p)
702 using value_type = std::remove_cvref_t<
decltype(F::value)>;
704 if constexpr(std::is_array_v<value_type>)
706 static constexpr int sz =
sizeof(value_type) /
sizeof(value_type{}[0]);
707 if constexpr(sz == 2)
709 return score::gfx::Types::Vec2;
711 else if constexpr(sz == 3)
713 return score::gfx::Types::Vec3;
715 else if constexpr(sz == 4)
717 return score::gfx::Types::Vec4;
720 else if constexpr(std::is_aggregate_v<value_type>)
722 static constexpr int sz = avnd::pfr::tuple_size_v<value_type>;
723 if constexpr(sz == 2)
725 return score::gfx::Types::Vec2;
727 else if constexpr(sz == 3)
729 return score::gfx::Types::Vec3;
731 else if constexpr(sz == 4)
733 return score::gfx::Types::Vec4;
736 return score::gfx::Types::Empty;
738 template <std::
size_t I,
typename F>
739 constexpr auto operator()(avnd::field_reflection<I, F> p)
741 return score::gfx::Types::Empty;
753template <
typename Field>
754constexpr score::gfx::Flag port_flags_for_field() noexcept
756 if constexpr(avnd::gpu_texture_port<Field>)
758 constexpr auto kind = halp::texture_kind_of<Field>();
759 constexpr bool nonD2 = (kind != halp::texture_kind::texture_2d);
760 constexpr bool depth = halp::samplable_depth_of<Field>();
762 !(single_cable_port<Field> && (depth || nonD2)),
763 "single_cable is only supported on 2D texture inputs without depth");
764 if constexpr(single_cable_port<Field>)
765 return score::gfx::Flag::SingleCable;
766 else if constexpr(nonD2 && depth)
767 return score::gfx::Flag::GrabsFromSource | score::gfx::Flag::SamplableDepth;
768 else if constexpr(nonD2)
769 return score::gfx::Flag::GrabsFromSource;
770 else if constexpr(depth)
771 return score::gfx::Flag::SamplableDepth;
773 return score::gfx::Flag{};
779inline constexpr halp::gpu_texture::depth_format_t qrhiToHalpDepthFormat(
780 QRhiTexture::Format f)
noexcept
782 using D = halp::gpu_texture::depth_format_t;
785 case QRhiTexture::D16:
return D::D16;
786 case QRhiTexture::D24:
return D::D24;
787 case QRhiTexture::D24S8:
return D::D24S8;
788 case QRhiTexture::D32F:
return D::D32F;
794template <
typename Node_T>
795inline void initGfxPorts(
auto* self,
auto& input,
auto& output)
797 avnd::input_introspection<Node_T>::for_all(
798 [self, &input]<
typename Field, std::size_t I>(avnd::field_reflection<I, Field> f) {
799 static constexpr auto type = port_to_type_enum{}(f);
800 static constexpr auto flags = port_flags_for_field<Field>();
803 avnd::output_introspection<Node_T>::for_all(
805 &output]<
typename Field, std::size_t I>(avnd::field_reflection<I, Field> f) {
806 static constexpr auto type = port_to_type_enum{}(f);
814 output.push_back(
new score::gfx::Port{self, {}, type, score::gfx::Flag{}, {}});
821 const auto& inputs = parent.
input;
825 for(
auto& edge : p->edges)
827 auto src_node = edge->source->node;
831 return src_renderer->bufferForOutput(*edge->source);
840static void readbackInputBuffer(
842 , QRhiResourceUpdateBatch& res
844 , QRhiBufferReadbackResult& readback
850 if(
auto buf = getInputBuffer(renderer, parent, port_index))
853 res.readBackBuffer(buf.handle, buf.byte_offset, buf.byte_size, &readback);
857static void recreateOutputBuffer(
861 const auto bytesize = avnd::get_bytesize(cpu_buf);
866 buf.handle = renderer.state.rhi->newBuffer(
870 QRhiBuffer::StorageBuffer | QRhiBuffer::VertexBuffer),
872 buf.handle->setName(
"GpuUtils::recreateOutputBuffer");
874 buf.byte_size = bytesize;
876 buf.handle->create();
880 cpu_buf.changed =
false;
884 else if(buf.handle->size() != bytesize)
886 buf.handle->destroy();
887 buf.handle->setSize(bytesize);
888 buf.handle->create();
889 buf.byte_size = bytesize;
893static void uploadOutputBuffer(
899 recreateOutputBuffer(renderer, cpu_buf, res, rhi_buf);
901 &res, rhi_buf.handle, 0, cpu_buf.byte_size,
902 (
const char*)avnd::get_bytes(cpu_buf));
903 cpu_buf.changed =
false;
907static void uploadOutputBuffer(
911 rhi_buf.handle =
reinterpret_cast<QRhiBuffer*
>(gpu_buf.handle);
912 rhi_buf.byte_size = gpu_buf.byte_size;
913 rhi_buf.byte_offset = gpu_buf.byte_offset;
917struct geometry_inputs_storage;
919struct mesh_input_storage
921 std::vector<QRhiBufferReadbackResult> readbacks;
922 std::vector<QRhiBuffer*> buffers;
924struct geometry_input_storage
926 ossia::geometry_spec spec;
927 std::vector<mesh_input_storage> meshes;
931 requires(avnd::geometry_input_introspection<T>::size > 0)
932struct geometry_inputs_storage<T>
935 static_assert(avnd::geometry_input_introspection<T>::size == 1);
937 geometry_input_storage inputs[avnd::geometry_input_introspection<T>::size];
938 ossia::small_vector<QRhiBuffer*, 4> allocated;
940 struct pending_transform
942 ossia::transform3d value;
945 pending_transform transforms[avnd::geometry_input_introspection<T>::size];
947 void setTransform(int32_t port,
const ossia::transform3d& v,
auto& state)
949 avnd::geometry_input_introspection<T>::for_all_n2(
950 avnd::get_inputs<T>(state),
951 [&]<
typename Field, std::size_t N, std::size_t NField>(
952 Field&, avnd::predicate_index<N>, avnd::field_index<NField>) {
953 if(int32_t(NField) == port)
954 transforms[N] = {v,
true};
958 void readInputGeometries(
965 avnd::geometry_input_introspection<T>::for_all_n(
966 avnd::get_inputs<T>(state),
967 [&]<
typename Field, std::size_t N>(Field& t, avnd::predicate_index<N> np) {
968 this->inputs[N].spec = spec;
969 this->inputs[N].meshes.resize(1);
972 auto& meshes = this->inputs[N].meshes[0];
983 if constexpr(
requires { t.dirty_mesh; })
985 meshes.buffers.clear();
986 meshes.readbacks.clear();
990 oscr::meshes_from_ossia(
992 [&](
auto& write_buf,
int buffer_index,
void* data, int64_t bytesize) {
994 SCORE_ASSERT(buffer_index >= 0);
995 if(buffer_index < meshes.readbacks.size())
997 QRhiBuffer* handle = meshes.buffers[buffer_index];
998 write_buf.handle = handle;
999 write_buf.byte_size = handle->size();
1001 }, [&](
auto& write_buf,
int buffer_index,
void* handle) {
1003 SCORE_ASSERT(buffer_index >= 0);
1004 if(buffer_index < meshes.readbacks.size())
1007 auto& readback = meshes.readbacks[buffer_index].data;
1008 write_buf.raw_data =
reinterpret_cast<unsigned char*
>(readback.data());
1009 write_buf.byte_size = readback.size();
1013 if constexpr(
requires {
1018 auto& pending = transforms[N];
1021 static_assert(std::extent_v<std::remove_cvref_t<
decltype(t.transform)>> == 16);
1022 std::copy_n(pending.value.matrix, 16, t.transform);
1023 pending.dirty =
false;
1024 t.dirty_transform =
true;
1028 t.dirty_transform =
false;
1032 if constexpr(
requires { t.mesh.buffers[0].handle; })
1034 if(spec.meshes && !spec.meshes->meshes.empty())
1036 const auto& src = spec.meshes->meshes[0].buffers;
1038 = std::min({src.size(), t.mesh.buffers.size(), meshes.buffers.size()});
1039 for(std::size_t i = 0; i < n; i++)
1041 if(!ossia::get_if<ossia::geometry::cpu_buffer>(&src[i].data))
1043 if(QRhiBuffer* handle = meshes.buffers[i])
1045 t.mesh.buffers[i].handle = handle;
1046 t.mesh.buffers[i].byte_size = handle->size();
1054 void inputAboutToFinish(
1056 const ossia::geometry_spec& spec,
auto& state,
auto& parent)
1058 avnd::geometry_input_introspection<T>::for_all_n2(
1059 avnd::get_inputs<T>(state),
1060 [&]<
typename Field, std::size_t N, std::size_t NField>(
1061 Field& t, avnd::predicate_index<N> np, avnd::field_index<NField> nf) {
1062 this->inputs[N].spec = spec;
1063 this->inputs[N].meshes.resize(1);
1066 auto& meshes = this->inputs[N].meshes[0];
1067 auto upload = [&](
int buffer_index,
const void* data, int64_t bytesize) {
1068 if(meshes.buffers.size() <= std::size_t(buffer_index))
1070 meshes.buffers.resize(buffer_index + 1);
1071 meshes.readbacks.resize(buffer_index + 1);
1073 QRhiBuffer*& buf = meshes.buffers[buffer_index];
1074 if(!buf || !ossia::contains(allocated, buf))
1076 buf = renderer.state.rhi->newBuffer(
1079 *renderer.state.rhi,
1080 QRhiBuffer::StorageBuffer | QRhiBuffer::VertexBuffer),
1082 buf->setName(oscr::getUtf8Name<T>() +
"::" + oscr::getUtf8Name(t));
1085 allocated.push_back(buf);
1087 else if(buf->size() < bytesize)
1090 buf->setSize(bytesize);
1094 res->uploadStaticBuffer(buf, 0, bytesize, data);
1096 oscr::meshes_from_ossia(
1097 spec.meshes, t.mesh,
1098 [&](
auto& write_buf,
int buffer_index,
void* data, int64_t bytesize) {
1100 upload(buffer_index, data, bytesize);
1101 }, [&](
auto& write_buf,
int buffer_index,
void* handle) {
1103 if(meshes.readbacks.size() <= buffer_index)
1105 meshes.buffers.resize(buffer_index + 1);
1106 meshes.readbacks.resize(buffer_index + 1);
1109 meshes.readbacks[buffer_index] = {};
1110 if(
auto buf =
static_cast<QRhiBuffer*
>(handle))
1112 meshes.buffers[buffer_index] = buf;
1113 res->readBackBuffer(buf, 0, buf->size(), &meshes.readbacks[buffer_index]);
1117 meshes.buffers[buffer_index] = {};
1118 meshes.readbacks[buffer_index] = {};
1125 if constexpr(
requires { t.mesh.buffers[0].handle; })
1127 if(spec.meshes && !spec.meshes->meshes.empty())
1129 const auto& src = spec.meshes->meshes[0].buffers;
1130 for(std::size_t i = 0; i < src.size(); i++)
1132 auto* cpu = ossia::get_if<ossia::geometry::cpu_buffer>(&src[i].data);
1133 if(!cpu || !cpu->raw_data || cpu->byte_size <= 0)
1135 if(i < meshes.buffers.size() && meshes.buffers[i]
1136 && ossia::contains(allocated, meshes.buffers[i]))
1138 upload(
int(i), cpu->raw_data.get(), cpu->byte_size);
1147 for(
auto& buf : allocated)
1148 renderer.releaseBuffer(buf);
1150 for(
auto& in : inputs)
1155template <
typename T>
1156 requires(avnd::geometry_input_introspection<T>::size == 0)
1157struct geometry_inputs_storage<T>
1159 static void readInputGeometries(
auto&&...) { }
1161 static void inputAboutToFinish(
auto&&...) { }
1163 static void release(
auto&&...) { }
1167struct buffer_inputs_storage;
1170 requires (avnd::buffer_input_introspection<T>::size > 0)
1171struct buffer_inputs_storage<T>
1174 QRhiBufferReadbackResult
1175 m_readbacks[avnd::cpu_buffer_input_introspection<T>::size + 1];
1178 void readInputBuffers(
1181 if constexpr(avnd::cpu_buffer_input_introspection<T>::size > 0)
1186 avnd::cpu_buffer_input_introspection<T>::for_all_n(
1187 avnd::get_inputs<T>(state),
1188 [&]<
typename Field, std::size_t N>
1189 (Field& t, avnd::predicate_index<N> np)
1191 auto& readback = m_readbacks[N].data;
1192 t.buffer.raw_data =
reinterpret_cast<unsigned char*
>(readback.data());
1193 t.buffer.byte_size = readback.size();
1194 t.buffer.byte_offset = 0;
1195 t.buffer.changed =
true;
1199 if constexpr(avnd::gpu_buffer_input_introspection<T>::size > 0)
1204 avnd::gpu_buffer_input_introspection<T>::for_all_n2(
1205 avnd::get_inputs<T>(state),
1206 [&]<
typename Field, std::size_t N, std::size_t NField>(
1207 Field& t, avnd::predicate_index<N> np, avnd::field_index<NField> nf) {
1214 buf = getInputBuffer(renderer, parent, nf);
1217 t.buffer.handle =
nullptr;
1218 t.buffer.byte_size = 0;
1219 t.buffer.byte_offset = 0;
1222 t.buffer.handle = buf.handle;
1223 t.buffer.byte_size = buf.byte_size;
1224 t.buffer.byte_offset = buf.byte_offset;
1230 void inputAboutToFinish(
1232 QRhiResourceUpdateBatch*& res,
1236 avnd::cpu_buffer_input_introspection<T>::for_all_n2(
1237 avnd::get_inputs<T>(state),
1238 [&]<
typename Field, std::size_t N, std::size_t NField>
1239 (Field& port, avnd::predicate_index<N> np, avnd::field_index<NField> nf) {
1240 readbackInputBuffer(renderer, *res, parent, m_readbacks[N], nf);
1242 avnd::gpu_buffer_input_introspection<T>::for_all_n2(
1243 avnd::get_inputs<T>(state),
1244 [&]<
typename Field, std::size_t N, std::size_t NField>
1245 (Field& port, avnd::predicate_index<N> np, avnd::field_index<NField> nf) {
1246 m_gpubufs[N] = getInputBuffer(renderer, parent, nf);
1252 requires (avnd::buffer_input_introspection<T>::size == 0)
1253struct buffer_inputs_storage<T>
1255 static void readInputBuffers(
auto&&...)
1260 static void inputAboutToFinish(
auto&&...)
1272struct buffer_outputs_storage;
1275 requires (avnd::buffer_output_introspection<T>::size > 0)
1276struct buffer_outputs_storage<T>
1278 std::pair<const score::gfx::Port*, MaybeOwnedBuffer>
1279 m_buffers[avnd::buffer_output_introspection<T>::size];
1281 QRhiResourceUpdateBatch* currentResourceUpdateBatch{};
1287 template <
typename Field, std::
size_t N, std::
size_t NField>
1288 requires avnd::cpu_buffer<std::decay_t<
decltype(Field::buffer)>>
1291 avnd::predicate_index<N> np, avnd::field_index<NField> nf)
1293 auto& [gfx_port, buf] = m_buffers[N];
1294 gfx_port = parent.
output[nf];
1295 buf.handle = renderer.state.rhi->newBuffer(
1298 *renderer.state.rhi,
1299 QRhiBuffer::StorageBuffer | QRhiBuffer::VertexBuffer), 1);
1300 buf.handle->setName(oscr::getUtf8Name<T>() +
"::" + oscr::getUtf8Name(port));
1301 buf.byte_offset = 0;
1305 buf.handle->create();
1307 m_renderer = &renderer;
1308 bindUpload(port, np);
1318 template <
typename Field, std::
size_t N>
1319 void bindUpload(Field& port, avnd::predicate_index<N>)
1322 = [
this, &port](
const char* data, int64_t offset, int64_t bytesize) {
1324 SCORE_ASSERT(currentResourceUpdateBatch);
1325 SCORE_ASSERT(m_renderer);
1326 auto& rhi = *m_renderer->state.rhi;
1327 auto& [gfx_port, buf] = m_buffers[N];
1333 buf.handle = rhi.newBuffer(
1336 rhi, QRhiBuffer::StorageBuffer | QRhiBuffer::VertexBuffer),
1338 buf.handle->setName(oscr::getUtf8Name<T>() +
"::" + oscr::getUtf8Name(port));
1339 buf.byte_offset = 0;
1340 buf.byte_size = bytesize;
1343 buf.handle->create();
1347 buf.handle = rhi.newBuffer(
1350 rhi, QRhiBuffer::StorageBuffer | QRhiBuffer::VertexBuffer),
1352 buf.handle->setName(oscr::getUtf8Name<T>() +
"::" + oscr::getUtf8Name(port));
1353 buf.byte_offset = 0;
1357 buf.handle->create();
1361 else if(buf.handle->size() != bytesize)
1363 buf.handle->destroy();
1364 buf.handle->setSize(bytesize);
1365 buf.handle->create();
1366 buf.byte_size = bytesize;
1370 currentResourceUpdateBatch, buf.handle, offset, bytesize, data);
1376 void bindUploads(
auto& state)
1378 avnd::buffer_output_introspection<T>::for_all_n(
1379 avnd::get_outputs<T>(state),
1380 [
this]<
typename Field, std::size_t N>(Field& port, avnd::predicate_index<N> np) {
1381 if constexpr(avnd::cpu_buffer<std::decay_t<
decltype(Field::buffer)>> &&
requires {
1382 port.buffer.upload(
nullptr, 0, 0);
1385 bindUpload(port, np);
1390 template <
typename Field, std::
size_t N, std::
size_t NField>
1391 requires avnd::gpu_buffer<std::decay_t<
decltype(Field::buffer)>>
1394 avnd::predicate_index<N> np, avnd::field_index<NField> nf)
1396 auto& [gfx_port, buf] = m_buffers[N];
1397 gfx_port = parent.
output[nf];
1398 buf.handle =
reinterpret_cast<QRhiBuffer*
>(port.buffer.handle);
1399 buf.byte_size = port.buffer.byte_size;
1400 buf.byte_offset = port.buffer.byte_offset;
1407 avnd::buffer_output_introspection<T>::for_all_n2(
1408 avnd::get_outputs<T>(state), [&]<
typename Field, std::size_t N, std::size_t NField>
1409 (Field& port, avnd::predicate_index<N> np, avnd::field_index<NField> nf) {
1410 SCORE_ASSERT(parent.
output.size() > nf);
1411 SCORE_ASSERT(parent.
output[nf]->type == score::gfx::Types::Buffer);
1412 using buffer_type = std::decay_t<
decltype(port.buffer)>;
1414 if constexpr(avnd::cpu_raw_buffer<buffer_type> &&
requires {
1415 port.buffer.upload(
nullptr, 0, 0);
1418 createOutput(renderer, parent, port, np, nf);
1420 else if constexpr(avnd::gpu_buffer<buffer_type>)
1422 createOutput(renderer, parent, port, np, nf);
1427 static_assert(std::is_same_v<T, void>,
"unsupported");
1432 void prepareUpload(QRhiResourceUpdateBatch& res)
1434 currentResourceUpdateBatch = &res;
1439 avnd::buffer_output_introspection<T>::for_all_n(
1440 avnd::get_outputs<T>(state), [&]<std::size_t N>(
auto& t, avnd::predicate_index<N> idx) {
1441 auto& [port, buf] = m_buffers[N];
1442 uploadOutputBuffer(renderer, t.buffer, res, buf);
1449 for(
auto& [p, buf] : m_buffers)
1452 renderer.releaseBuffer(buf.handle);
1453 buf.handle =
nullptr;
1460 requires (avnd::buffer_output_introspection<T>::size == 0)
1461struct buffer_outputs_storage<T>
1463 static void init(
auto&&...)
1468 static void prepareUpload(
auto&&...)
1472 static void bindUploads(
auto&&...)
1476 static void upload(
auto&&...)
1480 static void release(
auto&&...)
1486template <
typename Tex>
1490 auto& rhi = *renderer.state.rhi;
1491 QRhiTexture* texture = &renderer.emptyTexture();
1492 if(size.width() > 0 && size.height() > 0)
1496 texture = rhi.newTexture(
1497 gpp::qrhi::textureFormat(texture_spec), size, 1,
1498 QRhiTexture::UsedAsTransferSource);
1503 auto sampler = rhi.newSampler(
1504 QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
1505 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
1513struct texture_inputs_storage;
1516 requires (avnd::texture_input_introspection<T>::size > 0)
1517struct texture_inputs_storage<T>
1519 ossia::small_flat_map<const score::gfx::Port*, score::gfx::TextureRenderTarget, 2>
1521 ossia::small_flat_map<const score::gfx::Port*, QRhiSampler*, 2> m_samplers;
1523 QRhiReadbackResult m_readbacks[avnd::texture_input_introspection<T>::size];
1524 bool m_readbackPremultiplied[avnd::texture_input_introspection<T>::size]{};
1526 template <
typename Tex>
1527 QRhiTexture* createInput(
1530 bool mipmapped =
false)
1532 QRhiTexture::Flags flags
1533 = QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource;
1535 flags |= QRhiTexture::MipMapped | QRhiTexture::UsedWithGenerateMips;
1536 QRhiTexture::Format fmt{};
1537 if constexpr(
requires (Tex tex) { tex.format = {}; } && !
requires (Tex tex) { tex.request_format; })
1541 gpp::qrhi::toTextureFormat(fmt, texture_spec);
1545 fmt = gpp::qrhi::textureFormat(texture_spec);
1548 QRhiTexture* texture = renderer.state.rhi->newTexture(
1549 fmt, spec.size, 1, flags);
1551 SCORE_ASSERT(texture->create());
1556 const bool wantsDepth = renderer.requiresDepth(*port) || wantsSamplableDepth;
1558 renderer.state, texture, renderer.samples(),
1559 wantsDepth, wantsSamplableDepth);
1566 avnd::texture_input_introspection<T>::for_all_n2(
1567 avnd::get_inputs<T>(*self.state),
1568 [&]<
typename F, std::size_t K, std::size_t N>(F& t, avnd::predicate_index<K>, avnd::field_index<N>) {
1575 if constexpr(avnd::gpu_texture_port<F>
1576 && halp::texture_kind_of<F>() != halp::texture_kind::texture_2d)
1578 t.texture.kind = halp::texture_kind_of<F>();
1584 auto& parent = self.node();
1585 auto spec = renderer.resolveInputRenderTargetSpecs(parent, N);
1586 if constexpr(
requires {
1591 spec.size.rwidth() = t.request_width;
1592 spec.size.rheight() = t.request_height;
1595 constexpr bool wantsSamplableDepth
1596 = avnd::gpu_texture_port<F> && halp::samplable_depth_of<F>();
1597 if constexpr(avnd::gpu_texture_port<F>)
1599 if(!single_cable_port<F> || singleCableNeedsTarget(renderer, *parent.
input[N]))
1601 renderer, parent.
input[N], t.texture, spec, wantsSamplableDepth,
1602 spec.mipmap_mode != QRhiSampler::None);
1603 auto* sampler = renderer.state.rhi->newSampler(
1604 spec.mag_filter, spec.min_filter, spec.mipmap_mode, spec.address_u,
1605 spec.address_v, spec.address_w);
1606 sampler->setName(
"texture_inputs_storage::sampler");
1608 m_samplers[parent.
input[N]] = sampler;
1612 createInput(renderer, parent.
input[N], t.texture, spec, wantsSamplableDepth);
1614 if constexpr(avnd::cpu_texture_port<F>)
1616 t.texture.width = spec.size.width();
1617 t.texture.height = spec.size.height();
1621 refreshGpuInputs(self, renderer);
1624 static std::pair<bool, QRhiTexture*> upstreamTexture(
1629 QRhiTexture* direct =
nullptr;
1630 for(
auto* edge : port.edges)
1632 if(!edge || !edge->source || !edge->source->node)
1634 auto& rendered = edge->source->node->renderedNodes;
1635 auto it = rendered.find(&renderer);
1636 if(it == rendered.end() || !it->second)
1639 direct = it->second->textureForOutput(*edge->source);
1641 if(wired != 1 || needsOwnTarget || node.hasExplicitRenderTargetSpecs(index))
1643 return {wired > 0, direct};
1649 for(
auto* edge : port.edges)
1651 if(!edge || !edge->source || !edge->source->node)
1653 auto& rendered = edge->source->node->renderedNodes;
1654 auto it = rendered.find(&renderer);
1655 if(it == rendered.end() || !it->second)
1657 return it->second->textureForOutput(*edge->source);
1665 return !port.edges.empty() && !singleCableTexture(renderer, port);
1671 for(
auto* edge : port.edges)
1673 if(!edge || !edge->source || !edge->source->node)
1675 auto& rendered = edge->source->node->renderedNodes;
1676 if(
auto it = rendered.find(&renderer);
1677 it != rendered.end() && it->second && it->second->hasOutputPassForEdge(*edge))
1685 if(
auto it = m_rts.find(port); it != m_rts.end())
1687 renderer.releaseOwnedTarget(it->second);
1692 QRhiSampler* refreshSampler(
1696 auto it = m_samplers.find(port);
1697 if(it == m_samplers.end() || !it->second)
1699 auto* sampler = it->second;
1700 const auto spec = node.resolveRenderTargetSpecs(index, renderer);
1701 if(sampler->magFilter() != spec.mag_filter || sampler->minFilter() != spec.min_filter
1702 || sampler->mipmapMode() != spec.mipmap_mode
1703 || sampler->addressU() != spec.address_u || sampler->addressV() != spec.address_v
1704 || sampler->addressW() != spec.address_w)
1707 sampler->setMagFilter(spec.mag_filter);
1708 sampler->setMinFilter(spec.min_filter);
1709 sampler->setMipmapMode(spec.mipmap_mode);
1710 sampler->setAddressU(spec.address_u);
1711 sampler->setAddressV(spec.address_v);
1712 sampler->setAddressW(spec.address_w);
1718 static void describeTexture(halp::gpu_texture& dst, QRhiTexture& tex)
1720 const auto sz = tex.pixelSize();
1722 dst.width = sz.width();
1723 dst.height = sz.height();
1724 gpp::qrhi::toTextureFormat(tex.format(), dst);
1725 const auto flags = tex.flags();
1726 if(flags & QRhiTexture::CubeMap)
1728 dst.kind = halp::texture_kind::cubemap;
1729 dst.layers_or_depth = 6;
1731 else if(flags & QRhiTexture::ThreeDimensional)
1733 dst.kind = halp::texture_kind::texture_3d;
1734 dst.layers_or_depth = tex.depth();
1736 else if(flags & QRhiTexture::TextureArray)
1738 dst.kind = halp::texture_kind::texture_array;
1739 dst.layers_or_depth = tex.arraySize();
1743 dst.kind = halp::texture_kind::texture_2d;
1744 dst.layers_or_depth = 1;
1750 avnd::texture_input_introspection<T>::for_all_n2(
1751 avnd::get_inputs<T>(*self.state),
1752 [&]<
typename F, std::size_t K, std::size_t N>(
1753 F& t, avnd::predicate_index<K>, avnd::field_index<N>) {
1755 avnd::gpu_texture_port<F>
1756 && halp::texture_kind_of<F>() == halp::texture_kind::texture_2d)
1758 constexpr bool wantsSamplableDepth = halp::samplable_depth_of<F>();
1759 auto* port = self.node().input[N];
1760 auto& tex = t.texture;
1761 const auto rt_it = m_rts.find(port);
1762 const bool mipmapped
1763 = rt_it != m_rts.end() && rt_it->second.texture
1764 && rt_it->second.texture->flags().testFlag(QRhiTexture::MipMapped);
1765 tex.sampler_handle = refreshSampler(self.node(), N, renderer, port);
1767 QRhiTexture* src = nullptr;
1768 if constexpr(single_cable_port<F>)
1770 src = singleCableTexture(renderer, *port);
1773 if(rt_it != m_rts.end() && !composited(renderer, *port))
1774 releaseTarget(renderer, port);
1776 else if(!port->edges.empty() && rt_it != m_rts.end())
1778 src = rt_it->second.texture;
1781 else if(auto [wired, direct]
1782 = upstreamTexture(renderer, self.node(), N, *port, mipmapped);
1785 if constexpr(!wantsSamplableDepth)
1787 if(!src && rt_it != m_rts.end())
1788 src = rt_it->second.texture;
1793 tex.handle = nullptr;
1796 tex.kind = halp::texture_kind::texture_2d;
1797 tex.layers_or_depth = 1;
1798 if constexpr(wantsSamplableDepth)
1799 tex.depth_handle = nullptr;
1803 describeTexture(tex, *src);
1804 if constexpr(wantsSamplableDepth)
1806 auto* depth = rt_it->second.depthTexture;
1807 tex.depth_handle = depth;
1809 tex.depth_format = qrhiToHalpDepthFormat(depth->format());
1815 bool update(
auto& self,
1818 avnd::texture_input_introspection<T>::for_all_n2(
1819 avnd::get_inputs<T>(*self.state),
1820 [&]<
typename F, std::size_t K, std::size_t N>(
1821 F& t, avnd::predicate_index<K>, avnd::field_index<N>) {
1822 if constexpr(single_cable_port<F> && avnd::gpu_texture_port<F>)
1824 auto& parent = self.node();
1825 auto* port = parent.input[N];
1826 if(m_rts.find(port) != m_rts.end() || !singleCableNeedsTarget(renderer, *port))
1828 auto spec = renderer.resolveInputRenderTargetSpecs(parent, N);
1829 if constexpr(requires {
1834 spec.size.rwidth() = t.request_width;
1835 spec.size.rheight() = t.request_height;
1838 renderer, port, t.texture, spec, false,
1839 spec.mipmap_mode != QRhiSampler::None);
1840 for(auto* edge : port->edges)
1842 auto& rendered = edge->source->node->renderedNodes;
1843 if(auto it = rendered.find(&renderer); it != rendered.end() && it->second)
1845 it->second->removeOutputPass(renderer, *edge);
1846 it->second->addOutputPass(renderer, *edge, res);
1852 bool need_update =
false;
1853 avnd::texture_input_introspection<T>::for_all_n2(
1854 avnd::get_inputs<T>(*self.state),
1855 [&]<
typename F, std::size_t K, std::size_t N>(F& t, avnd::predicate_index<K>, avnd::field_index<N>) {
1856 if constexpr(requires {
1861 auto& parent = self.node();
1862 auto port = parent.
input[N];
1866 sz = texture.texture->pixelSize();
1867 if(sz.width() != t.request_width || sz.height() != t.request_height)
1895 template <
typename F>
1896 static constexpr bool reads_upstream_directly() noexcept
1898 using Tex = std::decay_t<
decltype(F::texture)>;
1899 return avnd::cpu_texture_port<F>
1900 &&
requires(Tex tex) { tex.format = {}; }
1901 && !
requires(Tex tex) { tex.request_format; }
1902 && !
requires(F f) { f.request_width; };
1907 auto& rhi = *renderer.state.rhi;
1908 refreshGpuInputs(self, renderer);
1914 if constexpr(avnd::cpu_texture_input_introspection<T>::size > 0)
1916 avnd::texture_input_introspection<T>::for_all_n(
1917 avnd::get_inputs<T>(*self.state), [&]<
typename F, std::size_t K>(F& t, avnd::predicate_index<K>) {
1918 if constexpr(avnd::cpu_texture_port<F>)
1920 if constexpr(reads_upstream_directly<F>())
1922 const auto& rb = m_readbacks[K];
1923 if(!rb.pixelSize.isEmpty())
1925 t.texture.width = rb.pixelSize.width();
1926 t.texture.height = rb.pixelSize.height();
1927 gpp::qrhi::toTextureFormat(rb.format, t.texture);
1930 if(auto& rb = m_readbacks[K]; m_readbackPremultiplied[K] && !rb.data.isEmpty())
1932 gpp::qrhi::unpremultiply(
1933 rb.format, rb.data, rb.pixelSize.width(), rb.pixelSize.height());
1934 m_readbackPremultiplied[K] = false;
1936 oscr::loadInputTexture(rhi, m_readbacks, t.texture, K);
1946 for(
auto [port, rt] : m_rts)
1949 for(
auto [port, sampler] : m_samplers)
1950 sampler->deleteLater();
1954 void inputAboutToFinish(
1956 QRhiResourceUpdateBatch*& res)
1958 if constexpr(avnd::cpu_texture_input_introspection<T>::size > 0)
1960 const auto& inputs = self.node().input;
1961 avnd::texture_input_introspection<T>::for_all_n2(
1962 avnd::get_inputs<T>(*self.state),
1963 [&]<
typename F, std::size_t K, std::size_t N>(
1964 F&, avnd::predicate_index<K>, avnd::field_index<N>) {
1965 if constexpr(avnd::cpu_texture_port<F>)
1967 if(N >= inputs.size() || inputs[N] != &p)
1969 auto rt_it = m_rts.find(&p);
1970 if(rt_it == m_rts.end())
1972 QRhiTexture* tex = rt_it->second.texture;
1973 if constexpr(reads_upstream_directly<F>())
1975 auto [wired, direct] = upstreamTexture(renderer, self.node(), N, p);
1976 if(direct && direct->sampleCount() <= 1
1977 && (direct->flags() & QRhiTexture::UsedAsTransferSource)
1978 && !(direct->flags()
1979 & (QRhiTexture::CubeMap | QRhiTexture::ThreeDimensional
1980 | QRhiTexture::TextureArray)))
1985 auto& readback = m_readbacks[K];
1987 m_readbackPremultiplied[K] = tex == rt_it->second.texture;
1988 res->readBackTexture(QRhiReadbackDescription{tex}, &readback);
1996 requires (avnd::texture_input_introspection<T>::size == 0)
1997struct texture_inputs_storage<T>
1999 static void init(
auto&&...) { }
2000 static void runInitialPasses(
auto&&...) { }
2001 static void release(
auto&&...) { }
2002 static void inputAboutToFinish(
auto&&...) { }
2007template <avnd::cpu_texture Tex>
2008static QRhiTexture* updateTexture(
auto& self,
score::gfx::RenderList& renderer,
int k,
const Tex& cpu_tex)
2010 auto& sampler = self.m_samplers[k].sampler;
2011 auto& texture = self.m_samplers[k].texture;
2014 auto sz = texture->pixelSize();
2015 if(cpu_tex.width == sz.width() && cpu_tex.height == sz.height())
2020 if(cpu_tex.width > 0 && cpu_tex.height > 0)
2022 QRhiTexture* oldtex = texture;
2023 QRhiTexture* newtex = renderer.state.rhi->newTexture(
2024 gpp::qrhi::textureFormat(cpu_tex), QSize{cpu_tex.width, cpu_tex.height}, 1,
2025 QRhiTexture::UsedAsTransferSource);
2027 for(
auto& [edge, pass] : self.m_p)
2029 score::gfx::replaceTexture(*pass.p.srb, sampler, newtex);
2032 if(oldtex && oldtex != &renderer.emptyTexture())
2034 oldtex->deleteLater();
2041 for(
auto& [edge, pass] : self.m_p)
2043 score::gfx::replaceTexture(*pass.p.srb, sampler, &renderer.emptyTexture());
2045 return &renderer.emptyTexture();
2049template <avnd::cpu_texture Tex>
2050static void uploadOutputTexture(
auto& self,
2052 QRhiResourceUpdateBatch* res)
2056 if(
auto texture = updateTexture(self, renderer, k, cpu_tex))
2058 if(!cpu_tex.bytes || cpu_tex.bytesize() <= 0)
2060 cpu_tex.changed =
false;
2065 = QByteArray::fromRawData((
const char*)cpu_tex.bytes, cpu_tex.bytesize());
2066 if constexpr(
requires { Tex::RGB; })
2070 const QByteArray rgb = buf;
2072 rgba.resize(cpu_tex.width * cpu_tex.height * 4);
2073 auto src = (
const unsigned char*)rgb.constData();
2074 auto dst = (
unsigned char*)rgba.data();
2075 for(
int rgb_byte = 0, rgba_byte = 0, N = rgb.size(); rgb_byte < N;)
2077 dst[rgba_byte + 0] = src[rgb_byte + 0];
2078 dst[rgba_byte + 1] = src[rgb_byte + 1];
2079 dst[rgba_byte + 2] = src[rgb_byte + 2];
2080 dst[rgba_byte + 3] = 255;
2090 *renderer.state.rhi, std::move(buf), cpu_tex.height);
2092 QRhiTextureSubresourceUploadDescription sd(buf);
2093 QRhiTextureUploadDescription desc{QRhiTextureUploadEntry{0, 0, sd}};
2095 res->uploadTexture(texture, desc);
2098 cpu_tex.changed =
false;
2109static const constexpr auto generic_texgen_vs = R
"_(#version 450
2110layout(location = 0) in vec2 position;
2111layout(location = 1) in vec2 texcoord;
2113layout(binding=3) uniform sampler2D y_tex;
2114layout(location = 0) out vec2 v_texcoord;
2116layout(std140, binding = 0) uniform renderer_t {
2117 mat4 clipSpaceCorrMatrix;
2121out gl_PerVertex { vec4 gl_Position; };
2125#if defined(QSHADER_SPIRV) || defined(QSHADER_HLSL) || defined(QSHADER_MSL)
2126 v_texcoord = vec2(texcoord.x, 1. - texcoord.y);
2128 v_texcoord = texcoord;
2130 gl_Position = renderer.clipSpaceCorrMatrix * vec4(position.xy, 0.0, 1.);
2134static const constexpr auto generic_texgen_fs = R
"_(#version 450
2135layout(location = 0) in vec2 v_texcoord;
2136layout(location = 0) out vec4 fragColor;
2138layout(std140, binding = 0) uniform renderer_t {
2139mat4 clipSpaceCorrMatrix;
2143layout(binding=3) uniform sampler2D y_tex;
2147 fragColor = texture(y_tex, v_texcoord);
2152struct texture_outputs_storage;
2156 requires (avnd::texture_output_introspection<T>::size > 0)
2157struct texture_outputs_storage<T>
2159 static bool drawnOutputPremultiplied(
auto& self)
noexcept
2161 bool premultiplied =
false;
2162 const auto first = [&]<
typename F, std::size_t N>(F&, avnd::predicate_index<N>) {
2163 if constexpr(N == 0)
2164 premultiplied =
requires { F::premultiplied; };
2166 if constexpr(avnd::cpu_texture_output_introspection<T>::size > 0)
2167 avnd::cpu_texture_output_introspection<T>::for_all_n(
2168 avnd::get_outputs<T>(*self.state), first);
2170 avnd::gpu_texture_output_introspection<T>::for_all_n(
2171 avnd::get_outputs<T>(*self.state), first);
2172 return premultiplied;
2177 const auto& mesh = renderer.defaultTriangle();
2178 self.defaultMeshInit(renderer, mesh, res);
2179 self.processUBOInit(renderer);
2184 renderer.state, generic_texgen_vs, generic_texgen_fs);
2186 avnd::cpu_texture_output_introspection<T>::for_all(
2187 avnd::get_outputs<T>(*self.state), [&](
auto& t) {
2188 self.m_samplers.push_back(
2189 createOutputTexture(renderer, t.texture, QSize{t.texture.width, t.texture.height}));
2192 gpu_first = self.m_samplers.size();
2193 avnd::gpu_texture_output_introspection<T>::for_all(
2194 avnd::get_outputs<T>(*self.state), [&](
auto&) {
2195 auto sampler = renderer.state.rhi->newSampler(
2196 QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
2197 QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
2199 self.m_samplers.push_back(score::gfx::Sampler{sampler, nullptr});
2202 self.m_outputPremultiplied = drawnOutputPremultiplied(self);
2203 self.defaultPassesInit(renderer, mesh);
2208 for(
auto* port : self.node().output)
2210 if(!port || port->type != score::gfx::Types::Image)
2212 for(
auto* edge : port->edges)
2213 if(!self.hasOutputPassForEdge(*edge))
2214 self.addOutputPass(renderer, *edge, res);
2218 void runInitialPasses(
auto& self,
2220 QRhiResourceUpdateBatch*& res)
2222 avnd::cpu_texture_output_introspection<T>::for_all_n(
2223 avnd::get_outputs<T>(*self.state), [&]<std::size_t N>(
auto& t, avnd::predicate_index<N>) {
2224 uploadOutputTexture(self, renderer, N, t.texture, res);
2227 std::size_t k = gpu_first;
2228 avnd::gpu_texture_output_introspection<T>::for_all(
2229 avnd::get_outputs<T>(*self.state), [&](
auto& t) {
2230 auto* tex = static_cast<QRhiTexture*>(t.texture.handle);
2233 & (QRhiTexture::CubeMap | QRhiTexture::ThreeDimensional
2234 | QRhiTexture::TextureArray)))
2236 auto& sampler = self.m_samplers[k];
2237 if(tex != sampler.texture)
2239 sampler.texture = tex;
2240 for(auto& [edge, pass] : self.m_p)
2242 if(!pass.p.srb || !edge)
2246 const auto bound = self.samplersForOutputEdge(*edge);
2247 if(bound.size() == 1)
2249 if(bound.data() == &sampler)
2250 score::gfx::replaceTexture(
2251 *pass.p.srb, 3, tex ? tex : &renderer.emptyTexture());
2255 score::gfx::replaceTexture(
2256 *pass.p.srb, int(3 + k), tex ? tex : &renderer.emptyTexture());
2266 for(std::size_t i = 0; i < self.m_samplers.size(); i++)
2268 auto& texture = self.m_samplers[i].texture;
2270 texture->deleteLater();
2275 std::size_t gpu_first{};
2280 requires (avnd::texture_output_introspection<T>::size == 0)
2281struct texture_outputs_storage<T>
2287 static void runInitialPasses(
auto& self,
2289 QRhiResourceUpdateBatch*& res)
2298struct geometry_outputs_storage;
2301 requires (avnd::geometry_output_introspection<T>::size > 0)
2302struct geometry_outputs_storage<T>
2304 ossia::geometry_spec specs[avnd::geometry_output_introspection<T>::size];
2306 struct sent_transform
2308 std::optional<ossia::transform3d> value;
2309 std::vector<std::pair<const score::gfx::Edge*, const score::gfx::NodeRenderer*>>
2312 sent_transform transforms[avnd::geometry_output_introspection<T>::size];
2314 template <avnd::geometry_port Field>
2315 void reload_mesh(Field& ctrl, ossia::geometry_spec& spc)
2317 spc.meshes = std::make_shared<ossia::mesh_list>();
2318 auto& ossia_meshes = *spc.meshes;
2319 if constexpr(avnd::static_geometry_type<Field> || avnd::dynamic_geometry_type<Field>)
2321 ossia_meshes.meshes.resize(1);
2322 load_geometry(ctrl, ossia_meshes.meshes[0]);
2325 avnd::static_geometry_type<
decltype(Field::mesh)>
2326 || avnd::dynamic_geometry_type<
decltype(Field::mesh)>)
2328 ossia_meshes.meshes.resize(1);
2329 load_geometry(ctrl.mesh, ossia_meshes.meshes[0]);
2333 load_geometry(ctrl, ossia_meshes);
2337 template <avnd::geometry_port Field, std::
size_t N>
2340 avnd::predicate_index<N>)
2342 auto edge_sink = edge.sink;
2343 if(
auto pnode = edge_sink->node)
2345 ossia::geometry_spec& spc = specs[N];
2351 reload_mesh(ctrl, spc);
2357 auto& ossia_meshes = *spc.meshes;
2359 bool any_need_reload =
false;
2360 bool any_need_upload =
false;
2361 if constexpr(avnd::static_geometry_type<Field> || avnd::dynamic_geometry_type<Field>)
2363 SCORE_ASSERT(ossia_meshes.meshes.size() == 1);
2364 auto [need_reload, need_upload]
2365 = update_geometry(ctrl, ossia_meshes.meshes[0]);
2366 any_need_reload = need_reload;
2367 any_need_upload = need_upload;
2370 avnd::static_geometry_type<
decltype(Field::mesh)>
2371 || avnd::dynamic_geometry_type<
decltype(Field::mesh)>)
2373 SCORE_ASSERT(ossia_meshes.meshes.size() == 1);
2374 auto [need_reload, need_upload]
2375 = update_geometry(ctrl.mesh, ossia_meshes.meshes[0]);
2376 any_need_reload = need_reload;
2377 any_need_upload = need_upload;
2381 auto [need_reload, need_upload] = update_geometry(ctrl, ossia_meshes);
2382 any_need_reload = need_reload;
2383 any_need_upload = need_upload;
2388 reload_mesh(ctrl, spc);
2392 ctrl.dirty_mesh =
false;
2398 auto rendered_node = pnode->renderedNodes.find(&renderer);
2399 SCORE_ASSERT(rendered_node != pnode->renderedNodes.end());
2401 auto it = std::find(
2402 edge_sink->node->input.begin(), edge_sink->node->input.end(), edge_sink);
2403 SCORE_ASSERT(it != edge_sink->node->input.end());
2404 int n = it - edge_sink->node->input.begin();
2406 rendered_node->second->process(n, spc, edge.source);
2410 if constexpr(
requires { ctrl.transform; })
2412 auto& sent = transforms[N];
2413 if(ctrl.dirty_transform)
2415 sent.value.emplace();
2416 std::copy_n(ctrl.transform, std::ssize(ctrl.transform), sent.value->matrix);
2417 sent.receivers.clear();
2418 ctrl.dirty_transform =
false;
2421 const std::pair<const score::gfx::Edge*, const score::gfx::NodeRenderer*>
2422 receiver{&edge, rendered_node->second};
2423 if(sent.value && !ossia::contains(sent.receivers, receiver))
2425 sent.receivers.push_back(receiver);
2426 rendered_node->second->process(n, *sent.value);
2428 pnode->process(n, *sent.value);
2437 avnd::geometry_output_introspection<T>::for_all_n(
2438 avnd::get_outputs(state),
2439 [&](
auto& field,
auto pred) { this->upload(renderer, field, edge, pred); });
2450 requires (avnd::geometry_output_introspection<T>::size == 0)
2451struct geometry_outputs_storage<T>
2453 static void upload(
auto&&...)
2457 static void release(
auto&&...) noexcept { }
2464template <
typename Field>
2465using is_scene_port_t = boost::mp11::mp_bool<scene_port<Field>>;
2467template <
typename T>
2468using scene_output_introspection =
2469 avnd::predicate_introspection<typename avnd::outputs_type<T>::type, is_scene_port_t>;
2471template <
typename T>
2472using scene_input_introspection =
2473 avnd::predicate_introspection<typename avnd::inputs_type<T>::type, is_scene_port_t>;
2481template <
typename T>
2482struct scene_inputs_storage;
2484template <
typename T>
2485 requires(scene_input_introspection<T>::size > 0)
2486struct scene_inputs_storage<T>
2490 ossia::small_vector<std::pair<const ossia::scene_state*, int64_t>, 4> inputs;
2491 ossia::scene_spec merged;
2493 port_cache m_cache[scene_input_introspection<T>::size];
2495 static ossia::scene_spec
2498 ossia::small_vector<std::pair<const ossia::scene_state*, int64_t>, 4> sig;
2499 ossia::small_vector<ossia::scene_spec, 4> scenes;
2500 renderer.forEachSceneOnPort(port, [&](
const ossia::scene_spec& s) {
2501 sig.push_back({s.state.get(), s.state->version});
2502 scenes.push_back(s);
2510 if(scenes.size() == 1)
2515 if(sig == cache.inputs && cache.merged.state)
2516 return cache.merged;
2518 cache.inputs.assign(sig.begin(), sig.end());
2519 cache.merged = ossia::merge_scenes(
2520 std::span<const ossia::scene_spec>{scenes.data(), scenes.size()});
2521 return cache.merged;
2526 if constexpr(scene_input_introspection<T>::size == 1)
2528 scene_input_introspection<T>::for_all(
2529 avnd::get_inputs<T>(state), [&](
auto& field) { field.scene = renderer.scene; });
2532 scene_input_introspection<T>::for_all_n2(
2533 avnd::get_inputs<T>(state),
2534 [&]<
typename F, std::size_t K, std::size_t N>(
2535 F& field, avnd::predicate_index<K>, avnd::field_index<N>) {
2536 field.scene = sceneOnPort(renderer,
int(N), m_cache[K]);
2542 for(
auto& c : m_cache)
2547template <
typename T>
2548 requires(scene_input_introspection<T>::size == 0)
2549struct scene_inputs_storage<T>
2551 static void readInputScenes(
auto&&...) { }
2552 static void release(
auto&&...) { }
2555template <
typename T>
2556struct scene_outputs_storage;
2558template <
typename T>
2559 requires(scene_output_introspection<T>::size > 0)
2560struct scene_outputs_storage<T>
2562 template <scene_port Field, std::
size_t N>
2565 avnd::predicate_index<N>)
2572 if(!ctrl.scene.state)
2575 auto* edge_sink = edge.sink;
2576 if(!edge_sink || !edge_sink->node)
2580 if(rendered_node == edge_sink->node->renderedNodes.end())
2583 auto it = std::find(
2584 edge_sink->node->input.begin(), edge_sink->node->input.end(), edge_sink);
2585 if(it == edge_sink->node->input.end())
2587 int n = it - edge_sink->node->input.begin();
2594 rendered_node->second->process(n, ctrl.scene, edge.source);
2596 if constexpr(
requires { ctrl.dirty; })
2602 scene_output_introspection<T>::for_all_n(
2603 avnd::get_outputs(state),
2604 [&](
auto& field,
auto pred) { this->upload(renderer, field, edge, pred); });
2616template <
typename T>
2617 requires(scene_output_introspection<T>::size == 0)
2618struct scene_outputs_storage<T>
2620 static void upload(
auto&&...) { }
2621 static void release(
auto&&...) noexcept { }
Root data model for visual nodes.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:115
std::vector< Port * > input
Input ports of that node.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:144
ossia::flat_map< RenderList *, score::gfx::NodeRenderer * > renderedNodes
Map associating each RenderList to a Renderer for this model.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:155
virtual void process(Message &&msg)
Process a message from the execution engine.
Definition score-plugin-gfx/Gfx/Graph/Node.cpp:25
ossia::small_pod_vector< Port *, 1 > output
Output ports of that node.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:150
Common base class for most single-pass, simple nodes.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:329
Renderer for a given node.
Definition NodeRenderer.hpp:11
Base class for sink nodes (QWindow, spout, syphon, NDI output, ...)
Definition OutputNode.hpp:56
Common base class for nodes that map to score processes.
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:266
List of nodes to be rendered to an output.
Definition RenderList.hpp:36
static void noteBufferLive(const QRhiBuffer *buf) noexcept
Definition RenderList.cpp:1178
QRhiTexture & emptyTexture() const noexcept
Texture to use when a texture is missing (2D)
Definition RenderList.hpp:329
TreeNode< DeviceExplorerNode > Node
Definition DeviceNode.hpp:74
void settle(::State::Address &a, const score::DocumentContext &ctx)
Definition ScriptableReference.cpp:121
Definition Controls.hpp:31
void bind_worker(Object &obj, std::weak_ptr< Object > obj_wp, Delivery deliver)
Definition WorkerBinding.hpp:31
std::pair< QShader, QShader > makeShaders(const RenderState &v, QString vert, QString frag, int multiViewCount)
Get a pair of compiled vertex / fragment shaders from GLSL 4.5 sources.
Definition score-plugin-gfx/Gfx/Graph/Utils.cpp:1707
TextureRenderTarget createRenderTarget(const RenderState &state, QRhiTexture *tex, int samples, bool depth, bool samplableDepth)
Create a render target from a texture.
Definition score-plugin-gfx/Gfx/Graph/Utils.cpp:86
void uploadStaticBufferWithStoredData(QRhiResourceUpdateBatch *ub, QRhiBuffer *buf, int offset, int64_t bytesize, const char *data)
Schedule a Static buffer update when we can guarantee the buffer outlives the frame.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:1065
QByteArray bytesInPublishedRowOrder(const QRhi &rhi, QByteArray bytes, int rows)
Definition RowOrder.hpp:47
QRhiBuffer::UsageFlags compatibleBufferUsage(QRhi &rhi, QRhiBuffer::UsageFlags usage) noexcept
Drop a StorageBuffer usage the backend cannot actually honour.
Definition RenderState.hpp:241
Base toolkit upon which the software is built.
Definition Application.cpp:85
Definition DocumentContext.hpp:18
Connection between two score::gfx::Port.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:236
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:60
Definition OutputNode.hpp:17
Port of a score::gfx::Node.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:215
score::gfx::Node * node
Parent node of the port.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:217
Definition score-plugin-gfx/Gfx/Graph/Node.hpp:71
Stores a sampler and the texture currently associated with it.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:169
Useful abstraction for storing all the data related to a render target.
Definition score-plugin-gfx/Gfx/Graph/Utils.hpp:307