• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ossia / score / 45465485304

24 Nov 2026 06:59PM UTC coverage: 62.1% (+0.3%) from 61.818%
45465485304

Pull #2302

github

web-flow
Merge 52aaaa0b4 into ef0dd3ce5
Pull Request #2302: Mixer: a console of strips with meters, and the execution reporting back without stopping the audio

268210 of 802082 branches covered (33.44%)

1579 of 2302 new or added lines in 45 files covered. (68.59%)

123 existing lines in 22 files now uncovered.

274219 of 441577 relevant lines covered (62.1%)

766034.2 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

66.37
/src/plugins/score-plugin-js/JS/Executor/GPUNode.cpp
1
#include "GPUNode.hpp"
2
#include <JS/Executor/ExecutionHelpers.hpp>
3
#include <JS/JSProcessMetadata.hpp>
4

5
#if defined(SCORE_HAS_GPU_JS)
6
#include <Gfx/Graph/Node.hpp>
7
#include <Gfx/Graph/NodeRenderer.hpp>
8
#include <Gfx/Graph/RenderList.hpp>
9
#include <Gfx/Graph/RenderState.hpp>
10
#include <Gfx/Graph/Window.hpp>
11
#include <JS/Qml/DeviceContext.hpp>
12
#include <JS/Qml/QmlObjects.hpp>
13
#include <JS/Qml/QmlRhiObjects.hpp>
14
#include <JS/Qml/Utils.hpp>
15
#include <JS/ThreadLocalQmlEngine.hpp>
16
#include <Scenario/Settings/ScenarioSettingsModel.hpp>
17

18
#include <score/application/ApplicationContext.hpp>
19

20
#include <score/gfx/Vulkan.hpp>
21

22
#include <ossia-qt/js_utilities.hpp>
23
#include <ossia-qt/qml_engine_functions.hpp>
24

25
#include <boost/unordered/concurrent_flat_map.hpp>
26

27
#include <QKeyEvent>
28
#include <QMouseEvent>
29
#include <QQmlComponent>
30
#include <QQmlContext>
31
#include <QQmlEngine>
32
#include <QQuickGraphicsDevice>
33
#include <QQuickRenderControl>
34
#include <QQuickRenderTarget>
35
#include <QQuickWindow>
36

37
#include <private/qquickrendercontrol_p.h>
38
#include <private/qquickwindow_p.h>
39
#include <private/qsgcontext_p.h>
40
#include <private/qsgdefaultrendercontext_p.h>
41

42
#include <algorithm>
43
#include <set>
44
#include <utility>
45
#include <JS/Qml/VariantToJs.hpp>
46
namespace JS
47
{
48
namespace
49
{
50
// The output window stands in for the offscreen QQuickWindow where Qt Quick
51
// needs a real one: keyboard focus, cursor shape, shortcuts, input method.
52
//
53
// While the scene itself is worked on it must not: Qt Quick takes the device
54
// pixel ratio from the render window when there is one
55
// (QQuickWindow::effectiveDevicePixelRatio; neither QQuickWindow nor
56
// QQuickRenderControl can override it), while the scene is laid out in
57
// render-size units that map 1:1 to the pixels of a render-size texture,
58
// whatever screen the output window is on. Without a render window the ratio
59
// is the render target's, set to 1. The scene is worked on when the script is
60
// loaded, when its messages and its tick run, and when it is polished,
61
// synchronized and rendered: everything but the delivery of input, which
62
// needs the window for focus and the cursor.
63
//
64
// The scope is the calling thread's: with SCORE_THREADED_GFX the scene is
65
// worked on in the render thread while the GUI thread asks for the window
66
// to match a shortcut or to set a cursor.
67
class WindowRenderControl final : public QQuickRenderControl
68
{
69
public:
70
  explicit WindowRenderControl(QWindow* window)
24 ✔
71
      : m_window{window}
24 !
72
  {
24 ✔
73
  }
24 ✔
74

75
  QWindow* renderWindow(QPoint* offset) override
826 ✔
76
  {
77
    if(offset)
826 !
78
      *offset = {};
×
79
    if(t_sceneWork == this)
826 ✔
80
      return nullptr;
778 ✔
81
    return m_window.data();
48 ✔
82
  }
826 ✔
83

84
  struct SceneScope
85
  {
86
    explicit SceneScope(QQuickRenderControl* rc)
1,185 ✔
87
        : previous{std::exchange(t_sceneWork, rc)}
1,185 ✔
88
    {
89
    }
1,185 ✔
90
    ~SceneScope() { t_sceneWork = previous; }
1,185 ✔
91
    SceneScope(const SceneScope&) = delete;
92
    SceneScope& operator=(const SceneScope&) = delete;
93
    const QQuickRenderControl* previous;
94
  };
95

96
private:
97
  QPointer<QWindow> m_window;
98
  static inline thread_local const QQuickRenderControl* t_sceneWork{};
99
};
100
}
101

102
class GpuRenderer;
103
struct GpuNode : score::gfx::NodeModel
104
{
105
public:
106
  explicit GpuNode(
107
      QObject* uiContext, JS::JSState&& st, const QString& root, const QString& source,
108
      const ossia::inlets& ins, const ossia::outlets& outs);
109
  virtual ~GpuNode();
110

111
  score::gfx::NodeRenderer*
112
  createRenderer(score::gfx::RenderList& r) const noexcept override;
113

114
  using score::gfx::NodeModel::process;
115
  void process(score::gfx::Message&& msg) override;
116

117
  QPointer<QObject> m_uiContext;
118
  JS::JSState m_modelState;
119
  QString m_root;
120
  QString source;
121
  std::atomic_int64_t sourceIndex{};
122

123
  score::gfx::Message m_lastState;
124
  std::function<void(QVariant)> m_messageToUi;
125
  std::shared_ptr<GpuValueQueue> m_valueMessages;
126

127
  using js_message_type = ossia::variant<QVariant, std::pair<QString, ossia::value>>;
128
  void uiMessage(const QVariant& v);
129
  void stateElementChanged(const QString& k, const ossia::value& v);
130

131
  struct Engine
48 !
132
  {
133
    std::shared_ptr<QQmlEngine> m_engine{};
24 ✔
134
    QQmlContext* m_context{};
24 ✔
135
    DeviceContext* m_execFuncs{};
24 ✔
136
    QQmlComponent* m_component{};
24 ✔
137
    JS::Script* m_object{};
24 ✔
138
    QPointer<QQuickItem> m_item{};
24 ✔
139

140
    // Qt Quick runtime. Created in GpuRenderer::initState(), destroyed
141
    // when the Engine itself is destroyed (GpuRenderer::release() drops
142
    // the map entry and the renderer's own shared_ptr, bringing refcount
143
    // to zero). Destruction runs while the owning QRhi is still alive —
144
    // see the note in GpuRenderer::release() for why this matters.
145
    QQuickRenderControl* m_quickRenderControl{};
24 ✔
146
    QQuickWindow* m_quickWindow{};
24 ✔
147

148
    std::vector<Inlet*> m_jsInlets;
149
    std::vector<std::pair<ControlInlet*, int>> m_ctrlInlets;
150
    std::vector<std::pair<Impulse*, int>> m_impulseInlets;
151
    std::vector<std::pair<ValueInlet*, int>> m_valInlets;
152
    std::vector<std::pair<TextureInlet*, int>> m_texInlets;
153
    std::vector<std::pair<ValueOutlet*, std::size_t>> m_valueOutlets;
154
    std::shared_ptr<GpuValueQueue> m_valueMessages;
155

156
    // The node this runtime belongs to, and the renderer it was acquired for.
157
    // Set before the QML component is instantiated: setupComponent's
158
    // script-to-UI connection needs them.
159
    GpuNode* m_node{};
24 ✔
160
    const GpuRenderer* m_owner{};
24 ✔
161

162
    // Whether this runtime is the one publishing the process's outputs.
163
    // Decided once per tick() by GpuNode::claimPublisher; read by the
164
    // Script::uiSend handler, which fires from inside the script's tick.
165
    bool m_publishing{};
24 ✔
166

167
    ossia::spsc_queue<js_message_type> ui_messages;
168

169
    void init(
170
        GpuRenderer& renderer, GpuNode& node, QQuickWindow* window,
171
        score::gfx::RenderList& rl);
172

173
    void createItem(
174
        GpuRenderer& renderer, GpuNode& node, score::gfx::RenderList& rl);
175

176
    void updateItemTextureOut(QQuickWindow* window);
177

178
    void setupComponent(
179
        GpuRenderer& renderer, GpuNode& node, score::gfx::RenderList& rl);
180

181
    void releaseItem();
182

183
    ~Engine();
184

185
    void processMessage(const score::gfx::Message& msg);
186
    void restoreControls(const score::gfx::Message& msg);
187

188
    void tick();
189

190
    void uiMessage(const QVariant& v)
5 ✔
191
    {
192
      if(!m_object)
5 !
193
        return;
×
194

195
      const auto& on_ui = this->m_object->uiEvent();
5 ✔
196
      if(!on_ui.isCallable())
5 !
197
        return;
×
198

199
      on_ui.call({JS::variantToJs(*m_engine, v)});
5 !
200
    }
5 ✔
201

202
    void stateElementChanged(const QString& k, const ossia::value& v)
×
203
    {
204
      if(!m_object)
×
205
        return;
×
206

207
      const auto& on_stateUpdated = this->m_object->stateUpdated();
×
208
      if(!on_stateUpdated.isCallable())
×
209
        return;
×
210

211
      if(v.valid())
×
212
      {
213
        if(auto res = v.apply(ossia::qt::ossia_to_qvariant{}); res.isValid())
×
214
          on_stateUpdated.call({k, JS::variantToJs(*m_engine, res)});
×
215
        else
216
          on_stateUpdated.call({k, QJSValue{}});
×
217
      }
×
218
      else
219
        on_stateUpdated.call({k, QJSValue{}});
×
220
    }
×
221
  };
222

223
  // One Qt Quick runtime per renderer — that is, per RenderList this node
224
  // takes part in: several sinks on a single node (two QML TextureSources
225
  // previewing the same process, a preview panel in two views) are several
226
  // render lists, possibly on the same thread and QRhi, and each of them
227
  // needs its own QQuickWindow bound to its own render target.
228
  //
229
  // Keying on the renderer also means a renderer only ever inserts and erases
230
  // its own entry, by its own identity: under SCORE_THREADED_GFX release can
231
  // run on another thread than the acquire.
232
  std::shared_ptr<Engine> acquireEngine(const GpuRenderer* renderer)
24 ✔
233
  {
234
    std::shared_ptr<Engine> res;
24 ✔
235
    m_engines.try_emplace_and_visit(
24 !
236
        renderer,
237
        std::make_shared<Engine>(),
24 !
238
        [&](auto& slot) { res = slot.second; },   // newly-inserted visitor
48 ✔
239
        [&](auto& slot) { res = slot.second; });  // existing-key visitor
24 ✔
240
    return res;
24 ✔
241
  }
24 ✔
242

243
  void releaseEngine(const GpuRenderer* renderer)
24 ✔
244
  {
245
    m_engines.erase(renderer);
24 ✔
246
    // Hand the role back if this runtime held it: the next one to run claims
247
    // it, so closing the panel that owned the process's outputs does not
248
    // silence the ones still open.
249
    auto expected = renderer;
24 ✔
250
    m_publisher.compare_exchange_strong(expected, nullptr);
24 ✔
251
  }
24 ✔
252

253
  // Several runtimes means several instances of the script, each running once
254
  // per frame of its own render list — but still ONE process. Its value
255
  // outlets and its script-to-UI messages are published by exactly one of
256
  // them, or opening a second preview of a mapping would double every value
257
  // it sends and every answer it gives.
258
  //
259
  // The first runtime to run claims the role and keeps it until its render
260
  // list goes away (releaseEngine); a runtime that is alive but idle still
261
  // holds it.
262
  bool claimPublisher(const GpuRenderer* renderer) noexcept
411 ✔
263
  {
264
    auto cur = m_publisher.load(std::memory_order_acquire);
411 ✔
265
    if(cur == renderer)
411 ✔
266
      return true;
308 ✔
267
    if(cur)
103 ✔
268
      return false;
79 ✔
269
    return m_publisher.compare_exchange_strong(
48 ✔
270
               cur, renderer, std::memory_order_acq_rel, std::memory_order_acquire)
24 ✔
271
           || m_publisher.load(std::memory_order_acquire) == renderer;
24 !
272
  }
411 ✔
273

274
  boost::concurrent_flat_map<const GpuRenderer*, std::shared_ptr<Engine>> m_engines;
275
  std::atomic<const GpuRenderer*> m_publisher{};
15 ✔
276
};
277

278
void GpuNode::uiMessage(const QVariant& v)
4 ✔
279
{
280
  m_engines.visit_all([&] (auto& elt) {
9 ✔
281
    elt.second->ui_messages.enqueue(v);
5 !
282
  });
5 ✔
283
}
4 ✔
284

285
void GpuNode::stateElementChanged(const QString& k, const ossia::value& v)
×
286
{
287
  // Keep m_modelState in sync so that engine recreation loads current state
288
  if(v.valid())
×
289
    m_modelState[k] = v;
×
290
  else
291
    m_modelState.erase(k);
×
292

293
  m_engines.visit_all([&, p = std::make_pair(k, v)] (auto& elt) {
×
294
    elt.second->ui_messages.enqueue(p);
×
295
  });
×
296
}
×
297

298

299
class GpuRenderer : public score::gfx::GenericNodeRenderer
300
{
301
public:
302
  GpuNode& node;
303
  std::atomic_int64_t sourceIndex{};
24 ✔
304
  explicit GpuRenderer(const GpuNode& node) noexcept
72 !
305
      : score::gfx::GenericNodeRenderer{node}
24 ✔
306
      , node{(GpuNode&)node}
24 ✔
307
  {
24 ✔
308
  }
24 ✔
309

310
private:
311
  ~GpuRenderer() { }
48 ✔
312

313
  static const constexpr auto vertex_shader = R"_(#version 450
314
layout(location = 0) in vec2 position;
315
layout(location = 1) in vec2 texcoord;
316

317
layout(binding = 3) uniform sampler2D y_tex;
318
layout(location = 0) out vec2 v_texcoord;
319

320
layout(std140, binding = 0) uniform renderer_t {
321
  mat4 clipSpaceCorrMatrix;
322
  vec2 renderSize;
323
} renderer;
324

325
out gl_PerVertex { vec4 gl_Position; };
326

327
void main()
328
{
329
  v_texcoord = texcoord;
330
  gl_Position = renderer.clipSpaceCorrMatrix * vec4(position, 0.0, 1.);
331
#if defined(QSHADER_GLSL) || defined(QSHADER_HLSL) || defined(QSHADER_MSL)
332
  gl_Position.y = - gl_Position.y;
333
#endif
334
}
335
)_";
336

337
  static const constexpr auto fragment_shader = R"_(#version 450
338
layout(std140, binding = 0) uniform renderer_t {
339
  mat4 clipSpaceCorrMatrix;
340
  vec2 renderSize;
341
} renderer;
342

343
layout(binding=3) uniform sampler2D y_tex;
344

345
layout(location = 0) in vec2 v_texcoord;
346
layout(location = 0) out vec4 fragColor;
347

348
void main ()
349
{
350
  fragColor = texture(y_tex, vec2(v_texcoord.x, v_texcoord.y));
351
}
352
)_";
353

354
  std::vector<score::gfx::Sampler> m_inputSamplers;
355

356
  // All setup lives in initState() rather than init(): the incremental
357
  // graph-edit path calls initState() directly on newly spawned renderers.
358
  // Mirrors RenderedISFNode's split, with the inherited
359
  // GenericNodeRenderer::init() calling initState() then addOutputPass() per
360
  // output edge.
361
  //
362
  // updateInputTexture is deliberately a no-op. GpuRenderer's m_samplers is a
363
  // private single-entry vector holding the internal "y_tex" sampler pointing at
364
  // m_internalTex, the texture Qt Quick renders into. The eight visible texture
365
  // inlets are routed through m_engine->m_texInlets and the per-frame
366
  // res.copyTexture in update(), and must not drive m_samplers: the base
367
  // implementation indexes m_samplers by image-input position, so a sink-sampler
368
  // update for input[0] would rebind y_tex away from m_internalTex.
369
  void updateInputTexture(
×
370
      const score::gfx::Port& input, QRhiTexture* tex,
371
      QRhiTexture* depthTex = nullptr) override
372
  {
373
  }
×
374

375
  bool followsRenderSize() const noexcept override { return true; }
×
376

377
  void initState(score::gfx::RenderList& renderer, QRhiResourceUpdateBatch& res) override
24 ✔
378
  {
379
    auto& rhi = *renderer.state.rhi;
24 ✔
380
    // Init the texture on which we are going to render
381
    // FIXME RGBA32F
382
    m_internalTex = score::gfx::createRenderTarget(
24 ✔
383
        renderer.state, QRhiTexture::RGBA8, renderer.state.renderSize,
24 ✔
384
        renderer.state.samples, true);
24 ✔
385

386
    // Use the quad mesh (GenericNodeRenderer::initState would default to
387
    // triangle). The inherited addOutputPass uses m_mesh to build pipelines.
388
    m_mesh = &renderer.defaultQuad();
24 ✔
389
    defaultMeshInit(renderer, *m_mesh, res);
24 ✔
390
    processUBOInit(renderer);
24 ✔
391
    std::tie(m_vertexS, m_fragmentS)
48 ✔
392
        = score::gfx::makeShaders(renderer.state, vertex_shader, fragment_shader);
24 !
393

394
    m_inputSamplers
48 ✔
395
        = score::gfx::initInputSamplers(this->node, renderer, this->node.input);
48 ✔
396

397
    // Create the sampler in which we are going to put the texture
398
    {
399
      auto sampler = rhi.newSampler(
24 ✔
400
          QRhiSampler::Linear, QRhiSampler::Linear, QRhiSampler::None,
401
          QRhiSampler::ClampToEdge, QRhiSampler::ClampToEdge);
402

403
      sampler->setName("JS::GPUNode::sampler");
24 !
404
      sampler->create();
24 ✔
405

406
      m_samplers.push_back({sampler, m_internalTex.texture});
24 ✔
407
    }
408

409
    // Acquire the Engine. release() drops the map entry and our own
410
    // ref, so we always get a fresh Engine here — tying the Qt Quick
411
    // runtime lifetime strictly to (initState, release) lets us free
412
    // all QRhi-owned buffers before the RHI itself is destroyed in
413
    // Graph::~Graph.
414
    m_engine = node.acquireEngine(this);
24 ✔
415
    if(!m_engine)
24 !
416
    {
417
      m_initialized = true;
×
418
      return;
×
419
    }
420

421
    SCORE_ASSERT(!m_engine->m_quickWindow);
24 !
422
    // renderWindow() answers with the real window so that input reaches the
423
    // scene; see WindowRenderControl for why it does not while drawing.
424
    const auto win = renderer.state.window.lock();
24 ✔
425
    m_engine->m_quickRenderControl = new WindowRenderControl{win.get()};
24 !
426
    m_engine->m_quickWindow = new QQuickWindow{m_engine->m_quickRenderControl};
24 !
427

428
#if QT_HAS_VULKAN
429
    if(renderer.state.api == score::gfx::GraphicsApi::Vulkan)
24 !
430
      m_engine->m_quickWindow->setVulkanInstance(
×
431
          score::gfx::staticVulkanInstance());
×
432
#endif
433

434
    if(win)
24 ✔
435
    {
436
      QObject::connect(
2 !
437
          win.get(), &score::gfx::Window::interactiveEvent,
2 ✔
438
          m_engine->m_quickWindow,
2 ✔
439
          [qqw = QPointer{m_engine->m_quickWindow}, source = QPointer{win.get()}](
2 !
440
              QEvent* e) {
441
        auto* q = qqw.data();
×
442
        if(!q || !source)
×
443
          return;
×
444
        switch(e->type())
×
445
        {
446
          case QEvent::MouseButtonPress:
447
          case QEvent::MouseButtonRelease:
448
          case QEvent::MouseButtonDblClick:
449
          case QEvent::MouseMove: {
450
            const auto& mouse = *static_cast<QMouseEvent*>(e);
×
451
            const QPointF position{
×
452
                mouse.position().x() * q->width() / std::max(1, source->width()),
×
453
                mouse.position().y() * q->height() / std::max(1, source->height())};
×
454
            // Each offscreen scene needs its own event in render coordinates.
455
            QMouseEvent mapped{
×
456
                e->type(),
×
457
                position,
458
                position,
459
                mouse.globalPosition(),
×
460
                mouse.button(),
×
461
                mouse.buttons(),
×
462
                mouse.modifiers(),
×
463
                mouse.source(),
×
464
                mouse.pointingDevice()};
×
465
            mapped.setTimestamp(mouse.timestamp());
×
466
            mapped.setAccepted(false);
×
467
            QCoreApplication::sendEvent(q, &mapped);
×
468
            if(mapped.isAccepted())
×
469
              e->accept();
×
470
            break;
471
          }
×
472
          case QEvent::KeyPress:
473
          case QEvent::KeyRelease: {
474
            const auto& key = *static_cast<QKeyEvent*>(e);
×
475
            QKeyEvent mapped{
×
476
                e->type(),
×
477
                key.key(),
×
478
                key.modifiers(),
×
479
                key.nativeScanCode(),
×
480
                key.nativeVirtualKey(),
×
481
                key.nativeModifiers(),
×
482
                key.text(),
×
483
                key.isAutoRepeat(),
×
484
                quint16(key.count()),
×
485
                key.device()};
×
486
            mapped.setTimestamp(key.timestamp());
×
487
            mapped.setAccepted(false);
×
488
            QCoreApplication::sendEvent(q, &mapped);
×
489
            if(mapped.isAccepted())
×
490
              e->accept();
×
491
            break;
492
          }
×
493
          default:
494
            QCoreApplication::sendEvent(q, e);
×
495
            break;
×
496
        }
497
      }, Qt::DirectConnection);
×
498
    }
2 ✔
499
    m_engine->m_quickWindow->setGraphicsDevice(
24 !
500
        QQuickGraphicsDevice::fromRhi(&rhi));
24 !
501
    m_engine->m_quickWindow->setColor(Qt::transparent);
24 !
502
    m_engine->m_quickRenderControl->initialize();
24 !
503
    // Mark the window as "visible" so QQuickItem::grabToImage() works.
504
    // The window is driven by QQuickRenderControl (no native OS
505
    // window) — this only sets the internal flag.
506
    QQuickWindowPrivate::get(m_engine->m_quickWindow)->visible = true;
24 ✔
507

508
    m_window = m_engine->m_quickWindow;
24 ✔
509
    m_renderControl = m_engine->m_quickRenderControl;
24 ✔
510

511
    // Size and render target are per-RenderList and must be refreshed
512
    // on every initState() (resize changes the RT dimensions).
513
    const auto sz = renderer.state.renderSize;
24 ✔
514
    m_window->setWidth(sz.width());
24 !
515
    m_window->setHeight(sz.height());
24 !
516
    m_window->contentItem()->setWidth(sz.width());
24 !
517
    m_window->contentItem()->setHeight(sz.height());
24 !
518
    auto quickTarget = QQuickRenderTarget::fromRhiRenderTarget(m_internalTex.renderTarget);
24 !
519
    quickTarget.setDevicePixelRatio(1.);
24 !
520
    m_window->setRenderTarget(quickTarget);
24 !
521

522
    {
523
      const WindowRenderControl::SceneScope scene{m_renderControl};
24 !
524
      m_engine->init(*this, node, m_window, renderer);
24 !
525
    }
24 ✔
526
    // Tolerant of script/port mismatches (live-edited QML may not line up
527
    // with the node's declared ports): skip bad inlets instead of aborting.
528
    // Mirrors Engine::setupComponent's guards.
529
    for(auto& [texture_in, i] : this->m_engine->m_texInlets)
24 !
530
    {
531
      if(i >= (int)this->node.input.size())
×
532
        continue;
×
533
      score::gfx::Port* port = this->node.input[i];
×
534
      if(!port || port->type != score::gfx::Types::Image)
×
535
        continue;
×
536
      auto rt = renderer.renderTargetForInputPort(*port);
×
537
      auto item = qobject_cast<JS::TextureInletItem*>(texture_in->item());
×
538
      if(item && rt.texture)
×
539
        item->setSize(rt.texture->pixelSize());
×
540
    }
×
541
    sourceIndex.store(node.sourceIndex.load());
24 ✔
542
    m_initialized = true;
24 ✔
543
  }
24 ✔
544

545
  void reloadEngine(score::gfx::RenderList& renderer)
387 ✔
546
  {
547
    // Guard: initState() bails out early if Engine acquisition failed,
548
    // leaving m_window/m_renderControl/m_engine null. update() can still
549
    // be invoked in that degraded state — short-circuit here.
550
    if(!m_window || !m_renderControl || !m_engine)
387 !
551
      return;
×
552

553
    // GpuNode::sourceIndex is fixed at 1 and never incremented, so the
554
    // GpuRenderer::sourceIndex seeded in initState() always equals it. A live
555
    // script change goes through a full releaseState()/initState() cycle.
556
  }
387 ✔
557

558
  void update(
387 ✔
559
      score::gfx::RenderList& renderer, QRhiResourceUpdateBatch& res,
560
      score::gfx::Edge* edge) override
561
  {
562
    reloadEngine(renderer);
387 ✔
563
    defaultUBOUpdate(renderer, res);
387 ✔
564

565
    if(!m_engine)
387 !
566
      return;
×
567

568
    // Schedule a copy of the input textures into the actual textures.
569
    // Tolerant of script/port mismatches (live-edited QML): skip bad inlets
570
    // instead of asserting. Mirrors Engine::setupComponent's guards.
571
    {
572
      for(auto& [texture_in, i] : this->m_engine->m_texInlets)
387 !
573
      {
574
        if(i >= (int)this->node.input.size())
×
575
          continue;
×
576
        score::gfx::Port* port = this->node.input[i];
×
577
        if(!port || port->type != score::gfx::Types::Image)
×
578
          continue;
×
579
        auto rt = renderer.renderTargetForInputPort(*port);
×
580
        auto item = qobject_cast<JS::TextureInletItem*>(texture_in->item());
×
581
        if(!item)
×
582
          continue;
×
583
        auto itemRenderer = item->renderer;
×
584
        auto texture = item->texture;
×
585
        if(itemRenderer && texture && rt.texture)
×
586
        {
587
          const bool sameSize = rt.texture->pixelSize() == texture->pixelSize();
×
588
          const bool sameSamples
×
589
              = rt.texture->sampleCount() == texture->sampleCount();
×
590
          if(sameSize && sameSamples)
×
591
          {
592
            QRhiTextureCopyDescription desc;
×
593
            res.copyTexture(texture, rt.texture, desc);
×
594
          }
×
595
          else if(!sameSize)
×
596
          {
597
            // The upstream RT changed dimensions since the last initState().
598
            // Resize the inlet item so Qt Quick rebuilds its QSGRhiLayer at
599
            // the new size; this frame's copy is intentionally skipped
600
            // (src/dst pair is mismatched) and the next update() will copy
601
            // correctly once the layer texture is recreated.
602
            item->setSize(rt.texture->pixelSize());
×
603
          }
×
604
          else
605
          {
606
            // Size matches but sample count differs, e.g. the inlet item's QSGRhiLayer is
607
            // single-sampled while the upstream RT is MSAA. QRhi::copyTexture requires
608
            // matching sample counts and setSize() is a no-op here, and the layer cannot be
609
            // recreated at a different sample count from outside Qt Quick, so skip the copy
610
            // -- the inlet keeps its last content -- and warn once per item.
611
            if(m_warnedSampleMismatch.insert(item).second)
×
612
            {
613
              qWarning() << "JS::GPUNode: texture inlet" << i
×
614
                         << "sample-count mismatch (upstream"
×
615
                         << rt.texture->sampleCount() << "vs inlet"
×
616
                         << texture->sampleCount()
×
617
                         << ") - copy skipped, inlet may appear stale/black";
×
618
            }
×
619
          }
620
        }
×
621
      }
×
622
    }
623
  }
387 ✔
624

625
  void processMessages()
387 ✔
626
  {
627
    score::gfx::Message msg;
387 ✔
628
    while(m_messages.try_dequeue(msg))
1,195 !
629
    {
630
      if(m_engine)
808 !
631
        m_engine->processMessage(msg);
808 !
632
    }
633
  }
387 ✔
634

635
  void render() { }
636

637
  void runInitialPasses(
387 ✔
638
      score::gfx::RenderList& renderer, QRhiCommandBuffer& cb,
639
      QRhiResourceUpdateBatch*& res, score::gfx::Edge& e) override
640
  {
641
    if(!m_window || !m_renderControl || !m_engine)
387 !
642
      return;
×
643

644
    // Qt Quick's layers have their own sample count and stay empty until the
645
    // scene has content.
646
    renderer.isolateFollowingPasses();
387 ✔
647

648
    // Here we run the Qt Quick render loop which handles its own pass
649
    if(auto sz = m_window->size(); sz != m_window->contentItem()->size())
387 !
650
    {
651
      m_window->contentItem()->setSize(sz); // why does this happen???
×
652
    }
×
653

654
    // 0. Copy the values in the inputs
655
    {
656
      const WindowRenderControl::SceneScope scene{m_renderControl};
387 ✔
657
      processMessages();
387 !
658
    }
387 ✔
659

660
    // 1. Run our object
661
    if(m_engine)
387 !
662
    {
663
      const WindowRenderControl::SceneScope scene{m_renderControl};
387 ✔
664
      m_engine->tick();
387 !
665
      if(m_engine->m_item)
387 !
666
        m_engine->m_item->update();
387 !
667

668
      // Mark texture inlet items dirty so the scene graph re-captures them
669
      for(auto& [texture_in, i] : m_engine->m_texInlets)
387 !
670
      {
671
        if(auto item = texture_in->item())
×
672
          item->update();
×
673
      }
674
    }
387 ✔
675
    // 2. Render
676
    m_window->beforeRendering();
387 ✔
677

678
    auto cd = QQuickWindowPrivate::get(m_window);
387 ✔
679
    auto rc = QQuickRenderControlPrivate::get(m_renderControl);
387 ✔
680
    rc->cb = &cb;
387 ✔
681

682
    cd->deliveryAgentPrivate()->flushFrameSynchronousEvents(m_window);
387 ✔
683

684
    const WindowRenderControl::SceneScope scene{m_renderControl};
387 ✔
685
    cd->polishItems();
387 !
686
    m_window->afterRendering();
387 !
687
    m_window->afterAnimating();
387 !
688

689
    // beginFrame:
690
    m_window->beforeFrameBegin();
387 !
691

692
    // sync:
693
    cd->setCustomCommandBuffer(&cb);
387 !
694

695
    auto rt = renderer.renderTargetForOutput(e).renderTarget;
387 ✔
696
    SCORE_ASSERT(rt);
387 !
697

698
    cd->syncSceneGraph();
387 !
699
    rc->rc->endSync();
387 !
700
    // render:
701
    cd->renderSceneGraph();
387 !
702
    // endFrame:
703
    m_window->afterFrameEnd();
387 !
704

705
    // Disassociate our transient cb — Qt's own qsgrhisupport pairs
706
    // setCustomCommandBuffer(cb) with setCustomCommandBuffer(nullptr)
707
    // to avoid leaving a dangling pointer past the frame.
708
    cd->setCustomCommandBuffer(nullptr);
387 !
709
    // Symmetric reset of QQuickRenderControlPrivate::cb, which was bound above to
710
    // a stack reference parameter that goes out of scope when the frame returns.
711
    rc->cb = nullptr;
387 ✔
712

713
    // Force-drain Qt Quick's glyph-cache resource-update batch. The batch is
714
    // lazily allocated in preprocess() and normally released when a glyph node
715
    // renders and commits it; a QML scene with no glyph node populates the cache
716
    // but never commits, pinning one slot of the 64-slot QRhi pool per render
717
    // context. Each window resize spawns a fresh QQuickRenderControl and context.
718
    // Merge any pending uploads into the outer batch so they still land, then reset
719
    // the context's pointer to return the slot.
720
    if(auto* rcp = QQuickRenderControlPrivate::get(m_renderControl))
387 !
721
    {
722
      if(auto* defRc = qobject_cast<QSGDefaultRenderContext*>(rcp->rc))
387 !
723
      {
724
        if(auto* pending = defRc->maybeGlyphCacheResourceUpdates())
387 !
725
        {
726
          if(res)
×
727
            res->merge(pending);
×
728
          defRc->resetGlyphCacheResources();
×
729
        }
×
730
      }
387 ✔
731
    }
387 ✔
732
    if(m_engine && m_engine->m_engine)
387 !
733
    {
734
      m_engine->m_engine->collectGarbage();
387 !
735
    }
387 ✔
736
    // No UpdateRequest post needed: runInitialPasses drives sync/render
737
    // directly via polishItems/syncSceneGraph/renderSceneGraph each frame.
738
  }
387 ✔
739

740
  void runRenderPass(
387 ✔
741
      score::gfx::RenderList& renderer, QRhiCommandBuffer& cb,
742
      score::gfx::Edge& edge) override
743
  {
744
    const auto& mesh = renderer.defaultQuad();
387 ✔
745
    defaultRenderPass(renderer, mesh, cb, edge);
387 ✔
746
    if(m_window)
387 !
747
      m_window->frameSwapped();
387 ✔
748
  }
387 ✔
749

750
  void releaseState(score::gfx::RenderList& r) override
41 ✔
751
  {
752
    for(auto sampler : m_inputSamplers)
41 !
753
    {
754
      delete sampler.sampler;
×
755
      // texture is deleted elsewhere
756
    }
757
    m_inputSamplers.clear();
41 ✔
758

759
    // Tear the Engine down here: this is the last hook while the QRhi is still
760
    // alive. Graph::~Graph calls RenderList::release() before out->destroyOutput()
761
    // kills the RHI, and the GpuRenderer destructor runs after that, so any
762
    // QRhi-owned buffers still held by the QQuickRenderControl / QQuickWindow would
763
    // leak.
764
    //
765
    // In releaseState() rather than release(), because
766
    // Graph::reconcileAllRenderLists calls releaseState() on renderers orphaned by
767
    // a live graph edit and never release(); otherwise the next reconnection's
768
    // acquireEngine would return a stale entry with m_quickWindow already set.
769
    m_window = nullptr;
41 ✔
770
    m_renderControl = nullptr;
41 ✔
771
    if(m_engine)
41 ✔
772
    {
773
      m_engine.reset();
24 ✔
774
      node.releaseEngine(this);
24 ✔
775
    }
24 ✔
776

777
    m_internalTex.release();
41 ✔
778

779
    defaultRelease(r);
41 ✔
780
  }
41 ✔
781

782
  void release(score::gfx::RenderList& r) override { releaseState(r); }
34 ✔
783

784
  score::gfx::TextureRenderTarget m_internalTex;
785

786
  QQuickRenderControl* m_renderControl{};
24 ✔
787
  QQuickWindow* m_window{};
24 ✔
788

789
  ossia::spsc_queue<score::gfx::Message> m_messages;
790
  std::shared_ptr<GpuNode::Engine> m_engine;
791

792
  // Texture inlet items for which a sample-count mismatch has already been
793
  // reported, to rate-limit the warning to once per item (see update()).
794
  std::set<const void*> m_warnedSampleMismatch;
795

796
  friend struct GpuNode;
797
};
798

799
GpuNode::GpuNode(
15 !
800
    QObject* uiContext, JS::JSState&& st, const QString& root, const QString& source,
801
    const ossia::inlets& ins, const ossia::outlets& outs)
802
    : m_uiContext{uiContext}
15 !
803
    , m_modelState{std::move(st)}
15 ✔
804
    , m_root{root}
15 ✔
805
    , source{source}
15 ✔
806
    , sourceIndex{1}
15 ✔
807
{
15 ✔
808
  for(auto& p : ins)
19 ✔
809
  {
810
    switch(p->which())
4 !
811
    {
812
      case ossia::audio_port::which:
813
        input.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Audio, {}});
×
814
        break;
×
815
      case ossia::value_port::which:
816
        input.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Float, {}});
4 !
817
        break;
4 ✔
818
      case ossia::texture_port::which:
819
        input.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Image, {}});
×
820
        break;
×
821
      case ossia::midi_port::which: // FIXME
822
        input.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Empty, {}});
×
823
        break;
×
824
      case ossia::geometry_port::which: // FIXME
825
        input.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Geometry, {}});
×
826
        break;
×
827
    }
828
  }
829

830
  for(auto& p : outs)
35 ✔
831
  {
832
    switch(p->which())
20 !
833
    {
834
      case ossia::audio_port::which:
835
        output.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Audio, {}});
×
836
        break;
×
837
      case ossia::value_port::which:
838
        output.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Float, {}});
5 !
839
        break;
5 ✔
840
      case ossia::texture_port::which:
841
        output.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Image, {}});
15 !
842
        break;
15 ✔
843
      case ossia::midi_port::which: // FIXME
844
        output.push_back(new score::gfx::Port{this, {}, score::gfx::Types::Empty, {}});
×
845
        break;
×
846
      case ossia::geometry_port::which: // FIXME
847
        output.push_back(
×
848
            new score::gfx::Port{this, {}, score::gfx::Types::Geometry, {}});
×
849
        break;
×
850
    }
851
  }
852
}
15 ✔
853
GpuNode::~GpuNode()
30 ✔
854
{
30 ✔
855
}
30 ✔
856

857
void GpuNode::Engine::tick()
387 ✔
858
{
859
  if(!m_object)
387 !
860
    return;
×
861

862
  // Decided here, once per tick, and read back by the uiSend handler which
863
  // fires from inside the script's own tick call below.
864
  m_publishing = m_node && m_node->claimPublisher(m_owner);
387 !
865

866
  // Process messages that may come from UI
867
  {
868
    js_message_type m;
387 ✔
869
    while(ui_messages.try_dequeue(m)) {
392 !
870
      struct {
871
        Engine& self;
872
        void operator()(const QVariant& v) {
5 ✔
873
          self.uiMessage(v);
5 ✔
874
        }
5 ✔
875
        void operator()(const std::pair<QString, ossia::value>& v) {
×
876
          self.stateElementChanged(v.first, v.second);
×
877
        }
×
878
      } vis{*this};
5 ✔
879
      ossia::visit(vis, m);
5 !
880
    }
881
  }
387 ✔
882

883
  if(auto& tick = m_object->tick(); tick.isCallable())
387 ✔
884
  {
885
    tick.call();
318 !
886
  }
318 ✔
887
  // UI events arrive on the rendering thread; publish their values on the
888
  // next execution tick, without sharing QJSValue across engine threads.
889
  //
890
  // Only the publishing runtime writes them out, but every runtime clears its
891
  // own outlets, or a non-publishing script's `values` would grow unbounded.
892
  for(auto [outlet, index] : m_valueOutlets)
425 ✔
893
  {
894
    if(m_publishing)
38 !
895
    {
896
      if(!outlet->value().isUndefined())
38 !
897
        m_valueMessages->enqueue(
×
898
            GpuValueMessage{index, ossia::qt::value_from_js(outlet->value())});
×
899
      for(const auto& message : outlet->values)
38 !
900
        m_valueMessages->enqueue(
×
901
            GpuValueMessage{index, ossia::qt::value_from_js(message.value)});
×
902
    }
38 ✔
903
    outlet->clear();
38 ✔
904
  }
905
}
387 ✔
906

907
void GpuNode::Engine::restoreControls(const score::gfx::Message& msg)
24 ✔
908
{
909
  // The values only. An impulse is something that happened once, and handing a
910
  // remembered one to a new item would be saying it happened again.
911
  for(std::size_t i = 0; i < msg.input.size(); i++)
28 ✔
912
  {
913
    auto it = ossia::get_if<ossia::value>(&msg.input[i]);
4 ✔
914
    if(!it)
4 !
915
      continue;
×
916
    if(m_jsInlets.size() <= i)
4 !
917
      return;
×
918

919
    auto inl = m_jsInlets[i];
4 ✔
920
    if(qobject_cast<Impulse*>(inl))
4 ✔
921
      continue;
2 ✔
922

923
    auto var = it->apply(ossia::qt::ossia_to_qvariant{});
2 ✔
924
    if(auto v = qobject_cast<ValueInlet*>(inl))
2 !
925
    {
926
      v->clear();
×
927
      v->setValue(std::move(var));
×
928
    }
×
929
    else if(auto v = qobject_cast<ControlInlet*>(inl))
2 !
930
    {
931
      v->clear();
2 !
932
      v->setValue(std::move(var));
2 !
933
    }
2 ✔
934
  }
2 ✔
935
}
24 ✔
936

937
void GpuNode::Engine::processMessage(const score::gfx::Message& msg)
808 ✔
938
{
939
  for(std::size_t i = 0; i < msg.input.size(); i++)
816 ✔
940
  {
941
    if(auto it = ossia::get_if<ossia::value>(&msg.input[i]))
8 !
942
    {
943
      auto var = it->apply(ossia::qt::ossia_to_qvariant{});
8 ✔
944

945
      if(m_jsInlets.size() <= i)
8 !
946
        return;
×
947
      auto inl = m_jsInlets[i];
8 ✔
948
      if(auto v = qobject_cast<ValueInlet*>(inl))
8 !
949
      {
950
        v->clear();
×
951
        v->setValue(std::move(var));
×
952
      }
×
953
      else if(auto v = qobject_cast<Impulse*>(inl))
8 !
954
      {
955
        v->impulse();
4 !
956
      }
4 ✔
957
      else if(auto v = qobject_cast<ControlInlet*>(inl))
4 !
958
      {
959
        v->clear();
4 !
960
        v->setValue(std::move(var));
4 !
961
      }
4 ✔
962
    }
8 ✔
963
  }
8 ✔
964
}
808 ✔
965

966
GpuNode::Engine::~Engine()
24 ✔
967
{
968
  m_ctrlInlets.clear();
24 ✔
969
  m_impulseInlets.clear();
24 ✔
970
  m_valInlets.clear();
24 ✔
971
  m_jsInlets.clear();
24 ✔
972

973
  delete m_object;
24 !
974
  m_object = nullptr;
24 ✔
975

976
  delete m_component;
24 !
977
  m_component = nullptr;
24 ✔
978

979
  delete m_context;
24 !
980
  m_context = nullptr;
24 ✔
981

982
  m_engine = nullptr; // Not owned here!
24 ✔
983

984
  // Destroy the persistent Qt Quick runtime synchronously. Order matches
985
  // Qt's own QQuickWidget: QQuickRenderControl first (its destructor
986
  // calls invalidate() and deletes the QSGRenderContext), then the
987
  // QQuickWindow.
988
  delete m_quickRenderControl;
24 !
989
  m_quickRenderControl = nullptr;
24 ✔
990
  delete m_quickWindow;
24 !
991
  m_quickWindow = nullptr;
24 ✔
992
}
24 ✔
993

994
void GpuNode::Engine::releaseItem()
×
995
{
996
  if(m_item)
×
997
  {
998
    // LOAD-BEARING: both detach calls must precede deleteLater(). The caller
999
    // follows this with init(), whose QML bindings and child-walkers must not
1000
    // observe the dying item. setParentItem(nullptr) removes it from
1001
    // contentItem->childItems() synchronously and setParent(nullptr) severs the
1002
    // QObject ownership chain; deleteLater() alone would briefly expose two items
1003
    // under contentItem to the new createItem().
1004
    m_item->setParent(nullptr);
×
1005
    m_item->setParentItem(nullptr);
×
1006
    m_item->deleteLater();
×
1007
    m_item = nullptr;
×
1008
  }
×
1009
  // A script reload destroys the whole QML tree. Clear the script-
1010
  // associated state here so Engine::init()'s `if(!m_item)` rebuild
1011
  // path can recreate everything cleanly without leaking the old
1012
  // component/object or appending to the inlet vectors.
1013
  delete m_object;
×
1014
  m_object = nullptr;
×
1015
  delete m_component;
×
1016
  m_component = nullptr;
×
1017
  m_jsInlets.clear();
×
1018
  m_ctrlInlets.clear();
×
1019
  m_impulseInlets.clear();
×
1020
  m_valInlets.clear();
×
1021
  m_texInlets.clear();
×
1022
}
×
1023

1024
void GpuNode::Engine::setupComponent(
24 ✔
1025
    GpuRenderer& renderer, GpuNode& node, score::gfx::RenderList& rl)
1026
{
1027
  connectStateCommit(m_object, qobject_cast<ProcessModel*>(node.m_uiContext.data()));
24 ✔
1028
  // FIXME refactor with CPUNode
1029
  // FIXME only works because same thread right now.
1030
  // Re-read QQuickRenderControl and use it to separate
1031
  // execution in GPUNode and rendering in GPURenderer
1032

1033
  QObject::connect(
24 ✔
1034
      m_object, &JS::Script::uiSend, node.m_uiContext,
24 ✔
1035
      [&node, self = this](const QJSValue& v) {
28 ✔
1036
    if(!node.m_uiContext || !node.m_messageToUi)
4 !
1037
      return;
×
1038
    // One process, one message: a second preview of it must not double the
1039
    // script's messages to the UI (see GpuNode::claimPublisher).
1040
    if(!self->m_publishing)
4 ✔
1041
      return;
1 ✔
1042
    QMetaObject::invokeMethod(qApp, [ctx=node.m_uiContext, &func = node.m_messageToUi, vv = v.toVariant()] {
6 !
1043
      if(!ctx)
3 !
1044
        return;
×
1045
      func(std::move(vv));
3 !
1046
    }, Qt::QueuedConnection);
3 ✔
1047
  }, Qt::DirectConnection);
4 ✔
1048

1049
  // (1) Enumerate QML children into the typed inlet vectors FIRST. loadState()
1050
  //     below fires reactive bindings like `ShaderEffectSource.sourceItem =
1051
  //     root.inletItems[src]`; those need each inlet item to already be at its
1052
  //     final pixel size so QQuickShaderEffectSource::updatePaintNode
1053
  //     (qquickshadereffectsource.cpp:657-664) does not take the "source item
1054
  //     is 0x0, delete paint node, return nullptr" branch on the first sync.
1055
  int input_i = 0;
24 ✔
1056
  std::size_t output_i = 0;
24 ✔
1057
  m_valueMessages = node.m_valueMessages;
24 ✔
1058

1059
  for(auto n : m_object->children())
57 ✔
1060
  {
1061
    if(auto imp_in = qobject_cast<Impulse*>(n))
33 ✔
1062
    {
1063
      m_jsInlets.push_back(imp_in);
2 ✔
1064
      m_impulseInlets.push_back({imp_in, input_i++});
2 ✔
1065
    }
2 ✔
1066
    else if(auto ctrl_in = qobject_cast<ControlInlet*>(n))
31 ✔
1067
    {
1068
      m_jsInlets.push_back(ctrl_in);
2 ✔
1069
      m_ctrlInlets.push_back({ctrl_in, input_i++});
2 ✔
1070
    }
2 ✔
1071
    else if(auto val_in = qobject_cast<ValueInlet*>(n))
29 !
1072
    {
1073
      m_jsInlets.push_back(val_in);
×
1074
      m_valInlets.push_back({val_in, input_i++});
×
1075
    }
×
1076
    else if(auto tex_in = qobject_cast<TextureInlet*>(n))
29 !
1077
    {
1078
      m_jsInlets.push_back(tex_in);
×
1079
      m_texInlets.push_back({tex_in, input_i++});
×
1080
    }
×
1081
    else if(auto unknown = qobject_cast<Inlet*>(n))
29 !
1082
    {
1083
      m_jsInlets.push_back(unknown);
×
1084
      input_i++;
×
1085
    }
×
1086
    else if(auto value = qobject_cast<ValueOutlet*>(n))
29 ✔
1087
    {
1088
      m_valueOutlets.emplace_back(value, output_i++);
5 ✔
1089
    }
5 ✔
1090
    else if(qobject_cast<Outlet*>(n))
24 !
1091
    {
1092
      ++output_i;
24 ✔
1093
    }
24 ✔
1094
  }
1095

1096
  // (2) Size each texture-inlet item to its upstream RT's pixel size before
1097
  //     loadState runs. QML's Component.onCompleted has already bound each
1098
  //     inlet item's width/height to inletContainer's, which is 0x0 at this
1099
  //     point because outputRoot has not been reparented to contentItem yet.
1100
  //     Setting the size explicitly breaks that binding and pins the item to
1101
  //     the RT pixel size, which is what the copyTexture in GpuRenderer::update
1102
  //     requires: it skips on any pixelSize mismatch.
1103
  for(auto& [texture_in, i] : m_texInlets)
24 !
1104
  {
1105
    if(i >= (int)node.input.size())
×
1106
      continue;
×
1107
    score::gfx::Port* port = node.input[i];
×
1108
    if(!port || port->type != score::gfx::Types::Image)
×
1109
      continue;
×
1110
    auto rt = rl.renderTargetForInputPort(*port);
×
1111
    auto* item = qobject_cast<JS::TextureInletItem*>(texture_in->item());
×
1112
    if(item && rt.texture)
×
1113
      item->setSize(rt.texture->pixelSize());
×
1114
  }
×
1115

1116
  // (3) Now run loadState. Every ShaderEffectSource that resolves its
1117
  //     sourceItem to an inletItem during the stateVersion++ re-binding pass
1118
  //     will see a non-zero-sized source item and the first scene-graph sync
1119
  //     will create its QSGRhiLayer (qsgrhilayer.cpp:248-254 "!m_item ||
1120
  //     m_pixelSize.isEmpty()" branch is avoided).
1121
  if(const auto& on_load = m_object->loadState(); on_load.isCallable())
24 !
1122
  {
1123
    QVariantMap vm;
×
1124
    for(auto& [k, v]: node.m_modelState) {
×
1125
      if(auto res = v.apply(ossia::qt::ossia_to_qvariant{}); res.isValid())
×
1126
        vm[k] = std::move(res);
×
1127
    }
1128
    on_load.call({JS::variantToJs(*m_engine, vm)});
×
1129
  }
×
1130
}
24 ✔
1131

1132
void GpuNode::Engine::updateItemTextureOut(QQuickWindow* window)
24 ✔
1133
{
1134
  if(!m_object)
24 !
1135
    return;
×
1136
  if(auto texout = m_object->findChild<TextureOutlet*>(); texout != nullptr)
24 !
1137
  {
1138
    this->m_item = texout->item();
24 ✔
1139
    auto contentItem = window->contentItem();
24 ✔
1140

1141
    if(this->m_item && contentItem)
24 !
1142
    {
1143
      this->m_item->setParent(contentItem);
24 ✔
1144
      this->m_item->setParentItem(contentItem);
24 ✔
1145
    }
24 ✔
1146
  }
24 ✔
1147
}
24 ✔
1148

1149
void GpuNode::Engine::createItem(
24 ✔
1150
    GpuRenderer& renderer, GpuNode& node, score::gfx::RenderList& rl)
1151
{
1152
  m_component = new QQmlComponent{this->m_engine.get()};
24 !
1153

1154
  // Same route as the cpu node: a script that is still its file goes through
1155
  // the type loader, so the render thread gets an already compiled one rather
1156
  // than parsing it again for every renderer that wants it.
1157
  loadJSObjectFromString(node.m_root, node.source.toUtf8(), *m_component, false);
24 !
1158
  if(m_component->isError())
24 !
1159
  {
1160
    qWarning() << m_component->errorString();
×
1161
    return;
×
1162
  }
1163

1164
  auto obj = m_component->create();
24 ✔
1165
  m_object = qobject_cast<JS::Script*>(obj);
24 ✔
1166
  if(!m_object)
24 !
1167
  {
1168
    delete obj;
×
1169
    return;
×
1170
  }
1171

1172
  setupComponent(renderer, node, rl);
24 ✔
1173
}
24 ✔
1174

1175
void GpuNode::Engine::init(
24 ✔
1176
    GpuRenderer& renderer, GpuNode& node, QQuickWindow* window,
1177
    score::gfx::RenderList& rl)
1178
{
1179
  m_node = &node;
24 ✔
1180
  m_owner = &renderer;
24 ✔
1181
  // Claim before the component is instantiated: a script that sends to the UI
1182
  // from loadState() does it during createItem(), before the first tick().
1183
  m_publishing = node.claimPublisher(&renderer);
24 ✔
1184
  if(!m_item)
24 !
1185
  {
1186
    if(!m_engine)
24 !
1187
    {
1188
      m_engine = JS::acquireThreadLocalEngine([](QQmlEngine& newEngine) {
47 !
1189
        const auto& paths = score::AppContext().settings<Library::Settings::Model>().getIncludePaths();
23 ✔
1190
        for(auto& path : paths) {
23 !
1191
          newEngine.addImportPath(path);
×
1192
        }
1193

1194
        // setContextProperty does not take ownership: parent it to the engine,
1195
        // which is recreated whenever the last node on this thread lets it go.
1196
        auto utils = new JsUtils;
23 !
1197
        utils->setParent(&newEngine);
23 !
1198
        newEngine.rootContext()->setContextProperty("Util", utils);
23 !
1199
      });
23 ✔
1200
    }
24 ✔
1201
    if(!m_context)
24 !
1202
    {
1203
      m_context = new QQmlContext{m_engine.get()};
24 !
1204
      m_execFuncs = new DeviceContext{*m_engine, m_context};
24 !
1205
      m_execFuncs->init();
24 ✔
1206

1207
      m_context->setContextProperty("Device", m_execFuncs);
24 !
1208
      setupExecFuncs(this, &node, m_execFuncs->m_impl);
24 ✔
1209
    }
24 ✔
1210
    createItem(renderer, node, rl);
24 ✔
1211

1212
    // A render target that changes size is built again from scratch, and this
1213
    // item with it: its controls come up at whatever qml gave them, while the
1214
    // values the process holds were handed to the item that just went away.
1215
    // Give them to this one too -- a shape whose subdivision count arrives that
1216
    // way is otherwise built with none of them, and disappears.
1217
    restoreControls(node.m_lastState);
24 ✔
1218
  }
24 ✔
1219

1220
  updateItemTextureOut(window);
24 ✔
1221
}
24 ✔
1222

1223
score::gfx::NodeRenderer*
1224
GpuNode::createRenderer(score::gfx::RenderList& r) const noexcept
24 ✔
1225
{
1226
  auto res = new GpuRenderer{*this};
24 !
1227
  res->m_messages.enqueue(m_lastState);
24 !
1228
  return res;
24 ✔
1229
}
1230

1231
void GpuNode::process(score::gfx::Message&& msg)
907 ✔
1232
{
1233
  if(msg.input.size() == 1 && get_if<score::gfx::FunctionMessage>(&msg.input[0]))
907 !
1234
  {
1235
    // This changes the script
1236
    auto& fun = *get_if<score::gfx::FunctionMessage>(&msg.input[0]);
×
1237
    fun(*this);
×
1238
  }
×
1239
  else
1240
  {
1241
    m_lastState.node_id = msg.node_id;
907 ✔
1242
    m_lastState.token = msg.token;
907 ✔
1243

1244
    m_lastState.input.resize(msg.input.size());
907 ✔
1245
    for(int i = 0, N = msg.input.size(); i < N; i++)
915 ✔
1246
    {
1247
      if(!get_if<ossia::monostate>(&msg.input[i]))
8 ✔
1248
        m_lastState.input[i] = msg.input[i];
7 ✔
1249
    }
8 ✔
1250
  }
1251

1252
  for(auto renderer : renderedNodes)
1,734 ✔
1253
  {
1254
    auto r = safe_cast<GpuRenderer*>(renderer.second);
827 ✔
1255
    r->m_messages.enqueue(msg);
827 ✔
1256
  }
1257
}
907 ✔
1258

1259
gpu_exec_node::gpu_exec_node(Gfx::GfxExecutionAction& ctx)
30 ✔
1260
    : gfx_exec_node{ctx}
15 ✔
1261
{
15 ✔
1262
}
15 ✔
1263

1264
gpu_exec_node::~gpu_exec_node()
15 ✔
1265
{
×
1266
  exec_context->ui->unregister_node(id);
15 !
1267
}
15 ✔
1268

1269
std::string gpu_exec_node::label() const noexcept
×
1270
{
1271
  return "JS::gpu_exec_node";
×
1272
}
1273

1274
void gpu_exec_node::run(
942 ✔
1275
    const ossia::token_request& tk, ossia::exec_state_facade state) noexcept
1276
{
1277
  gfx_exec_node::run(tk, state);
942 ✔
1278
  if(!m_valueMessages)
942 !
1279
    return;
×
1280
  const auto [start, duration] = state.timings(tk);
942 ✔
1281
  GpuValueMessage message;
942 ✔
1282
  while(m_valueMessages->try_dequeue(message))
942 !
1283
  {
1284
    if(message.outlet < root_outputs().size())
×
1285
      if(auto port = root_outputs()[message.outlet]->target<ossia::value_port>())
×
1286
        port->write_value(std::move(message.value), start);
×
1287
  }
1288
}
942 ✔
1289

1290
std::unique_ptr<score::gfx::Node> gpu_exec_node::prepareScript(
15 ✔
1291
    const QString& root, const QString& str, JS::JSState&& new_state)
1292
{
1293
  // Runs from a queued execution command, i.e. on the execution thread while
1294
  // the UI thread may be deleting the JS process: nothing here may touch the
1295
  // process. Building the GpuNode (a QObject) here is fine as long as it only
1296
  // reads the exec node's own ports; it is wired to the process on the UI
1297
  // thread, in attachAndRegister.
1298
  exec_context->ui->unregister_node(id);
15 ✔
1299
  id = score::gfx::invalid_node_index;
15 ✔
1300
  m_valueMessages = std::make_shared<GpuValueQueue>();
15 ✔
1301

1302
  auto n = std::make_unique<JS::GpuNode>(
15 ✔
1303
      nullptr, std::move(new_state), root, str, this->root_inputs(),
15 ✔
1304
      this->root_outputs());
15 ✔
1305
  n->m_valueMessages = m_valueMessages;
15 ✔
1306

1307
  // A render target may be created after the controls' first execution tick.
1308
  // Seed its retained input snapshot instead of waiting for another change.
1309
  n->m_lastState.input.resize(root_inputs().size());
15 !
1310
  std::size_t controlIndex = 0;
15 ✔
1311
  for(std::size_t i = 0; i < root_inputs().size(); ++i)
19 ✔
1312
  {
1313
    auto& port = *root_inputs()[i];
4 ✔
1314
    if(port.target<ossia::value_port>())
4 !
1315
    {
1316
      const auto& value = controls[controlIndex++]->value;
4 ✔
1317
      if(value.valid())
4 !
1318
        n->m_lastState.input[i] = value;
4 ✔
1319
    }
4 ✔
1320
    else if(port.which() == ossia::texture_port::which)
×
1321
    {
1322
      // Setup render_target_spec. FIXME this should be done at a more general
1323
      // level, right now it's only done here and in avendish nodes
1324
      n->process(int32_t(i), static_cast<ossia::texture_inlet&>(port).data);
×
1325
    }
×
1326
  }
4 ✔
1327

1328
  n->moveToThread(qApp->thread());
15 !
1329
  return n;
15 ✔
1330
}
15 ✔
1331

1332
void gpu_exec_node::adoptId(int32_t new_id, int expected_script_index)
14 ✔
1333
{
1334
  if(script_index == expected_script_index)
14 !
1335
    id = new_id;
14 ✔
1336
  else
1337
    exec_context->ui->unregister_node(new_id);
×
1338
}
14 ✔
1339

1340
int32_t gpu_exec_node::attachAndRegister(
14 ✔
1341
    std::unique_ptr<score::gfx::Node> node, JS::ProcessModel& element)
1342
{
1343
  OSSIA_ENSURE_CURRENT_THREAD_KIND(ossia::thread_type::Ui);
14 ✔
1344
  auto* n = safe_cast<JS::GpuNode*>(node.get());
14 ✔
1345
  n->m_uiContext = &element;
14 ✔
1346
  // Nothing goes to the interface while the execution does not report back.
1347
  if(score::AppContext().settings<Scenario::Settings::Model>().getExecutionUpdate())
14 !
1348
    n->m_messageToUi = [ctx = QPointer{&element}](const QVariant& v) {
17 !
1349
      OSSIA_ENSURE_CURRENT_THREAD_KIND(ossia::thread_type::Ui);
3 ✔
1350
      if(!ctx)
3 !
NEW
1351
        return;
×
1352
      ctx->executionToUi(v);
3 ✔
1353
    };
3 ✔
1354

1355
  QObject::connect(
14 ✔
1356
      &element, &JS::ProcessModel::uiToExecution, n, &JS::GpuNode::uiMessage);
14 ✔
1357
  QObject::connect(
14 ✔
1358
      &element, &JS::ProcessModel::stateElementChanged, n,
14 ✔
1359
      &JS::GpuNode::stateElementChanged);
14 ✔
1360
  return exec_context->ui->register_node(std::move(node));
14 !
1361
}
×
1362
}
1363
#endif
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc