feat(qt): immersive shader scenes — RHI items, scene menu, GL link pairing

Port the immersive GPU scenes: Plasma, Tunnel, Aurora, Ambient, Spectral
Ribbon and Line Bed as QQuickRhiItems/ShaderEffects under a pulse-driven
ShaderSceneLayer, plus the Qt-only Tunnel Flow (Tauri Canvas2D port) fed
by the Viz16 stream. Scene rows live in the header view menu (no Off row);
g cycles the ring. A fresh immersive open defaults to Split > Lyrics
(owner ruling).

OpenGL link fix (owner smoke: Tunnel black with "uniform _22 declared as
type buf and type buf"): every ShaderEffect fragment with its own uniform
layout now ships a paired vertex stage declaring the identical block —
the shared spectrum.vert only ever linked under Vulkan.

RHI hardening: render pass descriptors on the ping-pong targets (the
Tunnel Flow segfault / Plasma dead window), mirrorVertically tied to the
backend (!== OpenGL), ribbon sub-uploads carry setSourceSize.

km
This commit is contained in:
vicrodh committed 2026-08-16 08:22:57 -06:00
1 parent 8bd02e35d3
commit e6c058c2f2
74 files changed
+6036 -111

No files matched your search

+2
View File
@@ -6624,6 +6624,7 @@ dependencies = [
"arboard",
"ash",
"async-trait",
"cc",
"cxx",
"cxx-qt",
"cxx-qt-build",
@@ -6664,6 +6665,7 @@ dependencies = [
"qbz-theme",
"qconnect-app",
"qconnect-transport-ws",
"qt-build-utils",
"rand 0.10.1",
"reqwest",
"rfd",
+7
View File
@@ -170,6 +170,13 @@ ksni = { version = "0.3", default-features = false, features = ["blocking", "asy
[build-dependencies]
cxx-qt-build = "0.7"
# A4 (Line Bed QQuickRhiItem): the crate's first hand-written C++
# (cxx/linebed_item.cpp). `qt-build-utils` provides moc + the Qt include
# paths — it is cxx-qt-build's OWN engine, already in the lock at the same
# version, so this adds no new package. `cc` compiles the static lib
# (likewise already in the lock).
qt-build-utils = "0.7"
cc = "1"
# macOS only: the Dock-icon activation policy behind the "Hide Dock icon when
# closed to menu bar" setting (Spotify behaviour — close puts the app in the
+100 -6
View File
@@ -42,6 +42,13 @@ const SHADER_GLSL_NO_ES100: &str = "300 es,310 es,320 es,120,150,440";
/// Opt out of `100 es` by putting this marker anywhere in the shader source.
const NO_ES100_MARKER: &str = "QSB-SKIP-GLES100";
/// Opt out of the `-b` batching rewrite for VERTEX shaders by putting this
/// marker anywhere in the source. The rewrite is only valid for Qt Quick
/// scene-graph-batched items (ShaderEffect stages); a custom
/// `QQuickRhiItem` (linebed.vert, A4) owns its attribute layout and the
/// rewrite would corrupt it.
const NO_BATCH_MARKER: &str = "QSB-SKIP-BATCH";
/// Is `out` already a current bake of `src`? True only when it exists and is
/// no older than BOTH the shader source and this build script — the script
/// because the variant lists and the `100 es` opt-out live here, so editing
@@ -144,15 +151,19 @@ fn build_shaders() {
if up_to_date(&src, &out) {
continue;
}
let glsl = match std::fs::read_to_string(&src) {
Ok(text) if text.contains(NO_ES100_MARKER) => SHADER_GLSL_NO_ES100,
_ => SHADER_GLSL,
let text = std::fs::read_to_string(&src).unwrap_or_default();
let glsl = if text.contains(NO_ES100_MARKER) {
SHADER_GLSL_NO_ES100
} else {
SHADER_GLSL
};
let mut cmd = std::process::Command::new(&qsb);
cmd.args(["--glsl", glsl, "--hlsl", SHADER_HLSL, "--msl", SHADER_MSL]);
// Vertex shaders used by Qt Quick need the batching rewrite, or the
// scene graph cannot batch the item and falls back per-node.
if ext == "vert" {
// scene graph cannot batch the item and falls back per-node —
// EXCEPT custom QQuickRhiItem stages, which own their attribute
// layout (NO_BATCH_MARKER).
if ext == "vert" && !text.contains(NO_BATCH_MARKER) {
cmd.arg("-b");
}
cmd.arg("-o").arg(&out).arg(&src);
@@ -241,6 +252,64 @@ fn format_ymd(epoch_secs: i64) -> String {
format!("{year:04}-{m:02}-{d:02}")
}
/// The hand-written C++ QQuickRhiItems: A4's `LineBedItem`, A2's
/// `PlasmaItem`, A3's `RibbonItem` and B1's `TunnelFlowItem` (`cxx/*_item.*`,
/// the scenes a ShaderEffect cannot express — line strips / feedback
/// ping-pong / persistent sub-rect texture writes — spec 01 §2.5/§2.1/§2.4,
/// spec 02 §3).
///
/// The crate had no non-cxx-qt C++ precedent (`src/macos_chrome.rs` is pure
/// Rust objc2), so this adds the minimal wiring: `moc` (the Q_OBJECT meta
/// object) and the Qt include paths come from `qt-build-utils` — already in
/// the lock as cxx-qt-build's own engine, same version — and the compile is
/// a plain `cc::Build` static lib that cargo links into the binary. The Qt
/// LINK libraries are already emitted by CxxQtBuilder below (Gui/Quick are
/// among its modules); this lib only adds objects.
///
/// The `<rhi/qrhi.h>` headers live in Qt's PRIVATE include tree
/// (`<headers>/Qt<Module>/<version>/Qt<Module>`), so those paths are added
/// explicitly. macOS note: the private-headers path exists in the same
/// layout under Homebrew Qt; NOT COMPILED HERE (this tree builds on Linux,
/// same caveat as the macOS objc2 arms).
fn build_rhi_items() {
let mut qtbuild = qt_build_utils::QtBuild::new(vec![
"Core".to_string(),
"Gui".to_string(),
"Qml".to_string(),
"Quick".to_string(),
])
.expect("Qt6 not found for the RHI items (cxx-qt-build would fail too)");
let mut cc = cc::Build::new();
cc.cpp(true)
.std("c++17")
.pic(true)
.include("cxx"); // the moc outputs do `#include "<name>.h"`
for item in ["linebed_item", "plasma_item", "ribbon_item", "tunnelflow_item"] {
let header = format!("cxx/{item}.h");
let source = format!("cxx/{item}.cpp");
println!("cargo:rerun-if-changed={header}");
println!("cargo:rerun-if-changed={source}");
// moc: the Q_OBJECT meta-object. No QML_ELEMENT (the types are
// registered by hand in the .cpps), so no uri/include-path
// arguments are needed.
let moc = qtbuild.moc(&header, qt_build_utils::MocArguments::default());
cc.file(source).file(&moc.cpp);
}
for p in qtbuild.include_paths() {
cc.include(p);
}
let headers = qtbuild.qmake_query("QT_INSTALL_HEADERS");
let version = qtbuild.version().to_string();
for module in ["QtCore", "QtGui", "QtQml", "QtQuick"] {
let private = format!("{headers}/{module}/{version}/{module}");
if Path::new(&private).is_dir() {
cc.include(private);
}
}
cc.compile("qbz_rhi_items");
}
fn main() {
// The About modal's build stamp. Emitted before anything else so a failure
// anywhere below cannot leave the env vars unset (env! is a compile error
@@ -251,6 +320,11 @@ fn main() {
// freshly compiled .qsb is the one that gets embedded.
build_shaders();
// The hand-written C++ QQuickRhiItems (cxx/). Static lib linked into
// the binary; the QML types self-register at QGuiApplication
// construction.
build_rhi_items();
// The WHOLE asset tree, recursively. This used to name the root-level
// files by hand with only icons/ and fonts/ collected, so dropping a new
// asset next to hi-res.svg compiled fine and then failed at runtime with
@@ -285,7 +359,7 @@ fn main() {
// (myqbz_qt.rs, blacklist_qt.rs, toast_qt.rs, …) are plain
// modules and must NOT be listed — only files that declare a
// #[cxx_qt::bridge] mod belong in this array.
rust_files: &["src/bridge.rs", "src/session_bridge.rs", "src/shell_bridge.rs", "src/player_bridge.rs", "src/queue_bridge.rs", "src/home_bridge.rs", "src/viz_bridge.rs", "src/immersive_bridge.rs", "src/suggestions_bridge.rs", "src/hotkeys_bridge.rs", "src/search_bridge.rs", "src/local_bridge.rs", "src/library_bridge.rs", "src/album_bridge.rs", "src/artist_bridge.rs", "src/scene_bridge.rs", "src/musician_bridge.rs", "src/lyrics_qt.rs", "src/icon_tint_qt.rs", "src/cast_bridge.rs", "src/myqbz_bridge.rs", "src/myqbz_add_bridge.rs", "src/disco_bridge.rs", "src/blacklist_bridge.rs", "src/playlist_picker_bridge.rs", "src/playlist_manager_bridge.rs", "src/playlist_import_bridge.rs", "src/dac_wizard_bridge.rs", "src/folder_edit_bridge.rs", "src/playlist_edit_bridge.rs", "src/qconnect_bridge.rs", "src/kiosk_nav_bridge.rs", "src/mini_bridge.rs", "src/tray_bridge.rs", "src/about_bridge.rs"],
rust_files: &["src/bridge.rs", "src/session_bridge.rs", "src/shell_bridge.rs", "src/player_bridge.rs", "src/queue_bridge.rs", "src/home_bridge.rs", "src/viz_bridge.rs", "src/immersive_bridge.rs", "src/shader_scene_bridge.rs", "src/suggestions_bridge.rs", "src/hotkeys_bridge.rs", "src/search_bridge.rs", "src/local_bridge.rs", "src/library_bridge.rs", "src/album_bridge.rs", "src/artist_bridge.rs", "src/scene_bridge.rs", "src/musician_bridge.rs", "src/lyrics_qt.rs", "src/icon_tint_qt.rs", "src/cast_bridge.rs", "src/myqbz_bridge.rs", "src/myqbz_add_bridge.rs", "src/disco_bridge.rs", "src/blacklist_bridge.rs", "src/playlist_picker_bridge.rs", "src/playlist_manager_bridge.rs", "src/playlist_import_bridge.rs", "src/dac_wizard_bridge.rs", "src/folder_edit_bridge.rs", "src/playlist_edit_bridge.rs", "src/qconnect_bridge.rs", "src/kiosk_nav_bridge.rs", "src/mini_bridge.rs", "src/tray_bridge.rs", "src/about_bridge.rs"],
qml_files: &[
"qml/LoginScreen.qml",
"qml/Main.qml",
@@ -427,6 +501,26 @@ fn main() {
"qml/immersive/ImmersiveView.qml",
"qml/immersive/LyricsFocusPanel.qml",
"qml/immersive/QueueTabsPanel.qml",
// Shader scenes (2026-08-15 immersive-completion contract,
// block A1): the bottom-most scene layer (Tunnel / Aurora /
// Ambient) driven by QbzShaderScene.
"qml/immersive/ShaderSceneLayer.qml",
// Block A4: the Line Bed scene (mode 5) — the QML wrapper
// for the C++ LineBedItem (cxx/linebed_item.*). Its own
// file so the RHI item's contract is one screen of QML.
"qml/immersive/LineBedScene.qml",
// Block A2: Plasma (scene 1) — QML wrapper for PlasmaItem
// (cxx/plasma_item.*), the WGSL->GLSL feedback port.
"qml/immersive/PlasmaScene.qml",
// Block A3: Spectral Ribbon (scene 4) — RibbonItem wrapper
// plus the stream/FFT overlay ported from
// ImmersiveSpectralOverlay.slint.
"qml/immersive/RibbonScene.qml",
"qml/immersive/SpectralOverlay.qml",
// Block B1: Tunnel Flow (scene 8, Qt-only) — the QML wrapper
// for the C++ TunnelFlowItem (cxx/tunnelflow_item.*), the
// Tauri Canvas2D tunnel ported to a feedback fragment shader.
"qml/immersive/TunnelFlowScene.qml",
"qml/immersive/SpectrumPanel.qml",
"qml/immersive/StaticPanel.qml",
"qml/immersive/SuggestionsPanel.qml",
+286
View File
@@ -0,0 +1,286 @@
// Line Bed (immersive shader scene, mode 5) — the QRhi renderer behind
// LineBedItem. Ports the Slint line-strip pipeline
// (crates/qbz/src/shader_underlay.rs:689-727) and its draw call
// (:995-998): 200 INSTANCED line strips of (255*6 + 1) = 1531 vertices
// each, alpha blending, the heights ring as an R32F texture sampled in the
// VERTEX stage. The vertex/instance ids the WGSL took from
// @builtin(vertex_index)/@builtin(instance_index) arrive here as two float
// vertex attributes (1531-vert template buffer + a 200-entry per-instance
// buffer) — the maximally portable spelling across GL/GLES/Vulkan/Metal/
// D3D under QRhi.
//
// Resource cadence (the pulse law): `synchronize` snapshots the QML-side
// properties when the item updates (pulse tick only), `render` uploads the
// heights texture only when a NEW ring arrived, and the draw itself is
// ~306K line vertices at 30 Hz — trivial next to a fullscreen fragment
// scene.
#include "linebed_item.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtGui/QVector4D>
#include <QtQml/qqml.h>
#include <rhi/qrhi.h>
#include <cstring>
#include <vector>
namespace {
// The lattice — pinned by FOUR files that must agree: here, linebed.vert
// (NUM_BANDS/SUBDIV), src/linebed_qt.rs (LINEBED_LINES/LINEBED_BANDS) and
// the Slint reference (shader_underlay.rs:47-54).
constexpr int LINEBED_LINES = 200;
constexpr int LINEBED_BANDS = 256;
constexpr int LINEBED_SUBDIV = 6;
constexpr int VERTS_PER_LINE = (LINEBED_BANDS - 1) * LINEBED_SUBDIV + 1; // 1531
constexpr qsizetype HEIGHTS_BYTES = LINEBED_LINES * LINEBED_BANDS * qsizetype(sizeof(float));
// std140: vec2 + vec4 + vec4. The GLSL block (linebed.vert/.frag, binding 0):
// layout(std140, binding = 0) uniform buf {
// vec2 resolution; // 0
// vec4 primary; // 16
// vec4 accent; // 32
// };
// The WGSL reference reads the full 144-byte scene block but uses only
// resolution (VS) and primary/accent (FS) — line_bed.wgsl is the one scene
// with no time/level/energy input, so the block is trimmed to what the
// shader reads. Same field VALUES at the same meaning.
struct UniformData
{
float res[2];
float pad[2];
float primary[4];
float accent[4];
};
QShader loadShader(const QString &qrcPath)
{
QFile f(qrcPath);
if (f.open(QIODevice::ReadOnly)) {
const QShader s = QShader::fromSerialized(f.readAll());
if (!s.isValid())
qWarning("[linebed] shader %s failed to deserialize", qPrintable(qrcPath));
return s;
}
qWarning("[linebed] shader %s not found in the qrc", qPrintable(qrcPath));
return QShader();
}
class LineBedRenderer : public QQuickRhiItemRenderer
{
public:
void initialize(QRhiCommandBuffer *cb) override
{
QRhi *r = cb->rhi();
if (m_vbuf) // already built (initialize can re-run on rhi changes;
return; // the rebuild path below drops everything first)
m_vbuf.reset(r->newBuffer(QRhiBuffer::Immutable,
QRhiBuffer::VertexBuffer,
VERTS_PER_LINE * quint32(sizeof(float))));
m_ibuf.reset(r->newBuffer(QRhiBuffer::Immutable,
QRhiBuffer::VertexBuffer,
LINEBED_LINES * quint32(sizeof(float))));
m_ubuf.reset(r->newBuffer(QRhiBuffer::Dynamic,
QRhiBuffer::UniformBuffer,
quint32(sizeof(UniformData))));
m_tex.reset(r->newTexture(QRhiTexture::R32F, QSize(LINEBED_BANDS, LINEBED_LINES)));
m_sampler.reset(r->newSampler(QRhiSampler::Nearest,
QRhiSampler::Nearest,
QRhiSampler::None,
QRhiSampler::ClampToEdge,
QRhiSampler::ClampToEdge));
if (!m_vbuf->create() || !m_ibuf->create() || !m_ubuf->create()
|| !m_tex->create() || !m_sampler->create()) {
qWarning("[linebed] resource creation failed — the scene stays dark");
m_vbuf.reset();
return;
}
m_srb.reset(r->newShaderResourceBindings());
m_srb->setBindings({
QRhiShaderResourceBinding::uniformBuffer(
0,
QRhiShaderResourceBinding::VertexStage
| QRhiShaderResourceBinding::FragmentStage,
m_ubuf.get()),
// Binding 4, like the reference's @binding(4) heights_tex.
QRhiShaderResourceBinding::sampledTexture(
4, QRhiShaderResourceBinding::VertexStage, m_tex.get(), m_sampler.get()),
});
if (!m_srb->create()) {
qWarning("[linebed] shader resource bindings failed — the scene stays dark");
m_vbuf.reset();
return;
}
QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
// The vertex templates: vid = subdivided point index along the line
// (0..1530), line = the depth row per instance (0..199).
std::vector<float> vid(VERTS_PER_LINE);
for (int i = 0; i < VERTS_PER_LINE; ++i)
vid[i] = float(i);
u->uploadStaticBuffer(m_vbuf.get(), 0,
quint32(vid.size() * sizeof(float)), vid.data());
std::vector<float> lines(LINEBED_LINES);
for (int i = 0; i < LINEBED_LINES; ++i)
lines[i] = float(i);
u->uploadStaticBuffer(m_ibuf.get(), 0,
quint32(lines.size() * sizeof(float)), lines.data());
// Flat bed until the first ring publish (the Rust ring starts
// zeroed too — linebed_qt.rs LineBedState::default).
const QByteArray zeros(int(HEIGHTS_BYTES), 0);
QRhiTextureSubresourceUploadDescription sub(zeros);
sub.setDataStride(LINEBED_BANDS * quint32(sizeof(float)));
u->uploadTexture(m_tex.get(),
QRhiTextureUploadDescription(QRhiTextureUploadEntry(0, 0, sub)));
cb->resourceUpdate(u);
}
void synchronize(QQuickRhiItem *item) override
{
// GUI thread: snapshot the item's properties. Runs on item update()
// (the pulse tick) and on geometry/rhi changes.
auto *lb = static_cast<LineBedItem *>(item);
const QByteArray h = lb->heights();
if (h.size() == HEIGHTS_BYTES && h != m_heights) {
m_heights = h;
m_heightsDirty = true;
}
const QColor p = lb->primary();
const QColor a = lb->accent();
m_primary = QVector4D(float(p.redF()), float(p.greenF()), float(p.blueF()), 1.0f);
m_accent = QVector4D(float(a.redF()), float(a.greenF()), float(a.blueF()), 1.0f);
}
void render(QRhiCommandBuffer *cb) override
{
if (!m_vbuf)
return; // resource creation failed in initialize
QRhiRenderTarget *rt = renderTarget();
if (!m_pipeline || rt->renderPassDescriptor() != m_passDescriptor) {
m_passDescriptor = rt->renderPassDescriptor();
buildPipeline();
if (!m_pipeline)
return;
}
QRhiResourceUpdateBatch *u = rhi()->nextResourceUpdateBatch();
if (m_heightsDirty) {
m_heightsDirty = false;
QRhiTextureSubresourceUploadDescription sub(m_heights);
sub.setDataStride(LINEBED_BANDS * quint32(sizeof(float)));
u->uploadTexture(m_tex.get(),
QRhiTextureUploadDescription(QRhiTextureUploadEntry(0, 0, sub)));
}
const QSize ps = rt->pixelSize();
UniformData ud = {};
ud.res[0] = float(ps.width());
ud.res[1] = float(ps.height());
std::memcpy(ud.primary, &m_primary, sizeof(ud.primary));
std::memcpy(ud.accent, &m_accent, sizeof(ud.accent));
u->updateDynamicBuffer(m_ubuf.get(), 0, quint32(sizeof(ud)), &ud);
// Opaque black clear, like the reference's LoadOp::Clear(BLACK):
// the scene OWNS the background while active (the atmosphere and
// panels gate themselves off), and the item composites opaquely
// (alphaBlending stays false). The FS alpha rides the explicit
// SrcAlpha blend of the pipeline, exactly wgpu ALPHA_BLENDING.
cb->beginPass(rt, QColor(0, 0, 0, 255), QRhiDepthStencilClearValue(1.0f, 0), u);
cb->setGraphicsPipeline(m_pipeline.get());
cb->setViewport(QRhiViewport(0, 0, float(ps.width()), float(ps.height())));
const QRhiCommandBuffer::VertexInput vbufs[] = {
QRhiCommandBuffer::VertexInput(m_vbuf.get(), 0),
QRhiCommandBuffer::VertexInput(m_ibuf.get(), 0),
};
cb->setShaderResources(m_srb.get());
cb->setVertexInput(0, 2, vbufs);
cb->draw(VERTS_PER_LINE, LINEBED_LINES); // 200 instanced strips of 1531
cb->endPass();
}
private:
void buildPipeline()
{
if (!m_pipeline)
m_pipeline.reset(rhi()->newGraphicsPipeline());
m_pipeline->setTopology(QRhiGraphicsPipeline::LineStrip);
m_pipeline->setCullMode(QRhiGraphicsPipeline::None);
m_pipeline->setDepthTest(false);
m_pipeline->setDepthWrite(false);
// wgpu BlendState::ALPHA_BLENDING verbatim.
QRhiGraphicsPipeline::TargetBlend blend;
blend.enable = true;
blend.srcColor = QRhiGraphicsPipeline::SrcAlpha;
blend.dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha;
blend.srcAlpha = QRhiGraphicsPipeline::One;
blend.dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha;
m_pipeline->setTargetBlends({ blend });
m_pipeline->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/linebed.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/linebed.frag.qsb")) },
});
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({
QRhiVertexInputBinding(quint32(sizeof(float))),
QRhiVertexInputBinding(quint32(sizeof(float)),
QRhiVertexInputBinding::PerInstance),
});
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float, 0 }, // vid
{ 1, 1, QRhiVertexInputAttribute::Float, 0 }, // line (per instance)
});
m_pipeline->setVertexInputLayout(inputLayout);
m_pipeline->setShaderResourceBindings(m_srb.get());
m_pipeline->setRenderPassDescriptor(m_passDescriptor);
if (!m_pipeline->create()) {
qWarning("[linebed] pipeline creation failed — the scene stays dark");
m_pipeline.reset();
}
}
std::unique_ptr<QRhiBuffer> m_vbuf;
std::unique_ptr<QRhiBuffer> m_ibuf;
std::unique_ptr<QRhiBuffer> m_ubuf;
std::unique_ptr<QRhiTexture> m_tex;
std::unique_ptr<QRhiSampler> m_sampler;
std::unique_ptr<QRhiShaderResourceBindings> m_srb;
std::unique_ptr<QRhiGraphicsPipeline> m_pipeline;
QRhiRenderPassDescriptor *m_passDescriptor = nullptr;
QByteArray m_heights;
bool m_heightsDirty = false;
// The Slint default palette (see the header) until synchronize() runs.
QVector4D m_primary{ 0.0f, 0.863f, 0.784f, 1.0f };
QVector4D m_accent{ 0.247f, 0.851f, 0.784f, 1.0f };
};
} // namespace
QQuickRhiItemRenderer *LineBedItem::createRenderer()
{
return new LineBedRenderer;
}
// QML type registration. The QML module is STATIC (linked into the
// binary), so there is no plugin load to hang this on: the startup function
// runs at QGuiApplication construction, BEFORE the engine loads the QML
// that names LineBedItem (ShaderSceneLayer.qml is compiled during the
// initial load; Component.onCompleted — where the singleton boots run — is
// already too late).
static bool g_linebedRegistered = false;
extern "C" void qbz_linebed_register_qml_type()
{
if (g_linebedRegistered)
return;
g_linebedRegistered = true;
qmlRegisterType<LineBedItem>("com.blitzfc.qbz", 1, 0, "LineBedItem");
}
Q_COREAPP_STARTUP_FUNCTION(qbz_linebed_register_qml_type)
+62
View File
@@ -0,0 +1,62 @@
// Line Bed (immersive shader scene, mode 5) — the GPU half. Block A4 of the
// 2026-08-15 immersive-completion contract (spec 01-shader-scenes-port.md
// §2.5). The project's FIRST QQuickRhiItem: the scene is not expressible as
// a ShaderEffect (fragment-only fullscreen quad) — it needs a LineStrip
// vertex stage with instancing and a vertex-sampled heights texture, the
// exact shape of the Slint linestrip pipeline
// (crates/qbz/src/shader_underlay.rs:689-727).
//
// The CPU half (the 512→256 reshape + the 200-deep ring) is Rust
// (src/linebed_qt.rs, a LineBedState port); the ring arrives per pulse tick
// through the `heights` property as raw f32 bytes (256x200, row 0 =
// newest). The palette rides the shell's ambient colors like every other
// scene (QbzShell.ambientPrimary/Accent, bound in LineBedScene.qml).
//
// Compiled by crates/qbz-qt/build.rs (moc via qt-build-utils + cc — the
// first hand-written C++ in this crate; cxx-qt's generated glue aside).
// Registered as QML type `LineBedItem` in `com.blitzfc.qbz` 1.0 at
// QGuiApplication construction (Q_COREAPP_STARTUP_FUNCTION in the .cpp),
// with `qbz_linebed_register_qml_type` as the Rust-reachable link anchor.
#ifndef QBZ_LINEBED_ITEM_H
#define QBZ_LINEBED_ITEM_H
#include <QtCore/QByteArray>
#include <QtGui/QColor>
#include <QtQuick/QQuickRhiItem>
class LineBedItem : public QQuickRhiItem
{
Q_OBJECT
// No NOTIFY anywhere: the QML wrapper writes `heights` only on the
// pulse edge and calls update() right after (the pulse law — nothing
// here may schedule its own repaint), and nobody binds these.
Q_PROPERTY(QByteArray heights READ heights WRITE setHeights)
Q_PROPERTY(QColor primary READ primary WRITE setPrimary)
Q_PROPERTY(QColor accent READ accent WRITE setAccent)
public:
explicit LineBedItem(QQuickItem *parent = nullptr)
: QQuickRhiItem(parent)
{
}
QByteArray heights() const { return m_heights; }
void setHeights(const QByteArray &heights) { m_heights = heights; }
QColor primary() const { return m_primary; }
void setPrimary(const QColor &c) { m_primary = c; }
QColor accent() const { return m_accent; }
void setAccent(const QColor &c) { m_accent = c; }
QQuickRhiItemRenderer *createRenderer() override;
private:
QByteArray m_heights;
// The Slint defaults (shader_underlay.rs:121-129 Palette::DEFAULT
// #00dcc8 / #3fd9c8 — `secondary` is unused by this scene), so the bed
// opened before the first album-art palette resolves still looks right.
QColor m_primary{ 0, 220, 200 };
QColor m_accent{ 63, 217, 200 };
};
#endif // QBZ_LINEBED_ITEM_H
+417
View File
@@ -0,0 +1,417 @@
// Plasma (immersive shader scene, mode 1) — the QRhi renderer behind
// PlasmaItem. Ports the Slint feedback loop (crates/qbz/src/
// shader_underlay.rs:1003-1025: render the frame sampling the history
// texture, then copy it back) as a PING-PONG over two owned RGBA8 textures
// (the reference's TEX_FORMAT Rgba8Unorm, shader_underlay.rs:39): pass 1
// renders the plasma into history[write] sampling history[read], pass 2
// blits history[write] into the item's render target, then the indices
// swap. Owning both targets means the item's texture is never read back and
// no Qt-internal attachment is touched.
//
// Resource cadence (the pulse law): `synchronize` snapshots the QML-side
// properties when the item updates (pulse tick only); per frame the GPU
// work is one uniform upload + two fullscreen triangles — cheaper than any
// of the ShaderEffect scenes.
//
// History size tracks the item's physical size CAPPED at 2560x1440 (the
// reference's offscreen-target ceiling, shader_underlay.rs:37-39; the
// ShaderSceneLayer resW/resH rule); on a bigger screen the blit upscales.
// A resize rebuilds the pair and re-clears it (the field restarts — the
// same thing the reference gets when its window-size-tracking resources
// rebuild, shader_underlay.rs:522-523).
#include "plasma_item.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtQml/qqml.h>
#include <rhi/qrhi.h>
#include <cstring>
namespace {
// The history-target ceiling (see the header).
constexpr int MAX_W = 2560;
constexpr int MAX_H = 1440;
// The FULL 144-byte std140 scene block (spec 01 §1) — plasma.frag declares
// every field even though it reads only some; the unread ones stay zero.
struct UniformData
{
float time; // 0
float phase; // 4
float beat; // 8
float level; // 12
float res[2]; // 16
float levelSmooth; // 24
float transient; // 28
float energyLo[4]; // 32
float energyHi[4]; // 48
float bandsLo[4]; // 64
float bandsHi[4]; // 80
float primary[4]; // 96
float secondary[4];// 112
float accent[4]; // 128
};
static_assert(sizeof(UniformData) == 144, "std140 scene block");
QShader loadShader(const QString &qrcPath)
{
QFile f(qrcPath);
if (f.open(QIODevice::ReadOnly)) {
const QShader s = QShader::fromSerialized(f.readAll());
if (!s.isValid())
qWarning("[plasma] shader %s failed to deserialize", qPrintable(qrcPath));
return s;
}
qWarning("[plasma] shader %s not found in the qrc", qPrintable(qrcPath));
return QShader();
}
QVector4D colorVec(const QColor &c)
{
return QVector4D(float(c.redF()), float(c.greenF()), float(c.blueF()), 1.0f);
}
class PlasmaRenderer : public QQuickRhiItemRenderer
{
public:
~PlasmaRenderer() override
{
// The render pass descriptors are OURS (the RTs borrow them).
delete m_histRpDesc[0];
delete m_histRpDesc[1];
}
void initialize(QRhiCommandBuffer *cb) override
{
QRhi *r = cb->rhi();
if (m_vbuf) // already built (initialize can re-run on rhi changes;
return; // the rebuild path drops everything first)
// The fullscreen triangle (rhi_triangle.vert replaces gl_VertexID
// with this buffer — the GLES 3.0-portable spelling, linebed
// idiom). Shared by the feedback AND blit passes.
static const float TRI[] = { -1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f };
m_vbuf.reset(r->newBuffer(QRhiBuffer::Immutable,
QRhiBuffer::VertexBuffer,
quint32(sizeof(TRI))));
m_ubuf.reset(r->newBuffer(QRhiBuffer::Dynamic,
QRhiBuffer::UniformBuffer,
quint32(sizeof(UniformData))));
m_sampler.reset(r->newSampler(QRhiSampler::Linear,
QRhiSampler::Linear,
QRhiSampler::None,
QRhiSampler::ClampToEdge,
QRhiSampler::ClampToEdge));
if (!m_vbuf->create() || !m_ubuf->create() || !m_sampler->create()) {
qWarning("[plasma] resource creation failed — the scene stays dark");
m_vbuf.reset();
return;
}
QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
u->uploadStaticBuffer(m_vbuf.get(), TRI);
cb->resourceUpdate(u);
}
void synchronize(QQuickRhiItem *item) override
{
// GUI thread: snapshot the item's properties. Runs on item update()
// (the pulse tick) and on geometry/rhi changes.
auto *pl = static_cast<PlasmaItem *>(item);
m_time = pl->m_time;
m_beat = pl->m_beat;
m_level = pl->m_level;
m_levelSmooth = pl->m_levelSmooth;
m_energyLo = pl->m_energyLo;
m_energyHi = pl->m_energyHi;
m_primary = colorVec(pl->m_primary);
m_secondary = colorVec(pl->m_secondary);
m_accent = colorVec(pl->m_accent);
}
void render(QRhiCommandBuffer *cb) override
{
if (!m_vbuf)
return; // resource creation failed in initialize
QRhiRenderTarget *rt = renderTarget();
const QSize ps = rt->pixelSize();
if (ps.isEmpty())
return;
const QSize hist = capped(ps);
if (hist != m_histSize)
rebuildHistory(hist);
if (!m_hist[0])
return; // history creation failed — stay dark
// Pipeline A (plasma) renders into the history pair's pass; pipeline
// B (blit) into the item's. Rebuild each when its descriptor moves.
if (!m_plasmaPipe || m_histRt[0]->renderPassDescriptor() != m_plasmaPassDescriptor) {
m_plasmaPassDescriptor = m_histRt[0]->renderPassDescriptor();
buildPlasmaPipeline();
if (!m_plasmaPipe)
return;
}
if (!m_blitPipe || rt->renderPassDescriptor() != m_blitPassDescriptor) {
m_blitPassDescriptor = rt->renderPassDescriptor();
buildBlitPipeline();
if (!m_blitPipe)
return;
}
QRhiResourceUpdateBatch *u = rhi()->nextResourceUpdateBatch();
UniformData ud = {};
ud.time = m_time;
ud.beat = m_beat;
ud.level = m_level;
ud.res[0] = float(hist.width());
ud.res[1] = float(hist.height());
ud.levelSmooth = m_levelSmooth;
std::memcpy(ud.energyLo, &m_energyLo, sizeof(ud.energyLo));
std::memcpy(ud.energyHi, &m_energyHi, sizeof(ud.energyHi));
std::memcpy(ud.primary, &m_primary, sizeof(ud.primary));
std::memcpy(ud.secondary, &m_secondary, sizeof(ud.secondary));
std::memcpy(ud.accent, &m_accent, sizeof(ud.accent));
u->updateDynamicBuffer(m_ubuf.get(), 0, quint32(sizeof(ud)), &ud);
// A fresh pair starts BLACK (the reference's history starts
// zero-filled too — an unsampled-cleared first frame would advect
// garbage).
if (m_needClear) {
m_needClear = false;
for (int i = 0; i < 2; ++i) {
cb->beginPass(m_histRt[i].get(), QColor(0, 0, 0, 255),
QRhiDepthStencilClearValue(1.0f, 0), nullptr);
cb->endPass();
}
}
const int read = m_read;
const int write = 1 - m_read;
// Pass 1: plasma into history[write], sampling history[read].
cb->beginPass(m_histRt[write].get(), QColor(0, 0, 0, 255),
QRhiDepthStencilClearValue(1.0f, 0), u);
cb->setGraphicsPipeline(m_plasmaPipe.get());
cb->setViewport(QRhiViewport(0, 0, float(hist.width()), float(hist.height())));
cb->setShaderResources(m_srbPlasma[read].get());
const QRhiCommandBuffer::VertexInput tri(m_vbuf.get(), 0);
cb->setVertexInput(0, 1, &tri);
cb->draw(3);
cb->endPass();
// Pass 2: blit history[write] into the item target (the composite).
cb->beginPass(rt, QColor(0, 0, 0, 255), QRhiDepthStencilClearValue(1.0f, 0), nullptr);
cb->setGraphicsPipeline(m_blitPipe.get());
cb->setViewport(QRhiViewport(0, 0, float(ps.width()), float(ps.height())));
cb->setShaderResources(m_srbBlit[write].get());
cb->setVertexInput(0, 1, &tri);
cb->draw(3);
cb->endPass();
m_read = write;
}
private:
static QSize capped(const QSize &ps)
{
if (ps.width() <= MAX_W && ps.height() <= MAX_H)
return ps;
const double s = qMin(double(MAX_W) / ps.width(), double(MAX_H) / ps.height());
return QSize(qMax(1, int(ps.width() * s)), qMax(1, int(ps.height() * s)));
}
// (Re)build the ping-pong pair + its render targets + both SRB sets.
// Old resources go through deleteLater() — an in-flight frame may still
// reference them (QRhiResource::deleteLater is the documented deferral).
void rebuildHistory(const QSize &size)
{
QRhi *r = rhi();
for (int i = 0; i < 2; ++i) {
if (m_hist[i])
m_hist[i].release()->deleteLater();
if (m_histRt[i])
m_histRt[i].release()->deleteLater();
if (m_srbPlasma[i])
m_srbPlasma[i].release()->deleteLater();
if (m_srbBlit[i])
m_srbBlit[i].release()->deleteLater();
}
if (m_plasmaPipe)
m_plasmaPipe.release()->deleteLater();
m_plasmaPassDescriptor = nullptr;
m_histSize = size;
m_needClear = true;
m_read = 0;
for (int i = 0; i < 2; ++i) {
m_hist[i].reset(r->newTexture(QRhiTexture::RGBA8, size));
if (!m_hist[i]->create()) {
qWarning("[plasma] history texture creation failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
// Vulkan/D3D/Metal REQUIRE a render pass descriptor before
// create(); without it the RT creation fails and the later
// beginPass corrupts the whole window (2026-08-15 owner smoke:
// Plasma left a transparent, unusable window). The RT does NOT
// own the descriptor — free the previous one on rebuild.
if (m_histRpDesc[i]) {
delete m_histRpDesc[i];
m_histRpDesc[i] = nullptr;
}
m_histRt[i].reset(r->newTextureRenderTarget({ m_hist[i].get() }));
m_histRpDesc[i] = m_histRt[i]->newCompatibleRenderPassDescriptor();
m_histRt[i]->setRenderPassDescriptor(m_histRpDesc[i]);
if (!m_histRt[i]->create()) {
qWarning("[plasma] history render target failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
}
// SRB sets: plasma binds ubuf(0) + the READ texture(1); the blit
// binds only the WRITE texture(1) (its shader declares nothing
// else). Both bilinear (the reference's prev_samp is bilinear).
for (int i = 0; i < 2; ++i) {
m_srbPlasma[i].reset(r->newShaderResourceBindings());
m_srbPlasma[i]->setBindings({
QRhiShaderResourceBinding::uniformBuffer(
0,
QRhiShaderResourceBinding::VertexStage
| QRhiShaderResourceBinding::FragmentStage,
m_ubuf.get()),
QRhiShaderResourceBinding::sampledTexture(
1, QRhiShaderResourceBinding::FragmentStage,
m_hist[i].get(), m_sampler.get()),
});
m_srbBlit[i].reset(r->newShaderResourceBindings());
m_srbBlit[i]->setBindings({
QRhiShaderResourceBinding::sampledTexture(
1, QRhiShaderResourceBinding::FragmentStage,
m_hist[i].get(), m_sampler.get()),
});
if (!m_srbPlasma[i]->create() || !m_srbBlit[i]->create()) {
qWarning("[plasma] shader resource bindings failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
}
}
void setVertexLayout(QRhiGraphicsPipeline *pipe)
{
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({ QRhiVertexInputBinding(quint32(2 * sizeof(float))) });
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float2, 0 }, // pos
});
pipe->setVertexInputLayout(inputLayout);
}
void buildPlasmaPipeline()
{
if (!m_plasmaPipe)
m_plasmaPipe.reset(rhi()->newGraphicsPipeline());
m_plasmaPipe->setTopology(QRhiGraphicsPipeline::Triangles);
m_plasmaPipe->setCullMode(QRhiGraphicsPipeline::None);
m_plasmaPipe->setDepthTest(false);
m_plasmaPipe->setDepthWrite(false);
// OPAQUE output (the FS writes alpha 1; the scene owns the
// background while active — the linebed header documents the same
// choice for its explicit blend).
m_plasmaPipe->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/rhi_triangle.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/plasma.frag.qsb")) },
});
setVertexLayout(m_plasmaPipe.get());
m_plasmaPipe->setShaderResourceBindings(m_srbPlasma[0].get());
m_plasmaPipe->setRenderPassDescriptor(m_plasmaPassDescriptor);
if (!m_plasmaPipe->create()) {
qWarning("[plasma] pipeline creation failed — the scene stays dark");
m_plasmaPipe.reset();
}
}
void buildBlitPipeline()
{
if (!m_blitPipe)
m_blitPipe.reset(rhi()->newGraphicsPipeline());
m_blitPipe->setTopology(QRhiGraphicsPipeline::Triangles);
m_blitPipe->setCullMode(QRhiGraphicsPipeline::None);
m_blitPipe->setDepthTest(false);
m_blitPipe->setDepthWrite(false);
m_blitPipe->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/rhi_triangle.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/plasma_blit.frag.qsb")) },
});
setVertexLayout(m_blitPipe.get());
m_blitPipe->setShaderResourceBindings(m_srbBlit[0].get());
m_blitPipe->setRenderPassDescriptor(m_blitPassDescriptor);
if (!m_blitPipe->create()) {
qWarning("[plasma] blit pipeline creation failed — the scene stays dark");
m_blitPipe.reset();
}
}
std::unique_ptr<QRhiBuffer> m_vbuf;
std::unique_ptr<QRhiBuffer> m_ubuf;
std::unique_ptr<QRhiSampler> m_sampler;
std::unique_ptr<QRhiTexture> m_hist[2];
std::unique_ptr<QRhiTextureRenderTarget> m_histRt[2];
// Render pass descriptors owned BY US (the RT borrows them) — see the
// rebuild loop. Raw pointers, freed on rebuild.
QRhiRenderPassDescriptor *m_histRpDesc[2] = { nullptr, nullptr };
std::unique_ptr<QRhiShaderResourceBindings> m_srbPlasma[2];
std::unique_ptr<QRhiShaderResourceBindings> m_srbBlit[2];
std::unique_ptr<QRhiGraphicsPipeline> m_plasmaPipe;
std::unique_ptr<QRhiGraphicsPipeline> m_blitPipe;
QRhiRenderPassDescriptor *m_plasmaPassDescriptor = nullptr;
QRhiRenderPassDescriptor *m_blitPassDescriptor = nullptr;
QSize m_histSize;
int m_read = 0;
bool m_needClear = true;
// synchronize() snapshots.
float m_time = 0.0f;
float m_beat = 0.0f;
float m_level = 0.0f;
float m_levelSmooth = 0.0f;
QVector4D m_energyLo{ 0.0f, 0.0f, 0.0f, 0.0f };
QVector4D m_energyHi{ 0.0f, 0.0f, 0.0f, 0.0f };
QVector4D m_primary{ 0.0f, 0.863f, 0.784f, 1.0f };
QVector4D m_secondary{ 0.588f, 0.196f, 1.0f, 1.0f };
QVector4D m_accent{ 0.247f, 0.851f, 0.784f, 1.0f };
};
} // namespace
QQuickRhiItemRenderer *PlasmaItem::createRenderer()
{
return new PlasmaRenderer;
}
// QML type registration — the linebed_item.cpp idiom: the module is STATIC,
// so a startup function runs at QGuiApplication construction, BEFORE the
// engine loads the QML that names PlasmaItem.
static bool g_plasmaRegistered = false;
extern "C" void qbz_plasma_register_qml_type()
{
if (g_plasmaRegistered)
return;
g_plasmaRegistered = true;
qmlRegisterType<PlasmaItem>("com.blitzfc.qbz", 1, 0, "PlasmaItem");
}
Q_COREAPP_STARTUP_FUNCTION(qbz_plasma_register_qml_type)
+50
View File
@@ -0,0 +1,50 @@
// Plasma (immersive shader scene, mode 1) — the QQuickRhiItem behind the
// feedback fluid. Block A2 of the 2026-08-15 immersive-completion contract
// (spec 01 §2.1). Second hand-written C++ item after LineBedItem
// (cxx/linebed_item.h carries the why-C++ rationale: a ShaderEffect cannot
// own a feedback texture pair).
//
// QML properties are MEMBER-only (no NOTIFY): the QML wrapper
// (PlasmaScene.qml) writes them on the pulse edge and calls update()
// itself — the same cadence contract as LineBedItem.
//
// Registered as QML type `PlasmaItem` in `com.blitzfc.qbz` 1.0 (see the
// .cpp).
#pragma once
#include <QtGui/QColor>
#include <QtGui/QVector4D>
#include <QtQuick/QQuickRhiItem>
class PlasmaItem : public QQuickRhiItem
{
Q_OBJECT
Q_PROPERTY(float time MEMBER m_time)
Q_PROPERTY(float beat MEMBER m_beat)
Q_PROPERTY(float level MEMBER m_level)
Q_PROPERTY(float levelSmooth MEMBER m_levelSmooth)
Q_PROPERTY(QVector4D energyLo MEMBER m_energyLo)
Q_PROPERTY(QVector4D energyHi MEMBER m_energyHi)
Q_PROPERTY(QColor primary MEMBER m_primary)
Q_PROPERTY(QColor secondary MEMBER m_secondary)
Q_PROPERTY(QColor accent MEMBER m_accent)
public:
explicit PlasmaItem(QQuickItem *parent = nullptr) : QQuickRhiItem(parent) {}
QQuickRhiItemRenderer *createRenderer() override;
// Member snapshots the renderer reads in synchronize(). Defaults are the
// Slint palette (shader_underlay.rs:121-129) so a pre-art track still
// looks right.
float m_time = 0.0f;
float m_beat = 0.0f;
float m_level = 0.0f;
float m_levelSmooth = 0.0f;
QVector4D m_energyLo{ 0.0f, 0.0f, 0.0f, 0.0f };
QVector4D m_energyHi{ 0.0f, 0.0f, 0.0f, 0.0f };
QColor m_primary{ 0, 220, 200 };
QColor m_secondary{ 150, 50, 255 };
QColor m_accent{ 63, 217, 200 };
};
+280
View File
@@ -0,0 +1,280 @@
// Spectral Ribbon (immersive shader scene, mode 4) — the QRhi renderer
// behind RibbonItem. Ports the spectrogram half of the Slint pipeline
// (crates/qbz/src/shader_underlay.rs:855-929): a persistent R8 texture
// (512 freq bands wide × 2048 time columns tall, SPECTRO_BANDS/COLS
// verbatim), one 512-byte row written at the playback-time column per
// frame, the SAME gap-fill (progress updates ~1 Hz, so the column jumps
// several slots — every skipped column gets the row), and a full clear on
// track change/seek (the reset flag). The shader is only a colorizer
// (spectral_ribbon.frag).
//
// Unlike the reference (which resets a thread-local LAST_COL on clear),
// the last-column state lives HERE, next to the texture it describes.
//
// Resource cadence (the pulse law): `synchronize` snapshots the frame
// QByteArray when the item updates (pulse tick only); `render` uploads the
// 512 B row (or the 1 MB clear, rare) and draws ONE fullscreen triangle.
#include "ribbon_item.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtQml/qqml.h>
#include <rhi/qrhi.h>
#include <cstring>
namespace {
// The lattice — pinned with spectral_ribbon.frag, src/shader_scene_bridge.rs
// (the frame publisher) and the Slint reference (shader_underlay.rs:44-45).
constexpr int SPECTRO_BANDS = 512;
constexpr int SPECTRO_COLS = 2048;
constexpr qsizetype FRAME_BYTES = 4 + 1 + SPECTRO_BANDS;
// The FULL 144-byte std140 scene block (spec 01 §1) — the ribbon reads only
// energyHi.y (the real-time ceiling line); the rest arrives zeroed except
// resolution.
struct UniformData
{
float time; // 0
float phase; // 4
float beat; // 8
float level; // 12
float res[2]; // 16
float levelSmooth; // 24
float transient; // 28
float energyLo[4]; // 32
float energyHi[4]; // 48
float bandsLo[4]; // 64
float bandsHi[4]; // 80
float primary[4]; // 96
float secondary[4];// 112
float accent[4]; // 128
};
static_assert(sizeof(UniformData) == 144, "std140 scene block");
QShader loadShader(const QString &qrcPath)
{
QFile f(qrcPath);
if (f.open(QIODevice::ReadOnly)) {
const QShader s = QShader::fromSerialized(f.readAll());
if (!s.isValid())
qWarning("[ribbon] shader %s failed to deserialize", qPrintable(qrcPath));
return s;
}
qWarning("[ribbon] shader %s not found in the qrc", qPrintable(qrcPath));
return QShader();
}
class RibbonRenderer : public QQuickRhiItemRenderer
{
public:
void initialize(QRhiCommandBuffer *cb) override
{
QRhi *r = cb->rhi();
if (m_vbuf) // already built (initialize can re-run on rhi changes)
return;
static const float TRI[] = { -1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f };
m_vbuf.reset(r->newBuffer(QRhiBuffer::Immutable,
QRhiBuffer::VertexBuffer,
quint32(sizeof(TRI))));
m_ubuf.reset(r->newBuffer(QRhiBuffer::Dynamic,
QRhiBuffer::UniformBuffer,
quint32(sizeof(UniformData))));
m_tex.reset(r->newTexture(QRhiTexture::R8, QSize(SPECTRO_BANDS, SPECTRO_COLS)));
// Bilinear — the reference's `samp` smooths between bands/columns.
m_sampler.reset(r->newSampler(QRhiSampler::Linear,
QRhiSampler::Linear,
QRhiSampler::None,
QRhiSampler::ClampToEdge,
QRhiSampler::ClampToEdge));
if (!m_vbuf->create() || !m_ubuf->create() || !m_tex->create()
|| !m_sampler->create()) {
qWarning("[ribbon] resource creation failed — the scene stays dark");
m_vbuf.reset();
return;
}
m_srb.reset(r->newShaderResourceBindings());
m_srb->setBindings({
QRhiShaderResourceBinding::uniformBuffer(
0,
QRhiShaderResourceBinding::VertexStage
| QRhiShaderResourceBinding::FragmentStage,
m_ubuf.get()),
// Binding 3, like the reference's @binding(3) spectrogram.
QRhiShaderResourceBinding::sampledTexture(
3, QRhiShaderResourceBinding::FragmentStage, m_tex.get(), m_sampler.get()),
});
if (!m_srb->create()) {
qWarning("[ribbon] shader resource bindings failed — the scene stays dark");
m_vbuf.reset();
return;
}
QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
u->uploadStaticBuffer(m_vbuf.get(), TRI);
cb->resourceUpdate(u);
m_needClear = true; // the texture starts UNDEFINED — clear on frame 1
}
void synchronize(QQuickRhiItem *item) override
{
// GUI thread: snapshot the item's properties (pulse tick only).
auto *rb = static_cast<RibbonItem *>(item);
m_frame = rb->m_frame;
m_energyHi = rb->m_energyHi;
}
void render(QRhiCommandBuffer *cb) override
{
if (!m_vbuf)
return;
QRhiRenderTarget *rt = renderTarget();
if (!m_pipeline || rt->renderPassDescriptor() != m_passDescriptor) {
m_passDescriptor = rt->renderPassDescriptor();
buildPipeline();
if (!m_pipeline)
return;
}
QRhiResourceUpdateBatch *u = rhi()->nextResourceUpdateBatch();
if (m_needClear) {
m_needClear = false;
uploadClear(u);
}
// The pending frame: [col u32 LE][reset u8][512 row bytes].
if (m_frame.size() == FRAME_BYTES) {
const auto *p = reinterpret_cast<const uchar *>(m_frame.constData());
const quint32 col = quint32(p[0]) | (quint32(p[1]) << 8)
| (quint32(p[2]) << 16) | (quint32(p[3]) << 24);
if (p[4] != 0)
uploadClear(u);
uploadRow(u, p + 5, int(col));
m_frame.clear();
}
const QSize ps = rt->pixelSize();
UniformData ud = {};
ud.res[0] = float(ps.width());
ud.res[1] = float(ps.height());
std::memcpy(ud.energyHi, &m_energyHi, sizeof(ud.energyHi));
u->updateDynamicBuffer(m_ubuf.get(), 0, quint32(sizeof(ud)), &ud);
// Opaque clear (#03070c comes from the shader itself for the
// margins; the clear colour only covers a degenerate frame).
cb->beginPass(rt, QColor(3, 7, 12, 255), QRhiDepthStencilClearValue(1.0f, 0), u);
cb->setGraphicsPipeline(m_pipeline.get());
cb->setViewport(QRhiViewport(0, 0, float(ps.width()), float(ps.height())));
cb->setShaderResources(m_srb.get());
const QRhiCommandBuffer::VertexInput tri(m_vbuf.get(), 0);
cb->setVertexInput(0, 1, &tri);
cb->draw(3);
cb->endPass();
}
private:
// Full-texture zero — track change / seek (shader_underlay.rs:859-883).
// Resets the gap-fill cursor, like the reference's SPECTRO_LAST_COL.set(0).
void uploadClear(QRhiResourceUpdateBatch *u)
{
m_lastCol = 0;
const QByteArray zeros(SPECTRO_BANDS * SPECTRO_COLS, 0);
QRhiTextureSubresourceUploadDescription sub(zeros);
sub.setDataStride(SPECTRO_BANDS);
u->uploadTexture(m_tex.get(),
QRhiTextureUploadDescription(QRhiTextureUploadEntry(0, 0, sub)));
}
// The row write + gap-fill (shader_underlay.rs:884-927): every column
// skipped since the last write gets THIS row (progress updates ~1 Hz,
// so the column jumps several slots between ticks).
void uploadRow(QRhiResourceUpdateBatch *u, const uchar *row, int col)
{
col = qBound(0, col, SPECTRO_COLS - 1);
const int start = col > m_lastCol ? m_lastCol + 1 : col;
const int count = col + 1 - start;
QByteArray data;
data.resize(SPECTRO_BANDS * count);
for (int i = 0; i < count; ++i)
std::memcpy(data.data() + i * SPECTRO_BANDS, row, SPECTRO_BANDS);
QRhiTextureSubresourceUploadDescription sub(data);
sub.setDataStride(SPECTRO_BANDS);
sub.setDestinationTopLeft(QPoint(0, start));
// The partial upload NEEDS the explicit source size: without it the
// deduced region is wrong (the rows never landed — the 2026-08-15
// "axes but empty plot" bug; the full-texture clear painted fine).
sub.setSourceSize(QSize(SPECTRO_BANDS, count));
u->uploadTexture(m_tex.get(),
QRhiTextureUploadDescription(QRhiTextureUploadEntry(0, 0, sub)));
m_lastCol = col;
}
void buildPipeline()
{
if (!m_pipeline)
m_pipeline.reset(rhi()->newGraphicsPipeline());
m_pipeline->setTopology(QRhiGraphicsPipeline::Triangles);
m_pipeline->setCullMode(QRhiGraphicsPipeline::None);
m_pipeline->setDepthTest(false);
m_pipeline->setDepthWrite(false);
// Opaque output (the FS writes alpha 1; the scene owns the
// background while active).
m_pipeline->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/rhi_triangle.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/spectral_ribbon.frag.qsb")) },
});
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({ QRhiVertexInputBinding(quint32(2 * sizeof(float))) });
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float2, 0 }, // pos
});
m_pipeline->setVertexInputLayout(inputLayout);
m_pipeline->setShaderResourceBindings(m_srb.get());
m_pipeline->setRenderPassDescriptor(m_passDescriptor);
if (!m_pipeline->create()) {
qWarning("[ribbon] pipeline creation failed — the scene stays dark");
m_pipeline.reset();
}
}
std::unique_ptr<QRhiBuffer> m_vbuf;
std::unique_ptr<QRhiBuffer> m_ubuf;
std::unique_ptr<QRhiTexture> m_tex;
std::unique_ptr<QRhiSampler> m_sampler;
std::unique_ptr<QRhiShaderResourceBindings> m_srb;
std::unique_ptr<QRhiGraphicsPipeline> m_pipeline;
QRhiRenderPassDescriptor *m_passDescriptor = nullptr;
QByteArray m_frame;
QVector4D m_energyHi{ 0.0f, 0.0f, 0.0f, 0.0f };
int m_lastCol = 0;
bool m_needClear = false;
};
} // namespace
QQuickRhiItemRenderer *RibbonItem::createRenderer()
{
return new RibbonRenderer;
}
// QML type registration — the linebed_item.cpp idiom: the module is STATIC,
// so a startup function runs at QGuiApplication construction, BEFORE the
// engine loads the QML that names RibbonItem.
static bool g_ribbonRegistered = false;
extern "C" void qbz_ribbon_register_qml_type()
{
if (g_ribbonRegistered)
return;
g_ribbonRegistered = true;
qmlRegisterType<RibbonItem>("com.blitzfc.qbz", 1, 0, "RibbonItem");
}
Q_COREAPP_STARTUP_FUNCTION(qbz_ribbon_register_qml_type)
+41
View File
@@ -0,0 +1,41 @@
// Spectral Ribbon (immersive shader scene, mode 4) — the QQuickRhiItem
// behind the GPU spectrogram. Block A3 of the 2026-08-15
// immersive-completion contract (spec 01 §2.4). Third hand-written C++
// item after LineBedItem/PlasmaItem (cxx/linebed_item.h carries the
// why-C++ rationale; this scene additionally needs a PERSISTENT texture
// written in sub-rects, which a ShaderEffect cannot express).
//
// QML properties are MEMBER-only (no NOTIFY): the QML wrapper
// (RibbonScene.qml) writes them on the pulse edge and calls update()
// itself — the same cadence contract as LineBedItem/PlasmaItem.
//
// `frame` is ONE QByteArray per viz tick, self-describing:
// bytes 0..4 column (u32 LE) — playback-time column, 0..2047
// byte 4 reset flag (0/1) — full spectrogram clear (track
// change / seek), applied BEFORE the row write
// bytes 5..517 the 512-band row (u8 per band, dB-scaled host-side)
// (the pack's batching pattern: ONE property = ONE notify per tick).
//
// Registered as QML type `RibbonItem` in `com.blitzfc.qbz` 1.0 (see the
// .cpp).
#pragma once
#include <QtCore/QByteArray>
#include <QtGui/QVector4D>
#include <QtQuick/QQuickRhiItem>
class RibbonItem : public QQuickRhiItem
{
Q_OBJECT
Q_PROPERTY(QByteArray frame MEMBER m_frame)
Q_PROPERTY(QVector4D energyHi MEMBER m_energyHi)
public:
explicit RibbonItem(QQuickItem *parent = nullptr) : QQuickRhiItem(parent) {}
QQuickRhiItemRenderer *createRenderer() override;
QByteArray m_frame;
QVector4D m_energyHi{ 0.0f, 0.0f, 0.0f, 0.0f };
};
+415
View File
@@ -0,0 +1,415 @@
// Tunnel Flow (immersive shader scene, mode 8 — Qt-only) — the QRhi
// renderer behind TunnelFlowItem. Block B1 of the 2026-08-15
// immersive-completion contract (spec 02-tauri-tunnel-port.md). The
// mechanism is the PlasmaItem one (cxx/plasma_item.cpp carries the full
// rationale): a PING-PONG over two owned RGBA8 textures — pass 1 renders the
// tunnel into history[write] sampling history[read] (the source panel's
// self-drawImage trail system), pass 2 blits history[write] into the item's
// render target, then the indices swap. Owning both targets means the item's
// texture is never read back and no Qt-internal attachment is touched. The
// blit reuses plasma_blit.frag.qsb (a pure 1:1 textured triangle).
//
// Resource cadence (the pulse law): `synchronize` snapshots the QML-side
// properties when the item updates (pulse tick only); per frame the GPU work
// is one uniform upload + two fullscreen triangles.
//
// History size tracks the item's physical size CAPPED at 2560x1440 (the
// plasma_item / ShaderSceneLayer resW/resH rule); on a bigger screen the
// blit upscales. A resize rebuilds the pair and re-clears it (the trails
// restart).
#include "tunnelflow_item.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtQml/qqml.h>
#include <rhi/qrhi.h>
#include <cstring>
namespace {
// The history-target ceiling (see the header).
constexpr int MAX_W = 2560;
constexpr int MAX_H = 1440;
// The scene's own std140 block — NOT the 144-byte spec-01 block: Tunnel Flow
// consumes the Viz16 stream (smoothed in QML), not the shader pack, so the
// block holds exactly what tunnel_flow.frag reads. vec4-aligned.
struct UniformData
{
float time; // 0 (seconds)
float phase; // 4
float bass; // 8
float mid; // 12
float high; // 16
float kick; // 20
float res[2]; // 24
float palette0[4]; // 32
float palette1[4]; // 48
float palette2[4]; // 64
float palette3[4]; // 80
};
static_assert(sizeof(UniformData) == 96, "std140 tunnel-flow block");
QShader loadShader(const QString &qrcPath)
{
QFile f(qrcPath);
if (f.open(QIODevice::ReadOnly)) {
const QShader s = QShader::fromSerialized(f.readAll());
if (!s.isValid())
qWarning("[tunnelflow] shader %s failed to deserialize", qPrintable(qrcPath));
return s;
}
qWarning("[tunnelflow] shader %s not found in the qrc", qPrintable(qrcPath));
return QShader();
}
QVector4D colorVec(const QColor &c)
{
return QVector4D(float(c.redF()), float(c.greenF()), float(c.blueF()), 1.0f);
}
class TunnelFlowRenderer : public QQuickRhiItemRenderer
{
public:
~TunnelFlowRenderer() override
{
// The render pass descriptors are OURS (the RTs borrow them).
delete m_histRpDesc[0];
delete m_histRpDesc[1];
}
void initialize(QRhiCommandBuffer *cb) override
{
QRhi *r = cb->rhi();
if (m_vbuf) // already built (initialize can re-run on rhi changes;
return; // the rebuild path drops everything first)
// The fullscreen triangle (rhi_triangle.vert replaces gl_VertexID
// with this buffer — the GLES 3.0-portable spelling, plasma idiom).
// Shared by the feedback AND blit passes.
static const float TRI[] = { -1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f };
m_vbuf.reset(r->newBuffer(QRhiBuffer::Immutable,
QRhiBuffer::VertexBuffer,
quint32(sizeof(TRI))));
m_ubuf.reset(r->newBuffer(QRhiBuffer::Dynamic,
QRhiBuffer::UniformBuffer,
quint32(sizeof(UniformData))));
m_sampler.reset(r->newSampler(QRhiSampler::Linear,
QRhiSampler::Linear,
QRhiSampler::None,
QRhiSampler::ClampToEdge,
QRhiSampler::ClampToEdge));
if (!m_vbuf->create() || !m_ubuf->create() || !m_sampler->create()) {
qWarning("[tunnelflow] resource creation failed — the scene stays dark");
m_vbuf.reset();
return;
}
QRhiResourceUpdateBatch *u = r->nextResourceUpdateBatch();
u->uploadStaticBuffer(m_vbuf.get(), TRI);
cb->resourceUpdate(u);
}
void synchronize(QQuickRhiItem *item) override
{
// GUI thread: snapshot the item's properties. Runs on item update()
// (the pulse tick) and on geometry/rhi changes.
auto *tf = static_cast<TunnelFlowItem *>(item);
m_time = tf->m_time;
m_phase = tf->m_phase;
m_bass = tf->m_bass;
m_mid = tf->m_mid;
m_high = tf->m_high;
m_kick = tf->m_kick;
m_palette0 = colorVec(tf->m_palette0);
m_palette1 = colorVec(tf->m_palette1);
m_palette2 = colorVec(tf->m_palette2);
m_palette3 = colorVec(tf->m_palette3);
}
void render(QRhiCommandBuffer *cb) override
{
if (!m_vbuf)
return; // resource creation failed in initialize
QRhiRenderTarget *rt = renderTarget();
const QSize ps = rt->pixelSize();
if (ps.isEmpty())
return;
const QSize hist = capped(ps);
if (hist != m_histSize)
rebuildHistory(hist);
if (!m_hist[0])
return; // history creation failed — stay dark
// Pipeline A (scene) renders into the history pair's pass; pipeline
// B (blit) into the item's. Rebuild each when its descriptor moves.
if (!m_scenePipe || m_histRt[0]->renderPassDescriptor() != m_scenePassDescriptor) {
m_scenePassDescriptor = m_histRt[0]->renderPassDescriptor();
buildScenePipeline();
if (!m_scenePipe)
return;
}
if (!m_blitPipe || rt->renderPassDescriptor() != m_blitPassDescriptor) {
m_blitPassDescriptor = rt->renderPassDescriptor();
buildBlitPipeline();
if (!m_blitPipe)
return;
}
QRhiResourceUpdateBatch *u = rhi()->nextResourceUpdateBatch();
UniformData ud = {};
ud.time = m_time;
ud.phase = m_phase;
ud.bass = m_bass;
ud.mid = m_mid;
ud.high = m_high;
ud.kick = m_kick;
ud.res[0] = float(hist.width());
ud.res[1] = float(hist.height());
std::memcpy(ud.palette0, &m_palette0, sizeof(ud.palette0));
std::memcpy(ud.palette1, &m_palette1, sizeof(ud.palette1));
std::memcpy(ud.palette2, &m_palette2, sizeof(ud.palette2));
std::memcpy(ud.palette3, &m_palette3, sizeof(ud.palette3));
u->updateDynamicBuffer(m_ubuf.get(), 0, quint32(sizeof(ud)), &ud);
// A fresh pair starts BLACK (the source panel's canvas starts blank
// too — an unsampled-cleared first frame would advect garbage).
if (m_needClear) {
m_needClear = false;
for (int i = 0; i < 2; ++i) {
cb->beginPass(m_histRt[i].get(), QColor(0, 0, 0, 255),
QRhiDepthStencilClearValue(1.0f, 0), nullptr);
cb->endPass();
}
}
const int read = m_read;
const int write = 1 - m_read;
// Pass 1: the tunnel into history[write], sampling history[read].
cb->beginPass(m_histRt[write].get(), QColor(0, 0, 0, 255),
QRhiDepthStencilClearValue(1.0f, 0), u);
cb->setGraphicsPipeline(m_scenePipe.get());
cb->setViewport(QRhiViewport(0, 0, float(hist.width()), float(hist.height())));
cb->setShaderResources(m_srbScene[read].get());
const QRhiCommandBuffer::VertexInput tri(m_vbuf.get(), 0);
cb->setVertexInput(0, 1, &tri);
cb->draw(3);
cb->endPass();
// Pass 2: blit history[write] into the item target (the composite).
cb->beginPass(rt, QColor(0, 0, 0, 255), QRhiDepthStencilClearValue(1.0f, 0), nullptr);
cb->setGraphicsPipeline(m_blitPipe.get());
cb->setViewport(QRhiViewport(0, 0, float(ps.width()), float(ps.height())));
cb->setShaderResources(m_srbBlit[write].get());
cb->setVertexInput(0, 1, &tri);
cb->draw(3);
cb->endPass();
m_read = write;
}
private:
static QSize capped(const QSize &ps)
{
if (ps.width() <= MAX_W && ps.height() <= MAX_H)
return ps;
const double s = qMin(double(MAX_W) / ps.width(), double(MAX_H) / ps.height());
return QSize(qMax(1, int(ps.width() * s)), qMax(1, int(ps.height() * s)));
}
// (Re)build the ping-pong pair + its render targets + both SRB sets.
// Old resources go through deleteLater() — an in-flight frame may still
// reference them (QRhiResource::deleteLater is the documented deferral).
void rebuildHistory(const QSize &size)
{
QRhi *r = rhi();
for (int i = 0; i < 2; ++i) {
if (m_hist[i])
m_hist[i].release()->deleteLater();
if (m_histRt[i])
m_histRt[i].release()->deleteLater();
if (m_srbScene[i])
m_srbScene[i].release()->deleteLater();
if (m_srbBlit[i])
m_srbBlit[i].release()->deleteLater();
}
if (m_scenePipe)
m_scenePipe.release()->deleteLater();
m_scenePassDescriptor = nullptr;
m_histSize = size;
m_needClear = true;
m_read = 0;
for (int i = 0; i < 2; ++i) {
m_hist[i].reset(r->newTexture(QRhiTexture::RGBA8, size));
if (!m_hist[i]->create()) {
qWarning("[tunnelflow] history texture creation failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
// Vulkan/D3D/Metal REQUIRE a render pass descriptor before
// create(); without it QVkTextureRenderTarget warns and the
// later beginPass segfaults (2026-08-15 owner smoke: Tunnel
// Flow killed the app). The RT does NOT own the descriptor —
// free the previous one on rebuild.
if (m_histRpDesc[i]) {
delete m_histRpDesc[i];
m_histRpDesc[i] = nullptr;
}
m_histRt[i].reset(r->newTextureRenderTarget({ m_hist[i].get() }));
m_histRpDesc[i] = m_histRt[i]->newCompatibleRenderPassDescriptor();
m_histRt[i]->setRenderPassDescriptor(m_histRpDesc[i]);
if (!m_histRt[i]->create()) {
qWarning("[tunnelflow] history render target failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
}
// SRB sets: the scene pass binds ubuf(0) + the READ texture(1); the
// blit binds only the WRITE texture(1) (its shader declares nothing
// else). Both bilinear.
for (int i = 0; i < 2; ++i) {
m_srbScene[i].reset(r->newShaderResourceBindings());
m_srbScene[i]->setBindings({
QRhiShaderResourceBinding::uniformBuffer(
0,
QRhiShaderResourceBinding::VertexStage
| QRhiShaderResourceBinding::FragmentStage,
m_ubuf.get()),
QRhiShaderResourceBinding::sampledTexture(
1, QRhiShaderResourceBinding::FragmentStage,
m_hist[i].get(), m_sampler.get()),
});
m_srbBlit[i].reset(r->newShaderResourceBindings());
m_srbBlit[i]->setBindings({
QRhiShaderResourceBinding::sampledTexture(
1, QRhiShaderResourceBinding::FragmentStage,
m_hist[i].get(), m_sampler.get()),
});
if (!m_srbScene[i]->create() || !m_srbBlit[i]->create()) {
qWarning("[tunnelflow] shader resource bindings failed — the scene stays dark");
m_hist[0].reset();
m_hist[1].reset();
return;
}
}
}
void setVertexLayout(QRhiGraphicsPipeline *pipe)
{
QRhiVertexInputLayout inputLayout;
inputLayout.setBindings({ QRhiVertexInputBinding(quint32(2 * sizeof(float))) });
inputLayout.setAttributes({
{ 0, 0, QRhiVertexInputAttribute::Float2, 0 }, // pos
});
pipe->setVertexInputLayout(inputLayout);
}
void buildScenePipeline()
{
if (!m_scenePipe)
m_scenePipe.reset(rhi()->newGraphicsPipeline());
m_scenePipe->setTopology(QRhiGraphicsPipeline::Triangles);
m_scenePipe->setCullMode(QRhiGraphicsPipeline::None);
m_scenePipe->setDepthTest(false);
m_scenePipe->setDepthWrite(false);
// OPAQUE output (the FS writes alpha 1; the scene owns the
// background while active — the plasma header documents the same
// choice).
m_scenePipe->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/rhi_triangle.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/tunnel_flow.frag.qsb")) },
});
setVertexLayout(m_scenePipe.get());
m_scenePipe->setShaderResourceBindings(m_srbScene[0].get());
m_scenePipe->setRenderPassDescriptor(m_scenePassDescriptor);
if (!m_scenePipe->create()) {
qWarning("[tunnelflow] pipeline creation failed — the scene stays dark");
m_scenePipe.reset();
}
}
void buildBlitPipeline()
{
if (!m_blitPipe)
m_blitPipe.reset(rhi()->newGraphicsPipeline());
m_blitPipe->setTopology(QRhiGraphicsPipeline::Triangles);
m_blitPipe->setCullMode(QRhiGraphicsPipeline::None);
m_blitPipe->setDepthTest(false);
m_blitPipe->setDepthWrite(false);
m_blitPipe->setShaderStages({
{ QRhiShaderStage::Vertex,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/rhi_triangle.vert.qsb")) },
{ QRhiShaderStage::Fragment,
loadShader(QStringLiteral(
":/qt/qml/com/blitzfc/qbz/qml/assets/shaders/plasma_blit.frag.qsb")) },
});
setVertexLayout(m_blitPipe.get());
m_blitPipe->setShaderResourceBindings(m_srbBlit[0].get());
m_blitPipe->setRenderPassDescriptor(m_blitPassDescriptor);
if (!m_blitPipe->create()) {
qWarning("[tunnelflow] blit pipeline creation failed — the scene stays dark");
m_blitPipe.reset();
}
}
std::unique_ptr<QRhiBuffer> m_vbuf;
std::unique_ptr<QRhiBuffer> m_ubuf;
std::unique_ptr<QRhiSampler> m_sampler;
std::unique_ptr<QRhiTexture> m_hist[2];
std::unique_ptr<QRhiTextureRenderTarget> m_histRt[2];
// Render pass descriptors owned BY US (the RT borrows them) — see the
// rebuild loop. Raw pointers, freed on rebuild.
QRhiRenderPassDescriptor *m_histRpDesc[2] = { nullptr, nullptr };
std::unique_ptr<QRhiShaderResourceBindings> m_srbScene[2];
std::unique_ptr<QRhiShaderResourceBindings> m_srbBlit[2];
std::unique_ptr<QRhiGraphicsPipeline> m_scenePipe;
std::unique_ptr<QRhiGraphicsPipeline> m_blitPipe;
QRhiRenderPassDescriptor *m_scenePassDescriptor = nullptr;
QRhiRenderPassDescriptor *m_blitPassDescriptor = nullptr;
QSize m_histSize;
int m_read = 0;
bool m_needClear = true;
// synchronize() snapshots.
float m_time = 0.0f;
float m_phase = 0.0f;
float m_bass = 0.0f;
float m_mid = 0.0f;
float m_high = 0.0f;
float m_kick = 0.0f;
QVector4D m_palette0{ 1.0f, 0.416f, 0.416f, 1.0f };
QVector4D m_palette1{ 1.0f, 0.804f, 0.361f, 1.0f };
QVector4D m_palette2{ 0.408f, 0.863f, 0.667f, 1.0f };
QVector4D m_palette3{ 0.431f, 0.690f, 1.0f, 1.0f };
};
} // namespace
QQuickRhiItemRenderer *TunnelFlowItem::createRenderer()
{
return new TunnelFlowRenderer;
}
// QML type registration — the plasma_item.cpp idiom: the module is STATIC,
// so a startup function runs at QGuiApplication construction, BEFORE the
// engine loads the QML that names TunnelFlowItem.
static bool g_tunnelflowRegistered = false;
extern "C" void qbz_tunnelflow_register_qml_type()
{
if (g_tunnelflowRegistered)
return;
g_tunnelflowRegistered = true;
qmlRegisterType<TunnelFlowItem>("com.blitzfc.qbz", 1, 0, "TunnelFlowItem");
}
Q_COREAPP_STARTUP_FUNCTION(qbz_tunnelflow_register_qml_type)
+55
View File
@@ -0,0 +1,55 @@
// Tunnel Flow (immersive shader scene, mode 8 — Qt-only) — the
// QQuickRhiItem behind the feedback tunnel. Block B1 of the 2026-08-15
// immersive-completion contract (spec 02-tauri-tunnel-port.md): a rewrite of
// the legacy Tauri Canvas2D panel (TunnelFlowPanel.svelte) as
// qml/assets/shaders/tunnel_flow.frag. Same mechanism as PlasmaItem
// (cxx/plasma_item.h): a feedback ping-pong over two owned RGBA8 textures a
// ShaderEffect cannot own.
//
// QML properties are MEMBER-only (no NOTIFY): the QML wrapper
// (TunnelFlowScene.qml) computes the audio state (Viz16 smoothing, kick
// detector, the TAURI phase accumulator) and writes these on the pulse edge
// via pulseTick() — the same cadence contract as PlasmaItem/LineBedItem.
//
// Registered as QML type `TunnelFlowItem` in `com.blitzfc.qbz` 1.0 (see the
// .cpp).
#pragma once
#include <QtGui/QColor>
#include <QtQuick/QQuickRhiItem>
class TunnelFlowItem : public QQuickRhiItem
{
Q_OBJECT
Q_PROPERTY(float time MEMBER m_time)
Q_PROPERTY(float phase MEMBER m_phase)
Q_PROPERTY(float bass MEMBER m_bass)
Q_PROPERTY(float mid MEMBER m_mid)
Q_PROPERTY(float high MEMBER m_high)
Q_PROPERTY(float kick MEMBER m_kick)
Q_PROPERTY(QColor palette0 MEMBER m_palette0)
Q_PROPERTY(QColor palette1 MEMBER m_palette1)
Q_PROPERTY(QColor palette2 MEMBER m_palette2)
Q_PROPERTY(QColor palette3 MEMBER m_palette3)
public:
explicit TunnelFlowItem(QQuickItem *parent = nullptr) : QQuickRhiItem(parent) {}
QQuickRhiItemRenderer *createRenderer() override;
// Member snapshots the renderer reads in synchronize(). The palette
// defaults are the Tauri fallback (TunnelFlowPanel.svelte:63-68) so a
// pre-art track still looks right; time is SECONDS here (the shader
// converts to the source's ms domain).
float m_time = 0.0f;
float m_phase = 0.0f;
float m_bass = 0.0f;
float m_mid = 0.0f;
float m_high = 0.0f;
float m_kick = 0.0f;
QColor m_palette0{ 255, 106, 106 };
QColor m_palette1{ 255, 205, 92 };
QColor m_palette2{ 104, 220, 170 };
QColor m_palette3{ 110, 176, 255 };
};
+10 -4
View File
@@ -288,6 +288,12 @@ ApplicationWindow {
// atmosphere_url to this singleton on every track change — a missing
// boot line would drop those publishes silently (see above).
QbzImmersive.boot()
// Shader scenes (2026-08-15 immersive-completion contract, block A1).
// Booted right after QbzImmersive: its open funnel resets the scene
// through this singleton's hop, and the viz drain publishes the audio
// pack here on every tick while immersive is open — a missing boot
// line makes both silent no-ops (TRACK-RULES, singleton boot order).
QbzShaderScene.boot()
// Immersive Suggestions (the same contract, block B4 §4.5) — booted
// WITH its bridge: every publish the suggestions loader makes rides
// this hop, so a missing line is the forever-"{}" silent no-op the
@@ -646,10 +652,10 @@ ApplicationWindow {
// false, clear the maximized latch in the FullScreen branch too. Qt
// collapses both into one enum, so the maximized latch is cleared ONLY
// by an explicit return to Windowed — never by entering fullscreen.
// Nothing in QBZ's chrome sets FullScreen (both toggles go
// Maximized <-> Windowed, shell/HeaderBar.qml:76,830); it arrives from
// the WM keybind, and quitting from there must not un-maximize the
// next launch of either frontend.
// FullScreen arrives from the WM keybind OR from the immersive
// chrome (immersive/ImmersiveHeader.qml fs toggle — the first
// FullScreen write in this frontend, 2026-08-02 §5.2); quitting from
// there must not un-maximize the next launch of either frontend.
if (vis === Window.Maximized) {
window.maximizedLatch = true
window.fullScreenLatch = false
@@ -0,0 +1,31 @@
#version 440
// PAIRED with ambient.frag (AmbientField + the immersive Ambient scene).
// THE PAIRING RULE (see scene_pack.vert): both stages must declare the SAME
// uniform block, member for member, or the OpenGL program link rejects the
// two layouts (Vulkan never links, so it tolerated the mismatch). Keep this
// block byte-identical to ambient.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 primary;
vec4 secondary;
vec4 accent;
float qt_Opacity;
float time;
float levelSmooth;
float resX;
float resY;
float dim;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
Binary file not shown.
@@ -0,0 +1,29 @@
#version 440
// PAIRED with atmosphere.frag (ImmersiveAtmosphere). THE PAIRING RULE (see
// scene_pack.vert): both stages must declare the SAME uniform block, member
// for member, or the OpenGL program link rejects the two layouts. Keep this
// block byte-identical to atmosphere.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
float qt_Opacity;
float resX;
float resY;
float dim;
vec4 l1;
vec4 l2;
vec4 l3;
vec4 l4;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
Binary file not shown.
@@ -0,0 +1,124 @@
#version 440
// Aurora (immersive scene, mode 3) — a line-faithful GLSL 440 port of
// crates/qbz-ui/ui/shaders/aurora.wgsl (AURORA WARP, original clean-room
// shader; the stage-0 spike scene of the 2026-08-15 immersive-completion
// contract, chosen because it exercises the full uniform pack with zero
// extra GPU resources). Every constant and every formula is the reference's;
// the differences are mechanical (same list as tunnel.frag): uniform block
// instead of a bind group, resolution as resX/resY, energy/bands vec4s by
// their QML property names, `let` -> local floats, uv = qt_TexCoord0 with NO
// y-flip (the ambient.frag convention), premultiplied output.
//
// Three sine-domain-warped curtains take their colors from the album-art
// palette (primary / secondary / accent); bass swells the low curtain, mids
// drive sway speed/amplitude, presence the top curtain, air = shimmer
// frequency (5.0 + air*8.0) cross-fading toward accent, beat kicks the
// brightness and lifts the curtains, level_smooth sets the baseline bloom.
// Fixed work per pixel, no loops — GPU-cheap.
//
// Pure float math (no integer ops), so this shader keeps the FULL qsb
// variant set including 100 es (unlike ambient.frag / tunnel.frag).
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 primary;
vec4 secondary;
vec4 accent;
vec4 energyLo;
vec4 energyHi;
vec4 bandsLo;
vec4 bandsHi;
float qt_Opacity;
float time;
float phase;
float beat;
float level;
float resX;
float resY;
float levelSmooth;
// Named transientAmp, not `transient` — a RESERVED QML keyword (see
// tunnel.frag). The JSON pack key stays `transient`.
float transientAmp;
};
// A small smooth flow field: cheap sine lobes that act like a fake curl, so
// the curtains ripple horizontally instead of sliding rigidly.
float flow(vec2 p, float t) {
float a = sin(p.x * 2.3 + t * 0.7) * 0.5;
float b = sin(p.x * 4.7 - t * 0.45 + p.y * 1.3) * 0.25;
float c = sin((p.x + p.y) * 1.7 + t * 0.9) * 0.18;
return a + b + c;
}
void main() {
float t = time;
float bass = clamp(energyLo.y, 0.0, 1.0);
float mids = clamp(energyLo.z, 0.0, 1.0);
float presence = clamp(energyLo.w, 0.0, 1.0);
float air = clamp(energyHi.x, 0.0, 1.0);
float beatC = clamp(beat, 0.0, 1.0);
float lvl = clamp(levelSmooth, 0.0, 1.0);
float aspect = resX / max(resY, 1.0);
// x spread by aspect so the curtains aren't squashed on wide windows.
vec2 p = vec2((qt_TexCoord0.x - 0.5) * aspect, qt_TexCoord0.y);
// Mids drive the sway amplitude & speed.
float swaySpeed = 0.6 + mids * 0.9;
float warp1 = flow(p * 3.0, t * swaySpeed);
float warp2 = flow(p * 2.0 + vec2(7.3, 0.0), t * (0.8 * swaySpeed) + 2.0);
float warp3 = flow(p * 2.6 + vec2(-4.1, 1.0), t * (0.65 * swaySpeed) + 4.0);
// Curtain widths: bass swells the low curtain; beat lifts; presence the
// top.
float bw1 = 0.10 + bass * 0.16 + beatC * 0.03;
float bw2 = 0.09 + mids * 0.10;
float bw3 = 0.07 + presence * 0.10;
// Anchors drift on a slow vertical LFO + a beat lift; sway from warp +
// mids.
float lift = beatC * 0.03;
float sway = 0.08 + mids * 0.12;
float center1 = 0.40 + 0.02 * sin(t * 0.23) + warp1 * sway - lift;
float center2 = 0.60 + 0.02 * sin(t * 0.19 + 1.7) + warp2 * sway - lift;
float center3 = 0.50 + 0.025 * sin(t * 0.16 + 3.1) + warp3 * (sway * 0.9) - lift;
float band1 = bw1 / (abs(p.y - center1) + bw1);
float band2 = bw2 / (abs(p.y - center2) + bw2);
float band3 = bw3 / (abs(p.y - center3) + bw3);
// Treble shimmer cross-fades each curtain base color toward accent.
float shFreq = 5.0 + air * 8.0;
float sh1 = 0.5 + 0.5 * sin(p.x * shFreq + t * 1.3);
float sh2 = 0.5 + 0.5 * sin(p.x * (shFreq * 0.8) - t * 1.1 + 1.0);
float sh3 = 0.5 + 0.5 * sin(p.x * (shFreq * 1.2) + t * 1.6 + 2.0);
float shGain = 0.25 + air * 0.5;
vec3 col1 = mix(primary.rgb, accent.rgb, sh1 * shGain);
vec3 col2 = mix(secondary.rgb, accent.rgb, sh2 * shGain);
vec3 col3 = mix(accent.rgb, primary.rgb, sh3 * shGain);
vec3 col = col1 * band1 * (0.55 + sh1 * 0.45);
col += col2 * band2 * (0.55 + sh2 * 0.45);
col += col3 * band3 * (0.5 + sh3 * 0.4) * (0.4 + presence * 0.8);
// Baseline brightness from the smoothed level + beat; dim primary floor
// glow.
col *= 0.5 + lvl * 0.9;
col *= 1.0 + beatC * 0.5;
col += primary.rgb * 0.04;
// Beat bloom: vertical shimmer streaks where the curtains already are.
float streak = abs(fract(p.y * 6.0 - t * 2.0) - 0.5);
float bloom = (0.5 / (streak * 8.0 + 0.5)) * beatC;
col += accent.rgb * bloom * (band1 + band2 + band3) * 0.4;
col = clamp(col, vec3(0.0), vec3(1.0));
// Premultiplied, like every other effect in this tree (blending: false at
// the mount, so qt_Opacity is 1 and this equals the reference frame).
fragColor = vec4(col * qt_Opacity, qt_Opacity);
}
Binary file not shown.
@@ -0,0 +1,41 @@
#version 440
// Line Bed (immersive scene, mode 5) — FRAGMENT stage. Line-faithful port
// of `fs_main` in crates/qbz-ui/ui/shaders/line_bed.wgsl:
//
// * the bottom cutoff (`in.pos.y > u.resolution.y * 0.86 → discard`)
// reads the `yFrac` varying the VS computed from its own screen-space
// position — identical value to the reference's framebuffer-space
// builtin, portable across the gl_FragCoord y-orientation split (see
// the vertex shader's header);
// * the gradient: valleys take `primary`, peaks tip toward `accent`
// (`g = clamp(intensity * 1.25, 0, 1)`), peaks also brighten via alpha
// (0.5 + g*0.4) under the pipeline's SrcAlpha blend.
//
// QSB-SKIP-GLES100 — paired with the vertex stage (texelFetch); the ES 2.0
// variant cannot carry the scene and the tier gate keeps it off that
// hardware anyway.
layout(std140, binding = 0) uniform buf {
vec2 resolution;
vec4 primary;
vec4 accent;
} u;
layout(location = 0) in float intensity;
layout(location = 1) in float yFrac;
layout(location = 0) out vec4 fragColor;
void main() {
// Bottom cutoff — don't render below ~86% of the view, so the bed ends
// above the player bar instead of spilling to the window bottom.
if (yFrac > 0.86)
discard;
// Height gradient: the bed/valleys take `primary`, the mountain peaks
// tip toward `accent`, gradually — peaks also brighten.
float g = clamp(intensity * 1.25, 0.0, 1.0);
vec3 col = mix(u.primary.rgb, u.accent.rgb, g);
float a = 0.5 + g * 0.4;
fragColor = vec4(col, a);
}
Binary file not shown.
@@ -0,0 +1,140 @@
#version 440
// Line Bed (immersive scene, mode 5) — VERTEX stage. A line-faithful GLSL
// 440 port of `vs_main` in crates/qbz-ui/ui/shaders/line_bed.wgsl (itself a
// clean-room port of the Tauri LinebedPanel projection math): 200
// depth-stacked polylines, one historical 256-point spectrum each (X =
// frequency, Y = magnitude, Z = age), projected with a LEVELED pitch-only
// camera, each band span subdivided with a Catmull-Rom-STYLE uniform cubic
// B-spline across the 4 neighboring bands so the polylines read as smooth
// curves. The 256x200 heights arrive as an R32F texture (binding 4),
// DEPTH-ORDERED row 0 = newest, fed by the Rust LineBedState
// (src/linebed_qt.rs) — `textureLoad` becomes `texelFetch`.
//
// The ONLY mechanical differences from the WGSL, enumerated:
// * @builtin(vertex_index) / @builtin(instance_index) become two FLOAT
// vertex attributes (`vid`, `lineIdx`) driven from the 1531-vert
// template buffer and a 200-entry per-instance buffer — the portable
// spelling under QRhi (GLES 3.0 has no gl_VertexID; the C++ side
// uploads 0..1530 / 0..199 verbatim).
// * `u.resolution: vec2` sits at offset 0 of a TRIMMED uniform block
// (this scene reads only resolution in the VS and primary/accent in the
// FS — line_bed.wgsl has no time/level/energy input); same values,
// same meaning as the 144-byte block's fields.
// * the FS cutoff coordinate is exported as the `yFrac` varying
// (screen_y / resolution.y) instead of being re-read from
// @builtin(position) in the FS — gl_FragCoord.y is BOTTOM-up on GL,
// top-down on wgpu/Vulkan, so the portable route is to interpolate the
// value the VS already computed. w == 1 throughout, so the interpolated
// yFrac equals the reference's per-pixel pos.y/resolution.y exactly.
//
// QSB-SKIP-GLES100 — texelFetch (vertex texture fetch) needs GLSL ES 3.00;
// the ES 2.0 variant cannot carry this shader and the tier gate keeps the
// scene off that hardware anyway.
// QSB-SKIP-BATCH — a QQuickRhiItem shader, NOT a Qt Quick ShaderEffect
// stage: the `-b` batching rewrite is only valid for scene-graph batched
// items and would corrupt the custom attribute layout.
layout(location = 0) in float vid; // 0..1530: subdivided point index
layout(location = 1) in float lineIdx; // 0..199: depth row (per instance)
layout(std140, binding = 0) uniform buf {
vec2 resolution;
vec4 primary;
vec4 accent;
} u;
layout(binding = 4) uniform sampler2D heights_tex;
layout(location = 0) out float intensity;
layout(location = 1) out float yFrac;
out gl_PerVertex { vec4 gl_Position; };
// --- Camera constants (verbatim from line_bed.wgsl:42-59, which took them
// verbatim from LinebedPanel.svelte) ---------------------------------------
const float LINE_LENGTH = 9.0;
const float WORLD_AMPLITUDE = 2.4;
const float PLANE_HALF_WIDTH = 1147.5; // (255*9)/2
const float PLANE_HALF_DEPTH = 1990.0; // (199*20)/2
const float CAM_X = 26.1;
const float CAM_Y = 1738.6;
const float CAM_Z = 868.8;
const float CAMERA_NEAR = 80.0;
const float FOV_DEG = 45.0; // vertical
const int NUM_BANDS = 256;
// MUST match the host's LINEBED_SUBDIV (shader_underlay.rs:54 /
// linebed_qt.rs) and the 1531-vert template the C++ uploads.
const float SUBDIV = 6.0;
// Vertical screen position of the projection origin (lower = the bed sits
// HIGHER). 0.30 so the bed lifts off the bottom, clears the player bar,
// and uses the dead space up top.
const float VCENTER = 0.30;
float height_at(int line, int band) {
int b = clamp(band, 0, NUM_BANDS - 1);
return texelFetch(heights_tex, ivec2(b, line), 0).r;
}
// Uniform cubic B-spline through the 4 neighboring bands — C2-continuous
// (no kinks at the band points) and never overshoots; it APPROXIMATES
// (gently smooths) the samples, so the whole line reads as one continuous
// curve instead of stitched segments.
float curve_height(int line, float band_f) {
int b0 = int(floor(band_f));
float t = band_f - float(b0);
float p0 = height_at(line, b0 - 1);
float p1 = height_at(line, b0);
float p2 = height_at(line, b0 + 1);
float p3 = height_at(line, b0 + 2);
float t2 = t * t;
float t3 = t2 * t;
float w0 = (1.0 - 3.0 * t + 3.0 * t2 - t3) / 6.0;
float w1 = (4.0 - 6.0 * t2 + 3.0 * t3) / 6.0;
float w2 = (1.0 + 3.0 * t + 3.0 * t2 - 3.0 * t3) / 6.0;
float w3 = t3 / 6.0;
return p0 * w0 + p1 * w1 + p2 * w2 + p3 * w3;
}
void main() {
int line = int(lineIdx);
// Continuous (subdivided) band position along the line, 0..255.
float band_f = vid / SUBDIV;
float h = curve_height(line, band_f);
// World position. Only Y is audio-driven; X/Z are the fixed lattice.
float world_x = band_f * LINE_LENGTH - PLANE_HALF_WIDTH;
float world_y = h * WORLD_AMPLITUDE;
float depth_factor = lineIdx / 199.0;
float world_z = -PLANE_HALF_DEPTH + depth_factor * (PLANE_HALF_DEPTH * 2.0);
// LEVELED view transform: pitch ONLY (Rx). Yaw and roll are ZEROED so
// every line sits flat.
float cosX = cos(0.6543);
float sinX = sin(0.6543);
float tX = world_x - CAM_X;
float tY = world_y - CAM_Y;
float tZ = world_z - CAM_Z;
// Rz, Ry = identity (leveled); apply Rx (pitch about the X axis).
float rX = tX;
float rY = tY * cosX - tZ * sinX;
float rZ = tY * sinX + tZ * cosX;
// Near-clip (v1 — no polyline split, like the reference).
float depth = max(-rZ, CAMERA_NEAR);
// SAME focal for X and Y (no aspect correction — faithful to Tauri).
float focal = u.resolution.y * 0.5 / tan(FOV_DEG * 3.14159265 / 360.0);
float screen_x = u.resolution.x * 0.5 + rX * focal / depth;
float screen_y = u.resolution.y * VCENTER - rY * focal / depth;
// Screen px -> clip/NDC (flip Y — QRhi's NDC is y-up like wgpu's).
float ndc_x = screen_x / u.resolution.x * 2.0 - 1.0;
float ndc_y = 1.0 - screen_y / u.resolution.y * 2.0;
gl_Position = vec4(ndc_x, ndc_y, 0.0, 1.0);
intensity = clamp(h / 84.0, 0.0, 1.0);
yFrac = screen_y / u.resolution.y;
}
Binary file not shown.
@@ -0,0 +1,140 @@
#version 440
// Plasma (immersive scene, mode 1) — FRAGMENT stage. Line-faithful GLSL 440
// port of `fs_main` in crates/qbz-ui/ui/shaders/plasma.wgsl (the MilkDrop-
// class feedback fluid: sample the previous frame at a warped UV, decay,
// inject orbiting ink + beat splats). The feedback history lives in two
// RGBA8 ping-pong textures owned by the C++ PlasmaItem (the reference keeps
// ONE history and copies the frame back — shader_underlay.rs:1003-1025 —
// which is the same recurrence; ping-pong is how you say "sample last frame,
// write this frame" without a surface readback).
//
// Mechanical differences from the WGSL, enumerated:
// * textureSample(prev_tex, prev_samp, uv) -> texture(prev_tex, uv)
// (combined image sampler, binding 1).
// * bitcast<u32>(i32(x)) -> uint(int(x)): int->uint is a modulo-2^32
// conversion in GLSL, i.e. the same bit pattern the WGSL bitcast keeps.
// * The uniform block is the FULL 144-byte std140 scene block (spec 01
// §1) — this scene reads time/resolution/energy_lo/energy_hi.x/beat/
// level/level_smooth/primary/secondary/accent; the remaining fields
// arrive zeroed.
//
// QSB-SKIP-GLES100 — the lattice hash is UINT arithmetic (plasma.wgsl:55-67
// records why a float hash draws "wallpaper join" seams); ES 2.0 has no
// uint. The tier gate keeps the scene off that hardware.
layout(std140, binding = 0) uniform buf {
float time;
float phase;
float beat;
float level;
vec2 resolution;
float levelSmooth;
float transientAmp;
vec4 energyLo;
vec4 energyHi;
vec4 bandsLo;
vec4 bandsHi;
vec4 primary;
vec4 secondary;
vec4 accent;
} u;
layout(binding = 1) uniform sampler2D prev_tex;
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 fragColor;
// INTEGER lattice hash (bit-exact) — see the WGSL header above.
float hash2(vec2 p) {
uint h = uint(int(p.x)) * 0x8da6b343u + uint(int(p.y)) * 0xd8163841u;
h = (h ^ (h >> 15u)) * 0x2c1b3c6du;
h = (h ^ (h >> 12u)) * 0x297a2d39u;
h = h ^ (h >> 15u);
return float(h >> 8u) * (1.0 / 16777216.0);
}
float vnoise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
float a = hash2(i);
float b = hash2(i + vec2(1.0, 0.0));
float c = hash2(i + vec2(0.0, 1.0));
float d = hash2(i + vec2(1.0, 1.0));
vec2 uf = f * f * (3.0 - 2.0 * f);
return mix(mix(a, b, uf.x), mix(c, d, uf.x), uf.y);
}
// Divergence-free flow from a scalar potential: curl = (dphi/dy, -dphi/dx).
vec2 curl_noise(vec2 p) {
float e = 0.05;
float dx = vnoise(p + vec2(e, 0.0)) - vnoise(p - vec2(e, 0.0));
float dy = vnoise(p + vec2(0.0, e)) - vnoise(p - vec2(0.0, e));
return vec2(dy, -dx) / (2.0 * e);
}
// Soft gaussian blob — an ink emitter.
float blob(vec2 p, vec2 c, float radius) {
vec2 d = p - c;
return exp(-dot(d, d) / max(radius * radius, 1e-4));
}
void main() {
float t = u.time;
float aspect = u.resolution.x / max(u.resolution.y, 1.0);
float sub = clamp(u.energyLo.x, 0.0, 1.0);
float bass = clamp(u.energyLo.y, 0.0, 1.0);
float mids = clamp(u.energyLo.z, 0.0, 1.0);
float air = clamp(u.energyHi.x, 0.0, 1.0);
float beat = clamp(u.beat, 0.0, 1.0);
float level = clamp(u.level, 0.0, 1.0);
float lvl = clamp(u.levelSmooth, 0.0, 1.0);
// Centered, aspect-correct coords.
vec2 c = (uv - vec2(0.5)) * vec2(aspect, 1.0);
float pres = clamp(u.energyLo.w, 0.0, 1.0);
// === Feedback advection — turbulent, music-cranked. ===
// Bass inhale/zoom (stronger) + a beat kick.
float zoom = 1.0 + 0.006 + (sub + bass) * 0.03 + beat * 0.02;
// Mids swirl harder and faster; beats jolt the rotation.
float ang = (0.006 + mids * 0.05) * sin(t * 0.5 + length(c) * 4.0) + beat * 0.035;
float ca = cos(ang);
float sa = sin(ang);
vec2 w = c * zoom;
w = vec2(w.x * ca - w.y * sa, w.x * sa + w.y * ca);
// Two curl-noise octaves (treble + presence) -> filaments + fine turbulence.
w += curl_noise(c * 2.5 + vec2(t * 0.12, -t * 0.10)) * (0.003 + air * 0.015);
w += curl_noise(c * 5.5 - vec2(t * 0.09, t * 0.08)) * (0.0015 + pres * 0.009);
vec2 warpUv = w / vec2(aspect, 1.0) + vec2(0.5);
vec3 field = texture(prev_tex, warpUv).rgb;
// Decay: faster so it stays ALIVE (not muddy); louder lingers a bit longer.
field *= 0.85 + lvl * 0.06;
// === FOUR emitters, fast orbits — more elements, more motion. ===
vec2 e1 = vec2(sin(t * 0.5), cos(t * 0.6)) * (0.25 + bass * 0.2);
vec2 e2 = vec2(sin(-t * 0.42 + 2.1), cos(-t * 0.38 + 1.3)) * (0.3 + mids * 0.18);
vec2 e3 = vec2(sin(t * 0.74 + 1.0), cos(-t * 0.66 + 3.0)) * (0.22 + pres * 0.2);
vec2 e4 = vec2(cos(t * 0.33 + 4.0), sin(t * 0.58 + 0.5)) * (0.34 + air * 0.16);
field += u.primary.rgb * blob(c, e1, 0.045 + bass * 0.06) * (0.14 + level * 0.8);
field += u.secondary.rgb * blob(c, e2, 0.05 + mids * 0.05) * (0.14 + level * 0.65);
field += u.accent.rgb * blob(c, e3, 0.04 + pres * 0.05) * (0.10 + level * 0.6);
field += u.primary.rgb * blob(c, e4, 0.035 + air * 0.04) * (0.07 + air * 0.6);
// === Beat splats — TWO, bigger and brighter, detonating on the onset. ===
vec2 sp1 = vec2(sin(t * 0.9) * 0.35, cos(t * 0.7) * 0.28);
vec2 sp2 = vec2(cos(t * 1.1 + 2.0) * 0.3, sin(t * 0.85 + 1.0) * 0.32);
field += u.accent.rgb * blob(c, sp1, 0.05 + beat * 0.14) * beat * 2.2;
field += u.secondary.rgb * blob(c, sp2, 0.04 + beat * 0.10) * beat * 1.6;
// Treble shimmer on the crests.
float luma = dot(field, vec3(0.33, 0.34, 0.33));
field += u.accent.rgb * air * smoothstep(0.4, 0.9, luma) * 0.18;
field = clamp(field, vec3(0.0), vec3(1.3));
fragColor = vec4(field, 1.0);
}
Binary file not shown.
@@ -0,0 +1,19 @@
#version 440
// Plasma (immersive scene, mode 1) — BLIT stage: copy the just-rendered
// history texture into the item's render target. The feedback pass renders
// into an owned ping-pong texture (never into the item target directly),
// so the item never has to be read back — this 1:1 textured triangle is the
// composite step. Same vertex stage as plasma.vert.
//
// QSB-SKIP-GLES100 — paired with the plasma passes (the tier gate keeps the
// scene off ES 2.0 hardware; a blit this small needs no ES 2.0 variant).
layout(binding = 1) uniform sampler2D src_tex;
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 fragColor;
void main() {
fragColor = texture(src_tex, uv);
}
@@ -0,0 +1,25 @@
#version 440
// Shared fullscreen-triangle VERTEX stage for the QQuickRhiItem scenes
// (Plasma A2: the feedback AND blit passes; Spectral Ribbon A3). The Slint
// references derive the triangle from @builtin(vertex_index)
// (plasma.wgsl:42-53, spectral_ribbon.wgsl:44-51); GLES 3.0 has no
// gl_VertexID, so the C++ side uploads the three clip positions as a vertex
// buffer (the linebed.vert idiom).
//
// QSB-SKIP-BATCH — a QQuickRhiItem shader, NOT a Qt Quick ShaderEffect
// stage: the `-b` batching rewrite is only valid for scene-graph batched
// items and would corrupt the custom attribute layout.
layout(location = 0) in vec2 pos; // clip-space fullscreen triangle
layout(location = 0) out vec2 uv;
out gl_PerVertex { vec4 gl_Position; };
void main() {
// plasma.wgsl:51 — uv = p * 0.5 + 0.5. Self-consistent for every pass
// that renders and samples with this convention.
uv = pos * 0.5 + vec2(0.5);
gl_Position = vec4(pos, 0.0, 1.0);
}
@@ -0,0 +1,45 @@
#version 440
// PAIRED with tunnel.frag AND aurora.frag (their uniform layouts are
// identical, so one vertex stage serves both).
//
// THE PAIRING RULE (2026-08-15 black-Tunnel report): a ShaderEffect's two
// stages are LINKED into one program under the OpenGL RHI backend, and GLSL
// refuses one block name with two layouts ("uniform `_22' declared as type
// `buf' and type `buf'"). Vulkan never links stages, so the shared
// spectrum.vert (block = qt_Matrix + qt_Opacity) paired with these wider
// fragment blocks rendered fine there and died only on GL. The fix is Qt's
// own documented pattern: BOTH stages declare the SAME block, member for
// member, in the same order — the vertex stage simply never reads the
// fragment-only fields. Keep this block byte-identical to tunnel.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 primary;
vec4 secondary;
vec4 accent;
vec4 energyLo;
vec4 energyHi;
vec4 bandsLo;
vec4 bandsHi;
float qt_Opacity;
float time;
float phase;
float beat;
float level;
float resX;
float resY;
float levelSmooth;
float transientAmp;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
Binary file not shown.
@@ -0,0 +1,106 @@
#version 440
// Spectral Ribbon (immersive scene, mode 4) — FRAGMENT stage. Line-faithful
// GLSL 440 port of `fs_main` in crates/qbz-ui/ui/shaders/spectral_ribbon.wgsl
// (the paint-as-you-play sonogram: frequency on Y, time on X, the Spek
// purple→orange heatmap). The CPU side keeps the persistent R8 spectrogram
// (512 freq bands × 2048 time columns, shader_underlay.rs:44-45); the Qt
// port's Rust half publishes one 512-byte row per viz tick and the C++
// RibbonItem uploads it at the playback-time column with the same gap-fill
// (shader_underlay.rs:897-927).
//
// Mechanical differences from the WGSL, enumerated:
// * textureSample(spectrogram, samp, uv) -> texture(spectrogram, uv)
// (combined image sampler, binding 3 like the reference).
// * log(x)/log(10.0) stays as-is (GLSL has no log10 on all targets; the
// two-log spelling IS the reference's).
// The plot-rect Y convention (PLOT_Y0/Y1 already flipped vs the Slint
// overlay, spectral_ribbon.wgsl:77-81) is UNCHANGED — the QML overlay
// (SpectralOverlay.qml) keeps the overlay's top-down fractions, and the
// item's mirrorVertically makes the GL composite match wgpu's display.
layout(std140, binding = 0) uniform buf {
float time;
float phase;
float beat;
float level;
vec2 resolution;
float levelSmooth;
float transientAmp;
vec4 energyLo;
vec4 energyHi;
vec4 bandsLo;
vec4 bandsHi;
vec4 primary;
vec4 secondary;
vec4 accent;
} u;
layout(binding = 3) uniform sampler2D spectrogram;
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 fragColor;
// Spek-like 7-stop purple→magenta→orange ramp (Tauri spekColor), linear RGB.
vec3 spek_color(float x) {
float t = clamp(x, 0.0, 1.0);
// stops: 0.00 black, 0.36 deep-blue, 0.60 indigo, 0.78 purple,
// 0.92 magenta, 0.98 red-orange, 1.00 orange.
if (t < 0.36) {
return mix(vec3(0.0, 0.0, 0.0), vec3(0.0, 0.0, 0.243), t / 0.36);
} else if (t < 0.60) {
return mix(vec3(0.0, 0.0, 0.243), vec3(0.055, 0.0, 0.392), (t - 0.36) / 0.24);
} else if (t < 0.78) {
return mix(vec3(0.055, 0.0, 0.392), vec3(0.361, 0.0, 0.439), (t - 0.60) / 0.18);
} else if (t < 0.92) {
return mix(vec3(0.361, 0.0, 0.439), vec3(0.745, 0.0, 0.282), (t - 0.78) / 0.14);
} else if (t < 0.98) {
return mix(vec3(0.745, 0.0, 0.282), vec3(0.863, 0.188, 0.0), (t - 0.92) / 0.06);
} else {
return mix(vec3(0.863, 0.188, 0.0), vec3(0.933, 0.471, 0.125), (t - 0.98) / 0.02);
}
}
// Plot rectangle in 0..1 screen space (leaves a margin for axes; the bottom
// band clears the song card / time axis). MUST match SpectralOverlay.qml.
const float PLOT_X0 = 0.055;
const float PLOT_X1 = 0.970;
const float PLOT_Y0 = 0.220;
const float PLOT_Y1 = 0.930;
void main() {
vec3 bg = vec3(0.012, 0.027, 0.047); // #03070c
// Inside the plot rectangle?
if (uv.x < PLOT_X0 || uv.x > PLOT_X1 || uv.y < PLOT_Y0 || uv.y > PLOT_Y1) {
fragColor = vec4(bg, 1.0);
return;
}
// Plot-local coords. tf = time fraction (left→right), ff = freq
// fraction (band 0/bass at the BOTTOM, 511/Nyquist at the TOP).
float tf = (uv.x - PLOT_X0) / (PLOT_X1 - PLOT_X0);
float ff = (uv.y - PLOT_Y0) / (PLOT_Y1 - PLOT_Y0);
// Sample the spectrogram: u = frequency band (0..1 over 512), v = time
// column. Un-played columns are zero -> background.
float amp = texture(spectrogram, vec2(ff, tf)).r;
// dB + gamma (Tauri): db in [-120,0] -> normalized -> ^2.15.
float db = 20.0 * log(max(1e-6, amp)) / log(10.0);
float db_norm = clamp((db + 120.0) / 120.0, 0.0, 1.0);
float toned = pow(db_norm, 2.15);
vec3 col = spek_color(toned);
float a = (10.0 + toned * 156.0) / 255.0;
// Composite the heatmap over the dark background.
vec3 outc = mix(bg, col, a);
// Real-time ceiling line: a horizontal line at the highest active
// frequency (u.energyHi.y = smoothed peak band fraction), spanning the
// full plot width, in the axis green.
float on_line = 1.0 - smoothstep(0.0, 0.006, abs(ff - u.energyHi.y));
outc = mix(outc, vec3(0.373, 0.722, 0.478), on_line * 0.65);
fragColor = vec4(outc, 1.0);
}
@@ -0,0 +1,41 @@
#version 440
// PAIRED with spectrum_bars.frag (SpectrumBand). THE PAIRING RULE (see
// scene_pack.vert): both stages must declare the SAME uniform block,
// member for member, or the OpenGL program link rejects the two layouts
// (Vulkan never links, so it tolerated the mismatch). Keep this block
// byte-identical to spectrum_bars.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 topColor;
vec4 bottomColor;
float qt_Opacity;
float bandW;
float bandH;
float b0;
float b1;
float b2;
float b3;
float b4;
float b5;
float b6;
float b7;
float b8;
float b9;
float b10;
float b11;
float b12;
float b13;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
@@ -0,0 +1,31 @@
#version 440
// PAIRED with spectrum_energy.frag (SpectrumBand). THE PAIRING RULE (see
// scene_pack.vert): both stages must declare the SAME uniform block,
// member for member, or the OpenGL program link rejects the two layouts.
// Keep this block byte-identical to spectrum_energy.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 topColor;
vec4 bottomColor;
float qt_Opacity;
float bandW;
float bandH;
float b0;
float b1;
float b2;
float b3;
float b4;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
@@ -0,0 +1,73 @@
#version 440
// PAIRED with spectrum_wave.frag (SpectrumBand). THE PAIRING RULE (see
// scene_pack.vert): both stages must declare the SAME uniform block,
// member for member, or the OpenGL program link rejects the two layouts.
// Keep this block byte-identical to spectrum_wave.frag's.
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 qt_TexCoord0;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 topColor;
float qt_Opacity;
float bandW;
float bandH;
float b0;
float b1;
float b2;
float b3;
float b4;
float b5;
float b6;
float b7;
float b8;
float b9;
float b10;
float b11;
float b12;
float b13;
float b14;
float b15;
float b16;
float b17;
float b18;
float b19;
float b20;
float b21;
float b22;
float b23;
float b24;
float b25;
float b26;
float b27;
float b28;
float b29;
float b30;
float b31;
float b32;
float b33;
float b34;
float b35;
float b36;
float b37;
float b38;
float b39;
float b40;
float b41;
float b42;
float b43;
float b44;
float b45;
float b46;
float b47;
};
out gl_PerVertex { vec4 gl_Position; };
void main() {
qt_TexCoord0 = qt_MultiTexCoord0;
gl_Position = qt_Matrix * qt_Vertex;
}
@@ -0,0 +1,197 @@
#version 440
// Tunnel (immersive scene, mode 2) — a line-faithful GLSL 440 port of
// crates/qbz-ui/ui/shaders/tunnel.wgsl (DOOM TUNNEL, original clean-room
// shader). Every constant and every formula below is the reference's number;
// the differences are mechanical and are enumerated here:
//
// * uniform block instead of the bind group (the ShaderEffect contract):
// qt_Matrix/qt_Opacity are Qt-supplied, everything else is a property on
// the effect item, resolved BY NAME out of the .qsb reflection data (see
// ambient.frag). `resolution: vec2` arrives as resX/resY floats, the
// energy/bands vec4s as energyLo/energyHi/bandsLo/bandsHi — the QML
// property names are spelled identically on both sides.
// * uv = qt_TexCoord0 replaces in.uv DIRECTLY (no y-flip) — the same
// convention the ambient.frag port uses and the owner validated against
// the reference frame. Vertically this mirrors the wgpu frame; the scene
// is y-symmetric except the wind/sway phases, so the picture is the
// reference's mirrored, consistent with the Ambient port.
// * `let` -> local float decls; `array<f32,8>(...)` -> `float[8](...)`;
// `atan2(y,x)` -> `atan(y,x)`; `select(f,t,cond)` -> ternary;
// `u32(ringId & 7)` -> int index, `b[ringId & 7]` — two's-complement
// `& 7` on a negative ringId wraps identically to WGSL i32&u32 in both
// languages (-1 & 7 = 7), and the 4096 phase wrap (host side) keeps the
// ring math seamless exactly like the reference.
// * Output is premultiplied (`col * qt_Opacity`), like every other effect
// in this tree; the layer mounts it with blending: false, so opacity is
// 1.0 and the picture equals the reference's `vec4(col, 1.0)`.
//
// QSB-SKIP-GLES100 — build.rs drops the `100 es` variant for this file: GLSL
// ES 1.00 has no integer bitwise ops (band_at's `& 7`), and there is no
// Canvas fallback arm for scenes — on a tier that cannot run the effect the
// picker gate (QbzShell.shaderScenesAvailable) never offers the scene, and a
// load failure makes ShaderSceneLayer hand the background back to the
// atmosphere.
//
// The algorithm (tunnel.wgsl:78-184): NOT a raymarcher — a single fragment
// pass. Chebyshev/box distance r = max(|p.x|, |p.y|) gives SQUARE rings; the
// curvature lives in the PATH (the corridor snakes), never in the
// cross-section; the host forward-motion clock (phase, wrapped at 4096) is
// amplified by FLIGHT_SPEED; colors come from the album-art palette.
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
mat4 qt_Matrix;
vec4 primary;
vec4 secondary;
vec4 accent;
vec4 energyLo;
vec4 energyHi;
vec4 bandsLo;
vec4 bandsHi;
float qt_Opacity;
float time;
float phase;
float beat;
float level;
float resX;
float resY;
float levelSmooth;
// Named transientAmp, not `transient`: the uniform is matched BY NAME to
// a QML property and `transient` is a RESERVED QML keyword (qmlcachegen
// rejects it). Same field, same JSON pack key (`transient`) — only the
// QML-side identifier changes.
float transientAmp;
};
// One of the 8 log FFT bands, selected by ring index (per-ring spectral
// sweep). WGSL masks with `& 7u`; the int two's-complement equivalent wraps
// negatives the same way.
float band_at(int i) {
float b[8] = float[8](
bandsLo.x, bandsLo.y, bandsLo.z, bandsLo.w,
bandsHi.x, bandsHi.y, bandsHi.z, bandsHi.w
);
return b[i & 7];
}
// --- Tunables (the reference's numbers, tunnel.wgsl:65-75) -----------------
// Forward-flight multiplier on the host phase clock. The clock wraps at 4096
// (an integer multiple of 8), so any INTEGER multiplier keeps floor()/fract()/
// `& 7` ring math seamless across the (≈hourly) wrap.
const float FLIGHT_SPEED = 6.0;
// How hard the centerline snakes. The bend is applied to the PATH, so the
// rectangles only translate — they never warp.
const float BEND_AMT = 0.14;
// Number of radial speed-lines fanning out of the vanishing point (even, so
// they stay continuous across the atan seam at ±π).
const float SPOKES = 16.0;
void main() {
float t = time;
vec2 uv = qt_TexCoord0;
// FFT aggregates from the 8 log bands (match the Tauri canvas crossovers:
// bars 0-3 / 4-9 / 10-15 land on even band-pair boundaries).
float bass = clamp((bandsLo.x + bandsLo.y) * 0.5, 0.0, 1.0);
float mid = clamp((bandsLo.z + bandsLo.w + bandsHi.x) / 3.0, 0.0, 1.0);
float high = clamp((bandsHi.y + bandsHi.z + bandsHi.w) / 3.0, 0.0, 1.0);
float beatC = clamp(beat, 0.0, 1.0);
// FAST flight: the host forward-motion clock (base 0.012 + level + beat
// per frame, wrapped at 4096) amplified.
float flight = phase * FLIGHT_SPEED;
// Corridor cross-section is WIDER than tall (a hallway, not a square
// shaft): wider-than-tall scale derived from the viewport aspect.
float viewAspect = resX / max(resY, 1.0);
float scaleX = clamp(1.04 + viewAspect * 0.25, 1.22, 1.58);
float scaleY = clamp(1.38 - scaleX * 0.45, 0.62, 0.82);
// Vanishing point: a gentle Lissajous sway (from `time` only, so its own
// phase never jumps). Kept small — the real motion is the depth-wind.
float cphase = t * 0.18;
vec2 center = vec2(0.5, 0.5);
center.x += sin(cphase) * 0.03 + sin(cphase * 2.08 + 1.2) * 0.012;
center.y += cos(cphase * 0.82 + 0.7) * 0.02;
// First pass: unbent cross-section + depth, so we know how DEEP this
// pixel sits before bending the path.
vec2 p0 = (uv - center) / vec2(scaleX, scaleY);
float r0 = max(abs(p0.x), abs(p0.y)) + 1e-4;
float depth0 = 1.0 / r0;
float z0 = log2(depth0) - flight;
// WINDING CENTERLINE — the curvature is in the PATH, not the rectangle.
// The wave scrolls toward you with `flight`; the near mouth barely bends,
// deep sections swing the most. Louder music = a livelier road.
float windE = 0.75 + levelSmooth * 0.6 + beatC * 0.3;
float windX = sin(z0 * 0.65 + t * 0.6) + 0.5 * sin(z0 * 1.27 - t * 0.9);
float windY = 0.6 * cos(z0 * 0.85 + t * 0.5) + 0.35 * sin(z0 * 1.6 + t * 0.7);
float bendDepth = smoothstep(0.0, 2.6, depth0); // ~0 at the mouth -> 1 deep in
vec2 bend = vec2(windX, windY) * (bendDepth * BEND_AMT * windE);
// Second pass: BENT cross-section coords; BOX distance (Chebyshev) ->
// SQUARE rings that ride the winding path.
vec2 p = p0 - bend;
float r = max(abs(p.x), abs(p.y)) + 1e-4;
float depth = 1.0 / r;
float z = log2(depth) - flight; // minus -> rings grow outward (forward)
int ringId = int(floor(z));
float ringFrac = fract(z);
// Rectangle outline: bright on the frame edge, dark in the gap. Thickness
// breathes with bass + beat.
float lineW = 0.06 + bass * 0.16 + beatC * 0.10;
float edge = smoothstep(0.0, lineW, ringFrac) * smoothstep(0.0, lineW, 1.0 - ringFrac);
float frame = 1.0 - edge;
// Per-ring spectral pulse — the band sweeping bass->treble into depth.
float ringPulse = band_at(ringId);
// Four corridor corner lines (|p.x| == |p.y|) converging to the portal —
// the strongest "hallway" cue.
float corner = 1.0 - smoothstep(0.0, 0.05, abs(abs(p.x) - abs(p.y)));
// RADIAL SPEED-LINES fanning OUT of the vanishing point: thin spokes at
// SPOKES angles, invisible at the portal, fading in just outside it and
// streaming toward the mouth. They rotate very slowly and shimmer hard
// with treble + the beat, so they read as light rushing past.
float ang = atan(p.y, p.x);
float spokeWave = 0.5 + 0.5 * cos(ang * SPOKES + t * 0.25);
float spoke = pow(spokeWave, 12.0)
* smoothstep(0.02, 0.14, r) // emanate from the vanishing point
* (1.0 - smoothstep(0.85, 1.3, r)); // ease off at the near mouth
// Depth shading: black square portal at the center, lit corridor outward.
float depthShade = smoothstep(0.04, 0.55, r);
float nearWeight = smoothstep(0.35, 1.1, r);
// Palette: rings recede primary (near mouth) -> secondary -> accent (far).
float palT = 1.0 - smoothstep(0.05, 0.6, r);
vec3 ringCol = mix(primary.rgb, secondary.rgb, smoothstep(0.0, 0.5, palT));
ringCol = mix(ringCol, accent.rgb, smoothstep(0.5, 1.0, palT));
// Walls: lit gray gradient distinguishing left/right from top/bottom.
float wallLit = (abs(p.x) > abs(p.y)) ? 0.16 : 0.10;
vec3 col = vec3(wallLit) * depthShade * (0.6 + mid * 0.8);
// Ring frames (palette + spectral pulse + bass) and the corner lines.
float ringBright = frame * depthShade * (0.45 + ringPulse * 1.3 + bass * 0.5);
col += ringCol * ringBright;
col += accent.rgb * corner * depthShade * (0.35 + high * 0.7) * frame;
// Radial speed-lines (toward `primary` so they read as bright streaks).
col += primary.rgb * spoke * (0.5 + high * 1.4 + beatC * 0.8);
// Beat punch + a treble rim sparkle on the nearest ring (toward accent).
col *= 1.0 + beatC * 0.6;
col += accent.rgb * high * nearWeight * frame * 0.25;
col = clamp(col, vec3(0.0), vec3(1.0));
// Premultiplied, like every other effect in this tree (blending: false at
// the mount, so qt_Opacity is 1 and this equals the reference frame).
fragColor = vec4(col * qt_Opacity, qt_Opacity);
}
Binary file not shown.
@@ -0,0 +1,533 @@
#version 440
// Tunnel Flow (immersive shader scene, mode 8 — Qt-only) — FRAGMENT stage.
// Block B1 of the 2026-08-15 immersive-completion contract (spec
// 02-tauri-tunnel-port.md). A REWRITE of the legacy Tauri Canvas2D panel
// (qbz-worktrees/legacy-tauri .../panels/TunnelFlowPanel.svelte) as a
// feedback fragment shader: 18 warped square ring shells traveling outward,
// feedback trails (history sampled with the inverse zoom/rotation/drift
// transform at alpha ~0.74, then the near-black fade fill), the background
// wash, the portal (black hole + throat ring + halo), and the corner
// vignette. The feedback history lives in two RGBA8 ping-pong textures owned
// by the C++ TunnelFlowItem (cxx/tunnelflow_item.* — the PlasmaItem shape).
//
// Mechanical differences from the Canvas2D source, enumerated:
// * Vector polygon fills/strokes become PER-PIXEL ANALYTIC evaluation: each
// ring is a square SHELL measured with the Chebyshev distance
// (max(|x|/hx, |y|/hy)) to the warped square. The per-corner jitter of
// makeWarpedSquare is kept as four scalars per square and interpolated
// piecewise-linearly along the perimeter toward the pixel (the side the
// pixel direction hits, between that side's two corners); the boundary
// moves by 0.64*jitter — the outward-normal component of the source's
// (sx*0.6+sy*0.22, sy*0.6-sx*0.22) diagonal displacement.
// * Canvas2D blend modes become explicit color math: `screen` is
// mix(dst, 1-(1-dst)(1-src), srcAlpha) per layer, `multiply` is
// dst *= 1-alpha (black source), and `soft-light` (the diagonal haze) is
// the W3C per-pixel soft-light formula composited with the source alpha
// (spec 02 §3 sanctions "the standard soft-light formula applied
// per-pixel" — this is that choice).
// * The strut sort (rings by perspective) needs no sort: perspective is
// monotonic in travel, so the sorted order is a MODULAR ROTATION of the
// ring indices (sorted rank j = ringIndex (i0+j) % 18, i0 = the ring
// whose travel just wrapped). The gate/span/lane/start formulas are
// ported verbatim — the "simplified deterministic pick" spec 02 §3
// allows, with zero visual approximation beyond the sort itself.
// * drawSpeedMarks is dead code in the source (STREAK_COUNT = 0) and is
// NOT ported (spec 02 §3).
// * The source rendered at 0.58-0.7x CSS size and was upscaled; Qt renders
// at physical size (x DPR, capped 2560x1440 — the plasma_item pattern).
// Stroke widths are multiplied by WIDTH_COMP (1.56 ~ mean 1/scale) so
// the lines keep their on-screen weight; every other constant is
// verbatim.
// * Canvas y is DOWN, texture uv y is UP (uv = pos*0.5+0.5, the plasma
// convention; the GL composite flip is mirrorVertically on the item).
// All motion terms are symmetric sinusoids, so only fixed asymmetries
// would differ — there are none that read as orientation.
// * The 36x36-artwork palette arrives as four vec4 uniforms (Rust port of
// extractLinePaletteFromArtwork, src/tunnelflow_qt.rs); the audio
// smoothing/kick/phase accumulators run in TunnelFlowScene.qml on the
// pulse edge (the pulse law — nothing ticks off-pulse).
//
// No uint arithmetic -> the full qsb variant bake (no QSB-SKIP-GLES100).
layout(std140, binding = 0) uniform buf {
float time; // seconds (the shader converts to the source's ms)
float phase; // the TAURI phase accumulator (TunnelFlowScene.qml)
float bass; // mean of smoothed Viz16 bands 0..3
float mid; // bands 4..9
float high; // bands 10..15
float kick; // kickPulse (decays 0.9/pulse)
vec2 resolution; // history target px (capped 2560x1440)
vec4 palette0;
vec4 palette1;
vec4 palette2;
vec4 palette3;
} u;
layout(binding = 1) uniform sampler2D prev_tex;
layout(location = 0) in vec2 uv;
layout(location = 0) out vec4 fragColor;
// Stroke-width compensation for the source's 0.58-0.7 render scale (see the
// header): 1/0.7 .. 1/0.58 = 1.43..1.72, midpoint ~1.56.
const float WIDTH_COMP = 1.56;
// (e^3.2 - 1) denominator of the spacing curve.
const float SPACING_DENOM = 23.5325301971; // exp(3.2) - 1
const int RING_COUNT = 18;
// Frame-scope values the ring/portal helpers share (set once in main).
float gT; // time, MILLISECONDS (the source's timeMs domain)
float gPhase;
float gBass, gMid, gHigh, gKick;
float gMinDim;
vec2 gTC; // wandering tunnel center, px
vec2 gTScale; // tunnelScaleX/Y (the elliptical cross-section)
vec2 gPx; // the pixel being shaded, px
vec4 pal(int i) {
int k = i - (i / 4) * 4; // i % 4 without the % int pitfalls
if (k == 0) return u.palette0;
if (k == 1) return u.palette1;
if (k == 2) return u.palette2;
return u.palette3;
}
float clamp01(float x) { return clamp(x, 0.0, 1.0); }
// Canvas2D `screen` with source alpha (dst is opaque).
vec3 screenOver(vec3 dst, vec3 src, float a) {
return mix(dst, vec3(1.0) - (vec3(1.0) - dst) * (vec3(1.0) - src), clamp(a, 0.0, 1.0));
}
// W3C soft-light, one channel.
float softLightCh(float s, float d) {
if (s <= 0.5)
return d - (1.0 - 2.0 * s) * d * (1.0 - d);
float g = d <= 0.25 ? ((16.0 * d - 12.0) * d + 4.0) * d : sqrt(d);
return d + (2.0 * s - 1.0) * (g - d);
}
vec3 softLight(vec3 src, vec3 dst) {
return vec3(softLightCh(src.r, dst.r), softLightCh(src.g, dst.g), softLightCh(src.b, dst.b));
}
// makeWarpedSquare's per-corner jitter scalar (verbatim waves).
float cornerJitter(float halfSize, float warp, float seed, int k) {
float fk = float(k);
float waveA = sin(gT * 0.0015 + seed * 0.9 + fk * 1.7);
float waveB = cos(gT * 0.0012 - seed * 0.7 + fk * 1.3);
return halfSize * warp * (waveA * 0.6 + waveB * 0.4);
}
// Warped-square corner position (verbatim displacement).
vec2 cornerPos(vec2 c, float halfSize, float jitter, int k) {
vec2 s = vec2((k == 0 || k == 3) ? -1.0 : 1.0, (k < 2) ? -1.0 : 1.0);
return c + vec2(s.x * halfSize * gTScale.x + (s.x * 0.6 + s.y * 0.22) * jitter * gTScale.x,
s.y * halfSize * gTScale.y + (s.y * 0.6 - s.x * 0.22) * jitter * gTScale.y);
}
// Piecewise-linear interpolation of the four corner jitters along the
// perimeter, toward the pixel direction nq (square-normalized coords).
float perimJitter(vec2 nq, float j0, float j1, float j2, float j3) {
if (abs(nq.x) >= abs(nq.y)) {
float s = clamp(nq.y / max(abs(nq.x), 1e-5), -1.0, 1.0);
return nq.x > 0.0 ? mix(j1, j2, s * 0.5 + 0.5) : mix(j0, j3, s * 0.5 + 0.5);
}
float s = clamp(nq.x / max(abs(nq.y), 1e-5), -1.0, 1.0);
return nq.y > 0.0 ? mix(j3, j2, s * 0.5 + 0.5) : mix(j0, j1, s * 0.5 + 0.5);
}
float segDist(vec2 p, vec2 a, vec2 b) {
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0);
return length(pa - ba * h);
}
// Antialiased stroke coverage: width w px centered on the path.
float strokeCov(float d, float w) {
float aa = max(fwidth(d), 0.6);
return 1.0 - smoothstep(w * 0.5 - aa, w * 0.5 + aa, d);
}
// Per-ring derived geometry (drawTunnelLayers, verbatim constants).
struct Ring {
vec2 c; // bent center, px
float outerHalf;
float innerHalf;
float warpO; // outer warp
float warpI; // inner warp (x0.72)
float fade;
float travel;
float spacing;
};
Ring ringAt(int i, float travelRate) {
float fi = float(i);
float travel = fract(fi / float(RING_COUNT) + travelRate);
float persp = pow(travel, 1.42);
float spacing = (exp(persp * 3.2) - 1.0) / SPACING_DENOM;
float appear = clamp01((persp - 0.18) / 0.26);
float vanish = 1.0 - clamp01((persp - 0.9) / 0.1);
Ring r;
r.fade = pow(max(appear * vanish, 0.0), 0.82);
r.outerHalf = gMinDim * (0.084 + spacing * 0.92);
float thickness = gMinDim * (0.005 + (1.0 - spacing) * (0.028 + gBass * 0.016) + gKick * 0.0036);
r.innerHalf = max(gMinDim * 0.028, r.outerHalf - thickness);
r.warpO = 0.0025 + (1.0 - spacing) * 0.013 + gHigh * 0.004;
r.warpI = r.warpO * 0.72;
float bendStrength = gMinDim * (0.018 + gHigh * 0.01 + gKick * 0.008) * (1.0 - spacing);
r.c = gTC + vec2(sin(gT * 0.0011 + fi * 0.31 + gPhase * 0.12) * bendStrength,
cos(gT * 0.00086 + fi * 0.24 + gPhase * 0.1) * bendStrength * 0.66);
r.travel = travel;
r.spacing = spacing;
return r;
}
void main() {
vec2 res = u.resolution;
float W = res.x;
float minDim = min(res.x, res.y);
float aspect = res.x / max(res.y, 1.0);
gT = u.time * 1000.0;
gPhase = u.phase;
gBass = u.bass;
gMid = u.mid;
gHigh = u.high;
gKick = u.kick;
gMinDim = minDim;
gPx = uv * res; // texture space, y-up (see the header)
float tunnelScaleX = clamp(1.04 + aspect * 0.25, 1.22, 1.58);
float tunnelScaleY = clamp(1.38 - tunnelScaleX * 0.45, 0.62, 0.82);
gTScale = vec2(tunnelScaleX, tunnelScaleY);
// --- Tunnel center wander (render(), verbatim) -------------------------
vec2 canvasCenter = res * 0.5;
float curvePhase = gT * 0.0006 + gPhase * 0.14;
gTC = vec2(
canvasCenter.x + sin(curvePhase) * (W * (0.14 + gHigh * 0.05 + gKick * 0.04))
+ sin(curvePhase * 2.08 + 1.2) * W * 0.042,
canvasCenter.y + cos(curvePhase * 0.82 + 0.7) * (minDim * (0.036 + gBass * 0.018 + gKick * 0.014))
+ cos(curvePhase * 1.7 + 0.4) * minDim * 0.012);
float lateralCurve = clamp((gTC.x - canvasCenter.x) / max(1.0, W * 0.25), -1.0, 1.0);
// --- 1. Feedback (drawFeedback) -----------------------------------------
// The source draws the previous frame with
// M = T(tc) * R(a) * S(zoom) * T(-tc + drift)
// so destination pixel p shows the history at M^-1(p) =
// tc - drift + R(-a) * (p - tc) / zoom.
float fbAngle = sin(gT * 0.0011) * 0.0022 + (gHigh - gBass) * 0.003;
float zoom = 1.004 + gBass * 0.014 + gHigh * 0.01 + gKick * 0.011;
float driftRadius = minDim * (0.006 + gBass * 0.016 + gHigh * 0.01 + gKick * 0.012);
vec2 drift = vec2(cos(gT * 0.001 + gPhase * 0.18), sin(gT * 0.0012 + gPhase * 0.16)) * driftRadius;
vec2 d = gPx - gTC;
float ca = cos(fbAngle);
float sa = sin(fbAngle);
vec2 rd = vec2(d.x * ca + d.y * sa, -d.x * sa + d.y * ca) / zoom; // R(-a)*d
vec2 histUv = (gTC - drift + rd) / res;
vec3 col = texture(prev_tex, histUv).rgb * (0.74 + gKick * 0.08);
// --- 2. Dark fade fill: rgba(3,0,5, 0.28+high*0.08), source-over --------
float fadeA = 0.28 + gHigh * 0.08;
col = col * (1.0 - fadeA) + vec3(3.0, 0.0, 5.0) / 255.0 * fadeA;
// --- 3. Background wash (drawBackground) --------------------------------
// Radial center wash, source-over.
float washT = clamp01((length(gPx - gTC) - minDim * 0.06) / (minDim * 1.16 - minDim * 0.06));
float washA;
vec3 washC;
float a0 = 0.008 + gBass * 0.008;
float a1 = 0.006 + gHigh * 0.006;
if (washT < 0.45) {
float k = washT / 0.45;
washC = mix(vec3(1.0), vec3(180.0 / 255.0), k);
washA = mix(a0, a1, k);
} else {
float k = (washT - 0.45) / 0.55;
washC = vec3(180.0 / 255.0) * (1.0 - k);
washA = a1 * (1.0 - k);
}
col = mix(col, washC, washA);
// Diagonal haze, soft-light (see the header for the formula choice).
float hazeT = clamp01((gPx.x * res.x + gPx.y * res.y) / (res.x * res.x + res.y * res.y));
float hazeA;
vec3 hazeC;
float h0 = 0.004 + gHigh * 0.005;
float h1 = 0.005 + gBass * 0.007;
if (hazeT < 0.5) {
float k = hazeT * 2.0;
hazeC = vec3(1.0 - k);
hazeA = h0 * (1.0 - k);
} else {
float k = (hazeT - 0.5) * 2.0;
hazeC = vec3(180.0 / 255.0) * k;
hazeA = h1 * k;
}
col = mix(col, softLight(hazeC, col), hazeA);
// --- 4. Rings (drawTunnelLayers, screen composite) ----------------------
float travelRate = gPhase * (1.28 + gBass * 0.24 + gKick * 0.34);
Ring prevRing;
float prevJI[4];
for (int i = 0; i < RING_COUNT; ++i) {
Ring r = ringAt(i, travelRate);
float jI[4];
for (int k = 0; k < 4; ++k)
jI[k] = cornerJitter(r.innerHalf, r.warpI, float(i) + 1.7, k);
if (r.fade > 0.0008) {
float jO[4];
for (int k = 0; k < 4; ++k)
jO[k] = cornerJitter(r.outerHalf, r.warpO, float(i) + 0.3, k);
// Warped shell distances (Chebyshev + perimeter jitter).
vec2 q = gPx - r.c;
vec2 nqO = q / vec2(r.outerHalf * gTScale.x, r.outerHalf * gTScale.y);
float jOP = perimJitter(nqO, jO[0], jO[1], jO[2], jO[3]);
float chebO = max(abs(nqO.x), abs(nqO.y)) - 0.64 * jOP / r.outerHalf;
vec2 nqI = q / vec2(r.innerHalf * gTScale.x, r.innerHalf * gTScale.y);
float jIP = perimJitter(nqI, jI[0], jI[1], jI[2], jI[3]);
float chebI = max(abs(nqI.x), abs(nqI.y)) - 0.64 * jIP / r.innerHalf;
// Wall gradient quad (inner->outer): gray a*0.22 -> white a*1.16
// at 44% -> transparent, masked to the shell.
float rI = (r.innerHalf + 0.64 * jIP) / r.outerHalf;
float gRing = (chebO - rI) / max(1.0 - rI, 1e-4);
float alpha = r.fade * (0.2 + gBass * 0.08 + gKick * 0.06);
float wallA;
vec3 wallC;
if (gRing < 0.44) {
float k = clamp(gRing / 0.44, 0.0, 1.0);
wallC = mix(vec3(210.0 / 255.0), vec3(1.0), k);
wallA = mix(alpha * 0.22, min(alpha * 1.16, 1.0), k);
} else {
float k = clamp((gRing - 0.44) / 0.56, 0.0, 1.0);
wallC = vec3(1.0);
wallA = min(alpha * 1.16, 1.0) * (1.0 - k);
}
float aa = max(fwidth(gRing), 0.02);
wallA *= smoothstep(0.0, aa, gRing);
col = screenOver(col, wallC, wallA);
// Sparse wall stains ((i + side) % 3 == 0), radial palette blobs.
for (int side = 0; side < 4; ++side) {
if ((i + side) - ((i + side) / 3) * 3 != 0)
continue;
vec2 nrm = vec2(side == 1 ? 1.0 : (side == 3 ? -1.0 : 0.0),
side == 2 ? 1.0 : (side == 0 ? -1.0 : 0.0));
vec2 tng = vec2(side == 0 ? 1.0 : (side == 2 ? -1.0 : 0.0),
side == 1 ? 1.0 : (side == 3 ? -1.0 : 0.0));
float lane = sin(float(i) * 1.13 + float(side) * 1.7 + gT * 0.0012 + r.travel * 22.0);
vec2 radial = vec2(r.outerHalf * gTScale.x, r.outerHalf * gTScale.y);
vec2 bc = gTC + nrm * radial * 0.82 + tng * radial * 0.58 * lane;
float blobSize = minDim * (0.008 + r.fade * (0.018 + gBass * 0.01));
float bd = length(gPx - bc);
float bt = clamp01((bd - blobSize * 0.14) / (blobSize * 0.94));
vec3 bcC;
float bcA;
if (bt < 0.62) {
float k = bt / 0.62;
bcC = mix(pal(i + side).rgb, pal(i + side + 1).rgb, k);
bcA = mix(alpha * (0.56 + gMid * 0.18), alpha * (0.3 + gHigh * 0.12), k);
} else {
float k = (bt - 0.62) / 0.38;
bcC = pal(i + side + 1).rgb;
bcA = alpha * (0.3 + gHigh * 0.12) * (1.0 - k);
}
float edge = 1.0 - smoothstep(blobSize - max(fwidth(bd), 0.6),
blobSize + max(fwidth(bd), 0.6), bd);
col = screenOver(col, bcC, bcA * edge);
}
// Palette-colored edge stroke on the inner square.
float edgeAlpha = r.fade * (0.34 + gBass * 0.12 + gKick * 0.08);
float edgeWidth = 0.86 + r.fade * (1.78 + gBass * 0.72 + gKick * 0.56);
vec3 edgeColor = pal(i).rgb;
float pxScale = abs(nqI.x) >= abs(nqI.y) ? r.innerHalf * gTScale.x
: r.innerHalf * gTScale.y;
float edgeDist = abs(chebI - 1.0) * pxScale;
col = screenOver(col, edgeColor,
edgeAlpha * strokeCov(edgeDist, edgeWidth * WIDTH_COMP));
// Corner connectors to the previous ring's inner square (same
// stroke style, width x0.88, min 0.74).
if (i > 0) {
float connW = max(0.74, edgeWidth * 0.88) * WIDTH_COMP;
for (int k = 0; k < 4; ++k) {
vec2 pa = cornerPos(prevRing.c, prevRing.innerHalf, prevJI[k], k);
vec2 pb = cornerPos(r.c, r.innerHalf, jI[k], k);
col = screenOver(col, edgeColor,
edgeAlpha * strokeCov(segDist(gPx, pa, pb), connW));
}
}
}
prevRing = r;
for (int k = 0; k < 4; ++k)
prevJI[k] = jI[k];
}
// --- Struts (the sorted cross-ring lines) -------------------------------
// The sort is a modular rotation (see the header); all gate math verbatim.
{
float audioDrive = clamp01(gBass * 0.38 + gHigh * 0.28 + gKick * 1.04);
int linesPerSide = 1 + int(floor(audioDrive * 1.6));
float eventStepMs = max(92.0, 172.0 - audioDrive * 84.0);
float bucket = floor(gT / eventStepMs);
// i0: the ring with the smallest travel (sorted rank 0).
float w = fract(travelRate) * float(RING_COUNT);
int i0 = int(ceil(float(RING_COUNT) - w)) % RING_COUNT;
for (int side = 0; side < 4; ++side) {
int nextSide = (side + 1) % 4;
for (int tr = 0; tr < 2; ++tr) {
if (tr >= linesPerSide)
break;
float seed = float(side) * 11.37 + float(tr) * 3.83 + bucket * 0.41;
float gate = (sin(bucket * 0.47 + gPhase * 2.2 + seed) + 1.0) * 0.5;
if (gate < 0.6 - audioDrive * 0.32)
continue;
int span = gate > 0.76 ? 3 : 2;
int maxStart = RING_COUNT - span - 1;
float startSel = (sin(gT * 0.0014 + gPhase * 1.8 + seed * 0.9) + 1.0) * 0.5;
int startIndex = min(maxStart, int(floor(startSel * float(maxStart + 1))));
int endIndex = min(RING_COUNT - 1, startIndex + span);
float laneSel = clamp01((sin(bucket * 0.73 + seed * 1.3) + 1.0) * 0.5);
float lane = laneSel < 0.333333 ? 0.2 : (laneSel < 0.666667 ? 0.5 : 0.8);
Ring rs = ringAt((i0 + startIndex) % RING_COUNT, travelRate);
Ring re = ringAt((i0 + endIndex) % RING_COUNT, travelRate);
float lineFade = clamp01((rs.fade + re.fade) * 0.7);
vec2 a0 = cornerPos(rs.c, rs.innerHalf,
cornerJitter(rs.innerHalf, rs.warpI,
float((i0 + startIndex) % RING_COUNT) + 1.7, side),
side);
vec2 b0 = cornerPos(rs.c, rs.innerHalf,
cornerJitter(rs.innerHalf, rs.warpI,
float((i0 + startIndex) % RING_COUNT) + 1.7, nextSide),
nextSide);
vec2 a1 = cornerPos(re.c, re.innerHalf,
cornerJitter(re.innerHalf, re.warpI,
float((i0 + endIndex) % RING_COUNT) + 1.7, side),
side);
vec2 b1 = cornerPos(re.c, re.innerHalf,
cornerJitter(re.innerHalf, re.warpI,
float((i0 + endIndex) % RING_COUNT) + 1.7, nextSide),
nextSide);
vec2 p0 = mix(a0, b0, lane);
vec2 p1 = mix(a1, b1, lane);
float strutAlpha = (0.32 + audioDrive * 0.34) * lineFade;
col = screenOver(col, pal(side * 3 + tr + startIndex).rgb,
strutAlpha * strokeCov(segDist(gPx, p0, p1),
(1.5 + audioDrive * 1.4) * WIDTH_COMP));
}
}
}
// --- 5. Portal (drawPortal) ----------------------------------------------
{
float portalHalf = minDim * 0.057;
float throatOuterHalf = portalHalf * 1.58;
float warpO = 0.008 + gHigh * 0.006;
float warpI = 0.004 + gHigh * 0.004;
// Throat ring (screen), gradient white a -> gray a*0.24 at 50% -> 0.
float jO0 = cornerJitter(throatOuterHalf, warpO, 941.0, 0);
float jO1 = cornerJitter(throatOuterHalf, warpO, 941.0, 1);
float jO2 = cornerJitter(throatOuterHalf, warpO, 941.0, 2);
float jO3 = cornerJitter(throatOuterHalf, warpO, 941.0, 3);
float jI0 = cornerJitter(portalHalf, warpI, 942.0, 0);
float jI1 = cornerJitter(portalHalf, warpI, 942.0, 1);
float jI2 = cornerJitter(portalHalf, warpI, 942.0, 2);
float jI3 = cornerJitter(portalHalf, warpI, 942.0, 3);
vec2 q = gPx - gTC;
vec2 nqO = q / vec2(throatOuterHalf * gTScale.x, throatOuterHalf * gTScale.y);
float chebO = max(abs(nqO.x), abs(nqO.y))
- 0.64 * perimJitter(nqO, jO0, jO1, jO2, jO3) / throatOuterHalf;
vec2 nqI = q / vec2(portalHalf * gTScale.x, portalHalf * gTScale.y);
float jIP = perimJitter(nqI, jI0, jI1, jI2, jI3);
float chebI = max(abs(nqI.x), abs(nqI.y)) - 0.64 * jIP / portalHalf;
float sideAlpha = 0.032 + gHigh * 0.015;
float rI = portalHalf / throatOuterHalf;
float gT2 = (chebO - rI) / (1.0 - rI);
float throatA;
vec3 throatC;
if (gT2 < 0.5) {
float k = clamp(gT2 * 2.0, 0.0, 1.0);
throatC = mix(vec3(1.0), vec3(185.0 / 255.0), k);
throatA = mix(sideAlpha, sideAlpha * 0.24, k);
} else {
float k = clamp((gT2 - 0.5) * 2.0, 0.0, 1.0);
throatC = vec3(185.0 / 255.0);
throatA = sideAlpha * 0.24 * (1.0 - k);
}
throatA *= smoothstep(0.0, max(fwidth(gT2), 0.02), gT2);
col = screenOver(col, throatC, throatA);
// The black hole (0.82x the inner square), source-over a=0.98.
float holeDist = (chebI - 0.82) * min(portalHalf * gTScale.x, portalHalf * gTScale.y);
float holeCov = 1.0 - smoothstep(-max(fwidth(holeDist), 0.6), max(fwidth(holeDist), 0.6), holeDist);
col = mix(col, vec3(0.0), 0.98 * holeCov);
// Multiply dark halo out to 4.8x portal (radial, circular).
float haloT = clamp01((length(q) - portalHalf * 0.6) / (portalHalf * 4.8 - portalHalf * 0.6));
float haloA;
if (haloT < 0.32) {
haloA = mix(0.72, 0.48, haloT / 0.32);
} else if (haloT < 0.72) {
haloA = mix(0.48, 0.18, (haloT - 0.32) / 0.4);
} else {
haloA = 0.18 * (1.0 - (haloT - 0.72) / 0.28);
}
col *= 1.0 - haloA;
// Directional front shadow on the curve-leading side (multiply).
float portalEdgeWidth = 0.96 + gBass * 0.26;
float lateralAbs = abs(lateralCurve);
if (lateralAbs > 0.06) {
float shadowStrength = clamp01((lateralAbs - 0.06) / 0.58);
// The curve-leading SIDE of the portal band: x-dominant (for the
// square, the side region is |x| >= |y|) on the sign the tunnel
// center wanders toward.
bool lead = abs(nqI.x) >= abs(nqI.y) && nqI.x * sign(lateralCurve) > 0.0;
float gSh = clamp01((chebI - 0.82) / 0.18);
float shA;
if (gSh < 0.72) {
shA = mix(0.56 + shadowStrength * 0.22, 0.22 + shadowStrength * 0.18, gSh / 0.72);
} else {
shA = (0.22 + shadowStrength * 0.18) * (1.0 - (gSh - 0.72) / 0.28);
}
float inBand = smoothstep(0.0, max(fwidth(gSh), 0.02), gSh)
* (1.0 - smoothstep(1.0 - max(fwidth(gSh), 0.02), 1.0, gSh));
col *= 1.0 - shA * (lead ? inBand : 0.0);
// Dark stroke on the hole edge, leading side only.
float holeEdge = abs(chebI - 0.82) * min(portalHalf * gTScale.x, portalHalf * gTScale.y);
col *= 1.0 - (0.42 + shadowStrength * 0.22)
* (lead ? strokeCov(holeEdge, max(1.0, portalEdgeWidth * 1.2) * WIDTH_COMP) : 0.0);
}
// Portal edge highlight + hole rim (source-over, palette0).
float pxScale = abs(nqI.x) >= abs(nqI.y) ? portalHalf * gTScale.x
: portalHalf * gTScale.y;
float edgeDist = abs(chebI - 1.0) * pxScale;
col = mix(col, pal(0).rgb,
(0.18 + gHigh * 0.06) * strokeCov(edgeDist, portalEdgeWidth * WIDTH_COMP));
float rimDist = abs(chebI - 0.82) * pxScale;
col = mix(col, pal(0).rgb,
(0.14 + gHigh * 0.04) * strokeCov(rimDist, max(0.76, portalEdgeWidth * 0.8) * WIDTH_COMP));
}
// --- 6. Corner vignette (drawCornerVignette, multiply) -------------------
for (int c = 0; c < 4; ++c) {
vec2 corner = vec2((c == 1 || c == 3) ? res.x : 0.0, (c < 2) ? 0.0 : res.y);
float vt = clamp01(length(gPx - corner) / (minDim * 0.86));
float va;
if (vt < 0.44) {
va = mix(0.72, 0.38, vt / 0.44);
} else {
va = 0.38 * (1.0 - (vt - 0.44) / 0.56);
}
col *= 1.0 - va;
}
fragColor = vec4(col, 1.0);
}
@@ -83,6 +83,26 @@ Item {
property real glowOpacity: Math.min(0.1 + root.globalEnergy * 1.5, 1.0)
// --- Base art box (:84-92) ---------------------------------------------
// D2 (contract 04 §4): size-aware large art. `artSource` prefers the
// size-resolved large feed and falls back to the small one while it
// resolves (the Slint `artwork-large : artwork` pattern); the probe reads
// the SAME source so the native cap tracks the image actually shown.
readonly property string artSource: QbzPlayer.npArtworkPathLarge !== ""
? QbzPlayer.npArtworkPathLarge : QbzPlayer.npArtworkPath
// The baseArt slot expression WITHOUT the native cap — the request must
// reflect the SLOT so the feed can serve a variant big enough for it.
readonly property real artSlot: Math.max(180,
Math.min(Math.min((root.height - 384) / 1.25, root.width * 0.62), 660))
// Bucketed in Rust (one re-resolve per variant tier crossed, none per
// pixel); gated on visible so a hidden panel writes nothing (pulse law).
function requestArtSize() {
if (root.visible)
QbzPlayer.requestNpArtworkSize(Math.round(root.artSlot))
}
onArtSlotChanged: requestArtSize()
onVisibleChanged: requestArtSize()
Component.onCompleted: requestArtSize()
// Native source resolution — cap the RESTING art so the cover is never
// UPSCALED beyond its own size (owner: oversized blurry art looked
// nefasto); the audio breathing still grows it momentarily. Slint reads
@@ -92,7 +112,7 @@ Item {
Image {
id: artProbe
visible: false
source: QbzPlayer.npArtworkPath
source: root.artSource
}
readonly property real srcNative: artProbe.status === Image.Ready
? artProbe.implicitWidth : 0
@@ -175,7 +195,7 @@ Item {
RoundedImage {
anchors.fill: parent
radius: 8
source: QbzPlayer.npArtworkPath
source: root.artSource
}
}
}
+22 -6
View File
@@ -74,6 +74,17 @@ Item {
Math.min(Math.min(root.height - 372, root.width * 0.52), 560))
readonly property real pitch: root.baseArt * 0.42
// D2 (contract 04 §4): the CENTER card is a large slot (up to 560 CSS
// px) — report its size so the large-art feed re-resolves per bucket;
// the card below binds large-feed-first with the row cover as last
// fallback. Bucketed in Rust; invisible panel writes nothing (pulse law).
function requestArtSize() {
if (root.visible)
QbzPlayer.requestNpArtworkSize(Math.round(root.baseArt))
}
onBaseArtChanged: requestArtSize()
onVisibleChanged: requestArtSize()
// --- Animated scroll — the ONLY motion (:152-153) -----------------------
property real scroll: root.cfDoc.index
Behavior on scroll { NumberAnimation { duration: 320; easing.type: Easing.InOutQuad } }
@@ -88,7 +99,10 @@ Item {
root.coverMap = Object.assign({}, m)
}
}
Component.onCompleted: root.dispatchCovers()
Component.onCompleted: {
root.dispatchCovers()
requestArtSize() // D2 initial large-art request
}
onCfDocChanged: root.dispatchCovers()
function dispatchCovers() {
var tracks = root.cfDoc.tracks
@@ -274,9 +288,9 @@ Item {
// CENTER card — drawn LAST so it paints over its neighbors
// (:255-273). Bound to the current index's offset (eases to
// 0 with `scroll`). Prefers the unified large now-playing
// cover; falls back to the model row's cover while it
// resolves. Non-interactive.
// 0 with `scroll`). Prefers the size-resolved large
// now-playing cover (D2), then the small feed, then the
// model row's cover while they resolve. Non-interactive.
CoverCard {
readonly property string rowCover: root.centerIdx >= 0
&& root.centerIdx < root.cfLen
@@ -286,8 +300,10 @@ Item {
pitch: root.pitch
stageCx: fanStage.cx
stageHeight: fanStage.height
artSource: QbzPlayer.npArtworkPath !== ""
? QbzPlayer.npArtworkPath : rowCover
artSource: QbzPlayer.npArtworkPathLarge !== ""
? QbzPlayer.npArtworkPathLarge
: (QbzPlayer.npArtworkPath !== ""
? QbzPlayer.npArtworkPath : rowCover)
hasArt: artSource !== ""
interactive: false
}
@@ -191,10 +191,10 @@ Item {
}
fragmentShader: "../assets/shaders/atmosphere.frag.qsb"
// Shared default-equivalent vertex stage (Qt 6.11's built-in default
// emits no qt_TexCoord0, so the program link fails without an
// explicit one — the same file SpectrumBand/AmbientField use).
vertexShader: "../assets/shaders/spectrum.vert.qsb"
// Paired vertex stage (Qt 6.11's built-in default emits no
// qt_TexCoord0); the GL link requires both stages to declare the
// SAME uniform block (see atmosphere.vert / scene_pack.vert).
vertexShader: "../assets/shaders/atmosphere.vert.qsb"
}
// --- FALLBACK arm: the original four-Image stack, verbatim ----------------
+99 -15
View File
@@ -75,6 +75,8 @@ Item {
}
// One row model entry: vm 0 = FOCUS (mode m), vm 1 = SPLIT (panel sp).
// Block A1 adds `sc`: >= 0 = a SHADER SCENE row (the Slint shader
// rows at ImmersiveView.slint:654-711), -1/absent = a panel row.
// `entry` names the §5.5 entry load fired alongside setView:
// "queue" -> QbzQueue.queuePanelOpened()
// "trackinfo" -> QbzAlbum.openTrackInfo(QbzPlayer.npTrackId)
@@ -82,6 +84,19 @@ Item {
// "" -> none (Lyrics rows: Qt fetches lyrics
// automatically per track, §5.5).
function fireRow(row) {
if (row.sc !== undefined && row.sc >= 0) {
// Shader scene row: FOCUS view + scene N (Slint sets
// view-mode=0 and shader-mode=N and leaves `mode` alone;
// setView is the ONLY mode mutator here, §3.2).
if (row.sc > 0 && QbzImmersive.viewMode !== 0)
QbzImmersive.setView(0, QbzImmersive.mode, QbzImmersive.splitPanel)
QbzShaderScene.scene = row.sc
viewMenu.close()
return
}
// Panel rows turn the scene OFF — every Slint panel row sets
// shader-mode = 0 (:586-650) — then setView as before.
QbzShaderScene.scene = 0
QbzImmersive.setView(
row.vm === 0 ? 0 : 1,
row.vm === 0 ? row.m : QbzImmersive.mode,
@@ -99,9 +114,19 @@ Item {
id: menuRow
Rectangle {
required property var modelData
readonly property bool active: modelData.vm === 0
? (QbzImmersive.viewMode === 0 && QbzImmersive.mode === modelData.m)
: (QbzImmersive.viewMode === 1 && QbzImmersive.splitPanel === modelData.sp)
// A1: shader rows (sc >= 0) are active when their scene is
// on; FOCUS panel rows additionally require the scene OFF
// (Slint: `active: is-focus && sh == 0 && md == N`).
readonly property bool active: {
if (modelData.sc !== undefined && modelData.sc >= 0)
return QbzShaderScene.scene === modelData.sc
if (modelData.vm === 0)
return QbzImmersive.viewMode === 0
&& QbzImmersive.mode === modelData.m
&& QbzShaderScene.scene === 0
return QbzImmersive.viewMode === 1
&& QbzImmersive.splitPanel === modelData.sp
}
width: parent ? parent.width : 0
height: 33
radius: 8
@@ -157,7 +182,7 @@ Item {
Repeater {
// FOCUS rows IN SLINT ORDER (:586-650): Album Reactive(0),
// Static(1), Coverflow(2), Spectrum(3), Wave Bed(6), Lyrics(4),
// Queue(5). NO shader rows (owner ruling 1).
// Queue(5).
model: [
{ "vm": 0, "m": 0, "sp": -1, "entry": "",
"label": QbzSession.tr("Album Reactive", QbzSession.trRev) },
@@ -176,6 +201,43 @@ Item {
]
delegate: menuRow
}
Repeater {
// A1 shader rows (:654-711), inside the FOCUS group like Slint
// (no separate header there). SHIPPED scenes only — the Slint
// order is Plasma, Tunnel, Aurora, Ambient, Spectral Ribbon,
// Line Bed: Plasma shipped with A2, the Ribbon with A3; Liquid
// Spectrum is parked in Slint itself, so its row DOES NOT
// appear (00-CONTRACT ruling 1); Line Bed shipped with A4 and
// appears LAST here, the shipped-set tail.
// There is NO "Off" row (owner ruling 2026-08-15: Slint has
// none — a panel row already turns the scene off, and `g`
// cycles back to 0). The whole group hides on tiers that
// cannot run the shaders (the Slint `if shader-scenes-available`
// gates) — QbzShell.shaderScenesAvailable is the single source
// of truth, seeded from the Rust renderer probe. The six A-block
// labels are EXISTING qbz-ui msgids; B1's "Tunnel Flow" is the
// one NEW msgid (added to all 8 locales).
model: QbzShell.shaderScenesAvailable ? [
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 1,
"label": QbzSession.tr("Plasma", QbzSession.trRev) },
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 2,
"label": QbzSession.tr("Tunnel", QbzSession.trRev) },
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 3,
"label": QbzSession.tr("Aurora", QbzSession.trRev) },
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 7,
"label": QbzSession.tr("Ambient", QbzSession.trRev) },
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 4,
"label": QbzSession.tr("Spectral Ribbon", QbzSession.trRev) },
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 5,
"label": QbzSession.tr("Line Bed", QbzSession.trRev) },
// B1: Tunnel Flow (sc 8) — the QT-ONLY scene (spec 02),
// after Line Bed. Menu-only: NOT in the `g` ring (spec 02
// §5). NEW msgid (added to all 8 locales).
{ "vm": 0, "m": -1, "sp": -1, "entry": "", "sc": 8,
"label": QbzSession.tr("Tunnel Flow", QbzSession.trRev) },
] : []
delegate: menuRow
}
Text {
height: 26
leftPadding: 10
@@ -252,15 +314,24 @@ Item {
}
// --- RIGHT: the window-controls capsule --------------------------------
// Collapsed: 44px circle, sliders glyph. Hover expands it LEFTWARD to
// 112px (150ms ease-in-out, anchored right) revealing the fullscreen
// toggle and the X exit. Minimize/maximize/drag parked (Slint :1173-1183).
// Collapsed: 44px circle, sliders glyph. Expands LEFTWARD to 112px
// (150ms ease-in-out, anchored right) revealing the fullscreen toggle
// and the X exit. Minimize/maximize/drag parked (Slint :1173-1183).
//
// The expansion is the Slint state machine ported 1:1
// (ImmersiveView.slint:1057-1184): `expanded = pinned || anyHover` is a
// BOOL and the buttons gate on that bool — NEVER on the animated width.
// (2026-08-15 flicker root cause: gating on `capsule.width > 100`
// mid-animation let the binding flip while the capsule was traveling,
// and the expanding left edge could cross a resting cursor frame by
// frame — a visible 44↔112 bounce. Clicking the circle toggles `pinned`
// (Slint circle-ta, :1159-1162), which is what "stays 100% open" means.)
Rectangle {
id: capsule
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
height: 36
width: capHover.containsMouse ? 112 : 44
width: expanded ? 112 : 44
radius: 18
color: "#80000000"
border.width: 1
@@ -270,10 +341,23 @@ Item {
NumberAnimation { duration: 150; easing.type: Easing.InOutQuad }
}
// Click-pin state; survives the auto-hide (Slint keeps it too).
property bool pinned: false
// Hover over ANY part of the capsule: the background or either
// button (their hover areas extend 9px past the glyphs).
readonly property bool anyHover: capHover.containsMouse
|| fsArea.containsMouse || xArea.containsMouse
readonly property bool expanded: pinned || anyHover
MouseArea {
id: capHover
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
// Collapsed-circle click = pin open (Slint circle-ta). Clicking
// the expanded body un-pins; hover still holds it open, so this
// can never collapse anything out from under the cursor.
onClicked: capsule.pinned = !capsule.pinned
}
// Collapsed-state glyph (fades out as the capsule opens).
@@ -283,7 +367,7 @@ Item {
height: 16
anchors.centerIn: parent
tintName: "white"
opacity: capsule.width < 100 ? 1 : 0
opacity: capsule.expanded ? 0 : 1
Behavior on opacity { NumberAnimation { duration: 100 } }
}
@@ -299,18 +383,18 @@ Item {
x: capsule.width - 72
anchors.verticalCenter: parent.verticalCenter
tintName: fsArea.containsMouse ? "white" : "muted"
opacity: capsule.width > 100 ? 1 : 0
opacity: capsule.expanded ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 100 } }
MouseArea {
id: fsArea
anchors.fill: parent
anchors.margins: -9
// Gated on the expansion: the two button MouseAreas are
// Gated on the expansion BOOL: the two button MouseAreas are
// INVISIBLE while collapsed but would still cover the 44px
// circle (the -9 margins make the X's hit area span almost
// all of it), so a click on the collapsed capsule exited
// immersive instead of doing nothing.
enabled: capsule.width > 100
// immersive instead of pinning it.
enabled: capsule.expanded
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
@@ -329,13 +413,13 @@ Item {
x: capsule.width - 36
anchors.verticalCenter: parent.verticalCenter
tintName: xArea.containsMouse ? "white" : "muted"
opacity: capsule.width > 100 ? 1 : 0
opacity: capsule.expanded ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 100 } }
MouseArea {
id: xArea
anchors.fill: parent
anchors.margins: -9
enabled: capsule.width > 100
enabled: capsule.expanded
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
// Exit path 2 (§5.4) — every exit funnels through the bridge's
+138 -28
View File
@@ -17,8 +17,13 @@
//
// Layer order bottom->top (§5.1):
// 1. root color #0a0a0b, clip (:1199-1200)
// 2. ImmersiveAtmosphere — ALWAYS the underlay (the Slint shader-mode==0
// gate is constant in v1, ruling 1; :1313-1321)
// 1b. ShaderSceneLayer (block A1, :1293-1300) — the GPU shader scene,
// bottom-most VISUAL layer when QbzShaderScene.scene > 0, replacing
// the atmosphere AND the FOCUS/SPLIT panels (their gates below gain
// `scene === 0`, parity :1313-1405); chrome stays on top
// 2. ImmersiveAtmosphere — the underlay while NO scene is active
// (gated `scene === 0`; in v1 the shader-mode==0 gate was constant,
// ruling 1; :1313-1321)
// 2b. FULL-COVERAGE click-blocker MouseArea (load-bearing — without it
// clicks pass through to the desktop header search field, the dock's
// spectrum band and the viz eye toggle; port of the Slint root
@@ -117,15 +122,27 @@ Item {
color: "#0a0a0b"
}
// --- Layer 1b: the shader scene (block A1, :1293-1300) ------------------
// Bottom-most VISUAL layer, ABOVE the root surface, below everything
// else. Self-gated: it renders and ticks only while a scene is active
// (scene > 0 && open && available — see the file's header). The
// atmosphere below and every FOCUS/SPLIT panel gate themselves off on
// `scene === 0`, so the scene owns the background (parity :1313-1405).
ShaderSceneLayer {
anchors.fill: parent
visible: QbzShaderScene.scene > 0
}
// --- Layer 2: the atmosphere underlay (§5.1, :1313-1321) ----------------
// ALWAYS the underlay in v1 (the Slint shader-mode==0 gate is constant,
// ruling 1). Source = the host-generated 128x128 atmosphere PNG, fallback
// The underlay WHILE NO SCENE IS ACTIVE (the Slint shader-mode==0 gate,
// :1313). Source = the host-generated 128x128 atmosphere PNG, fallback
// the plain cover; dim 0.15. `animated` binds npPlaying (:1321); the
// && open arm stops the drift clock while the overlay is closed (the
// Slint view is UNMOUNTED then — same zero cost). Spectrum/WaveBed paint
// opaque #000 over it — intended (§5.1).
ImmersiveAtmosphere {
anchors.fill: parent
visible: QbzShaderScene.scene === 0
source: QbzImmersive.atmosphereUrl
fallbackSource: QbzPlayer.npArtworkPath
animated: QbzPlayer.npPlaying && QbzImmersive.open
@@ -137,6 +154,16 @@ Item {
anchors.fill: parent
acceptedButtons: Qt.AllButtons
hoverEnabled: true
// C1 fullscreen integration (contract 03 §5, divergence D2 — not a
// Slint parity item): blank the cursor when the chrome has
// auto-hidden in FullScreen; wake() restores it. Windowed mode keeps
// the cursor always. Note: panels with their own cursor-less
// MouseAreas above this layer still show the default arrow — the
// blank covers the bare-atmosphere regions, which is where a
// stationary cursor rests while watching fullscreen.
cursorShape: (root.Window.window !== null
&& root.Window.window.visibility === Window.FullScreen
&& !root.chromeVisible) ? Qt.BlankCursor : Qt.ArrowCursor
onPressed: function (mouse) { mouse.accepted = true }
onReleased: function (mouse) { mouse.accepted = true }
onClicked: function (mouse) { mouse.accepted = true }
@@ -146,20 +173,40 @@ Item {
// --- §5.3 auto-hide / wake ----------------------------------------------
// hideTimer 6000ms (:1271); hides chrome only when !immSearchOpen &&
// !pointerInChrome (:1275); pointerInChrome = pointerInWindow &&
// (y <= 64 || y >= height-132) (:1196-1197, HoverHandler on the root);
// wake on any mouse move (:1283-1286); 300ms fades on the chrome itself.
// !pointerInChrome; wake on any REAL mouse move (delta guard below);
// 300ms fades on the chrome itself.
//
// 2026-08-15 C1 (contract 03 §4): pointerInChrome is the union of the
// REAL chrome rects (header ∪ player bar ∪ song card), not the Slint
// y-only bands (:1196-1197). The bands kept the chrome awake over dead
// strips (the 24px side margins, the 18px above the bar) which read as
// "mouse-sensitive in some zones", and spanned the full width.
property bool chromeVisible: true
readonly property bool pointerInWindow: rootHover.hovered
readonly property bool pointerInChrome: rootHover.hovered
&& (rootHover.point.position.y <= 64
|| rootHover.point.position.y >= root.height - 132)
&& (pointInChromeItem(header) || pointInChromeItem(playerBar)
|| pointInChromeItem(songCard))
function pointInChromeItem(item) {
if (!item.visible)
return false
var p = item.mapFromItem(root, rootHover.point.position.x,
rootHover.point.position.y)
return p.x >= 0 && p.y >= 0 && p.x <= item.width && p.y <= item.height
}
function wake() {
chromeVisible = true
hideTimer.restart()
}
// C1 macOS traffic-light inset (contract 03 §6) — same rule as the
// shell's HeaderBar: ask SafeArea, floor at 78, only when the native
// lights float over client area (i.e. not with the system title bar).
readonly property int chromeLeftInset:
QbzShell.isMacos && !QbzShell.systemTitleBar
? Math.max(root.SafeArea.margins.left, 78) : 0
// Last hover position that WOKE the chrome. Load-bearing delta guard:
// Qt re-delivers HoverMove at the unchanged position whenever the scene
// under a stationary cursor updates (constant on any animated surface —
@@ -198,26 +245,33 @@ Item {
// --- Layer 3: the FOCUS panels (B3 + B4) --------------------------------
// FOCUS: one panel per mode, gated viewMode==0 && mode==N, full-viewport
// — each panel carries its own Slint-internal reserves (pad-top 52/70,
// the 132px player clearance; §6.1/§6.2/§6.6).
// the 132px player clearance; §6.1/§6.2/§6.6). Block A1 adds the
// `scene === 0` gate to every panel (parity :1313-1405 — a shader scene
// REPLACES the panels; chrome stays on top).
AlbumReactivePanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 0
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 0
}
StaticPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 1
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 1
}
CoverflowPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 2
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 2
}
SpectrumPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 3
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 3
}
WaveBedPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 6
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 6
}
// FOCUS Lyrics (mode 4, B4 §6.6): the giant-line variant. It shares the
// immersive LyricsSyncEngine with the split lyrics mount (trap 22 — the
@@ -225,7 +279,8 @@ Item {
// fetches lyrics automatically per track (§5.5).
LyricsFocusPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 4
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 4
lines: root.immLyricsLines
synced: root.immLyricsSynced
status: root.immLyricsStatus
@@ -235,7 +290,8 @@ Item {
// placement, full-screen (centered: false -> min(vw-96, 720) column).
QueueTabsPanel {
anchors.fill: parent
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 5
visible: QbzShaderScene.scene === 0
&& QbzImmersive.viewMode === 0 && QbzImmersive.mode === 5
centered: false
}
@@ -260,6 +316,7 @@ Item {
LyricsSyncEngine {
id: immLyricsEngine
gateOpen: QbzImmersive.open
&& QbzShaderScene.scene === 0 // A1: the scenes replace the panels
&& ((QbzImmersive.viewMode === 0 && QbzImmersive.mode === 4)
|| (QbzImmersive.viewMode === 1 && QbzImmersive.splitPanel === 0))
}
@@ -284,7 +341,11 @@ Item {
Item {
id: splitRoot
anchors.fill: parent
visible: QbzImmersive.viewMode === 1
// A1: a shader scene replaces the SPLIT layout too (:1416 parity).
visible: QbzShaderScene.scene === 0 && QbzImmersive.viewMode === 1
// D2: re-request the large art when the SPLIT layout becomes visible
// (leftCol's own request is gated on this visibility).
onVisibleChanged: if (visible) leftCol.requestArtSize()
// col-h: the column height below the header/player clearance
// (:1415). colW: the explicit half (:1435).
@@ -306,6 +367,24 @@ Item {
width: splitRoot.colW
height: parent.height
// D2 (contract 04 §4): size-aware large art — prefer the
// size-resolved large feed, fall back to the small one while
// it resolves (the StaticPanel/AlbumReactivePanel pattern).
readonly property string artSource: QbzPlayer.npArtworkPathLarge !== ""
? QbzPlayer.npArtworkPathLarge : QbzPlayer.npArtworkPath
// The artSize slot expression WITHOUT the native cap — the
// request must reflect the SLOT; the probe cap below stays
// the final upscale safety. Bucketed in Rust (one re-resolve
// per variant tier crossed, none per pixel).
readonly property real artSlot: Math.max(240,
Math.min(splitRoot.colW, splitRoot.colH - 200))
function requestArtSize() {
if (splitRoot.visible)
QbzPlayer.requestNpArtworkSize(Math.round(leftCol.artSlot))
}
onArtSlotChanged: requestArtSize()
Component.onCompleted: requestArtSize()
// Native source resolution (physical px) of the active
// cover, so the art is never UPSCALED beyond its own size
// (:1449-1452) — the AlbumReactivePanel.qml artProbe idiom
@@ -314,7 +393,7 @@ Item {
Image {
id: splitArtProbe
visible: false
source: QbzPlayer.npArtworkPath
source: leftCol.artSource
}
readonly property real srcNative: splitArtProbe.status === Image.Ready
? splitArtProbe.implicitWidth : 0
@@ -365,7 +444,7 @@ Item {
height: leftCol.artSize
visible: QbzPlayer.npArtworkPath !== ""
radius: 12
source: QbzPlayer.npArtworkPath
source: leftCol.artSource
}
}
@@ -463,15 +542,20 @@ Item {
}
// --- Layer 4: ImmersiveSongCard (§5.1, :1602-1605) ----------------------
// Visible ONLY viewMode==0 && mode==6 && npHasTrack (trap 19);
// bottom-right 24px insets; NON-interactive; does NOT fade with the
// auto-hide chrome (no opacity binding here — that is deliberate).
// Slint shows it bottom-right ONLY over the shader backgrounds OR in
// WaveBed (shader-mode > 0 || (view-mode == 0 && mode == 6)) &&
// has-track — the focus panels render their own metadata. In v1
// shader-mode was constant 0 so the first arm was dead (trap 19); A1
// makes it real. NON-interactive; does NOT fade with the auto-hide
// chrome (no opacity binding here — that is deliberate).
ImmersiveSongCard {
id: songCard
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.rightMargin: 24
anchors.bottomMargin: 24
visible: QbzImmersive.viewMode === 0 && QbzImmersive.mode === 6
visible: (QbzShaderScene.scene > 0
|| (QbzImmersive.viewMode === 0 && QbzImmersive.mode === 6))
&& QbzPlayer.npHasTrack
}
@@ -481,7 +565,8 @@ Item {
Connections {
target: QbzPlayer
function onNpTrackIdChanged() {
if (!root.visible || QbzImmersive.viewMode !== 1)
if (!root.visible || QbzImmersive.viewMode !== 1
|| QbzShaderScene.scene !== 0) // A1: split panels unmounted under a scene
return
if (QbzImmersive.splitPanel === 1)
QbzAlbum.openTrackInfo(QbzPlayer.npTrackId)
@@ -507,6 +592,24 @@ Item {
QbzImmersive.open = false
event.accepted = true
}
// Block A1: `g` cycles the SHIPPED shader scenes (0→1→2→3→4→5→7→0 with
// Plasma A2, Ribbon A3 and Line Bed A4 shipped — the ring lives in
// QbzShaderScene.cycleScene; Tunnel Flow 8 is menu-only, NOT in the
// ring). No-op on tiers where the scenes can't run
// (QbzShell.shaderScenesAvailable — the same flag the FOCUS menu rows
// check), and the textInputActive gate keeps a 'g' typed in the search
// field from cycling (§5.4). wake() on cycle, like Slint. The key is
// ACCEPTED even when unavailable — Slint's `return accept` — so it never
// falls through to another handler.
Keys.onPressed: function (event) {
if (event.key === Qt.Key_G && !root.textInputActive) {
if (QbzShell.shaderScenesAvailable) {
QbzShaderScene.cycleScene()
root.wake()
}
event.accepted = true
}
}
// The seek arrows are GONE (2026-08-03 hotkeys-port §1.3): ±5s/±10s now
// fire as the REBINDABLE focus.seekForward/Back/Long actions through the
// AppShell dispatcher, with the Context::Immersive gate and the central
@@ -517,6 +620,9 @@ Item {
// --- Layer 5: the player bar (§5.7, :1607-1616) -------------------------
// Centered, y = height-90-24; fades with the auto-hide chrome on the
// SAME binding as the header (300ms), inert while hidden.
// C1: hit-enabled follows the STATE (`chromeVisible`), not the animated
// opacity — gating on `opacity > 0` left the bar clickable mid-fade and
// re-triggered the Behavior on wake/hide races (contract 03 §2 item 4).
ImmersivePlayerBar {
id: playerBar
anchors.horizontalCenter: parent.horizontalCenter
@@ -524,7 +630,7 @@ Item {
viewportWidth: root.width
opacity: root.chromeVisible ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 300 } }
enabled: opacity > 0
enabled: root.chromeVisible
onWakeRequested: root.wake()
}
@@ -534,13 +640,17 @@ Item {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.leftMargin: 24
// C1 macOS: clear the native traffic-light cluster (it floats over
// the top-left corner, x ≈ 7-85 — the view trigger's exact spot) with
// the same inset the shell HeaderBar computes
// (HeaderBar.qml chromeLeftInset: SafeArea left margin, 78 floor).
anchors.leftMargin: 24 + root.chromeLeftInset
anchors.rightMargin: 24
anchors.topMargin: 16
height: 36
opacity: root.chromeVisible ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 300 } }
enabled: opacity > 0
enabled: root.chromeVisible
}
// --- Layer 7: the search cortinilla (§3.4, :1695-1705) -------------------
@@ -0,0 +1,48 @@
// Line Bed (immersive shader scene, mode 5) — the QML wrapper for the C++
// `LineBedItem` (cxx/linebed_item.*, the project's first QQuickRhiItem).
// Block A4 of the 2026-08-15 immersive-completion contract (spec 01 §2.5).
//
// Its own file (not an inline Component in ShaderSceneLayer.qml) so the RHI
// item's contract is one screen of QML — and so the C++ type name only has
// to resolve when this file compiles, which the tier gate already ensures
// never happens where the RHI can't run it (the Loader in
// ShaderSceneLayer.qml activates only while `root.active && scene === 5`).
//
// THE PULSE LAW: the item repaints ONLY from `pulseTick()`, which
// ShaderSceneLayer calls on the shared shell pulse (QbzShell.pulseMs) with
// the ring publish it stashed on the viz tick. `heights` has no NOTIFY and
// nothing binds it; the palette colors ride QbzShell's ambient triad (the
// same ambient_qt source every other scene uses — they change on track
// change, not per tick).
import QtQuick
import QtQuick.Window
import com.blitzfc.qbz
LineBedItem {
id: root
// The empirical orientation matrix (2026-08-15, BOTH verified today):
// owner's Vulkan + mirror=false -> bed UPSIDE-DOWN
// Xvfb Mesa GL + mirror=true -> bed UPSIDE-DOWN (peaks hang down)
// So the correct rule is mirror on everything EXCEPT OpenGL — my first
// guess (GL-only) had it exactly backwards, and "unconditional" broke GL.
mirrorVertically: GraphicsInfo.api !== GraphicsInfo.OpenGL
// The ambient palette triad (shell_bridge.rs; pushed per track by
// playback_qt.rs). The Slint reference defaults #00dcc8 / #3fd9c8 live
// in the C++ member initializers, so a pre-art track still looks right.
primary: QbzShell.ambientPrimary
accent: QbzShell.ambientAccent
// Called by ShaderSceneLayer on the pulse edge ONLY. `h` is the stashed
// 256x200 f32 ring (QbzShaderScene.linebedHeights, raw bytes) or null
// when the viz drain published nothing new (player paused); the repaint
// still runs so the item tracks its parent's resizes/palette changes at
// the same cadence the sibling ShaderEffect scenes tick their clocks.
function pulseTick(h) {
if (h !== null)
heights = h
update()
}
}
@@ -0,0 +1,48 @@
// Plasma (immersive shader scene, mode 1) — the QML wrapper for the C++
// `PlasmaItem` (cxx/plasma_item.*, the feedback-fluid QQuickRhiItem).
// Block A2 of the 2026-08-15 immersive-completion contract (spec 01 §2.1).
//
// Its own file (the LineBedScene.qml idiom) so the RHI item's contract is
// one screen of QML — and so the C++ type name only has to resolve when
// this file compiles, which the tier gate already ensures never happens
// where the RHI can't run it (the Loader in ShaderSceneLayer.qml activates
// only while `root.active && scene === 1`).
//
// THE PULSE LAW: the item repaints ONLY from `pulseTick()`, which
// ShaderSceneLayer calls on the shared shell pulse (QbzShell.pulseMs) with
// the applied pack it stashed on the viz tick. The properties have no
// NOTIFY and nothing binds them; the palette colors ride QbzShell's ambient
// triad (they change on track change, not per tick).
import QtQuick
import QtQuick.Window
import com.blitzfc.qbz
PlasmaItem {
id: root
// mirrorVertically rule (2026-08-15, verified BOTH ways today): mirror
// on Vulkan/Metal/D3D, NOT on OpenGL — the empirical matrix lives in
// LineBedScene.qml (owner's Vulkan + no mirror = flipped; Mesa GL +
// mirror = flipped). The feedback passes are self-consistent in texture
// space; this only affects the composite.
mirrorVertically: GraphicsInfo.api !== GraphicsInfo.OpenGL
// Called by ShaderSceneLayer on the pulse edge ONLY. `p` carries the
// applied pack values + the palette + the local scene clock; assigning
// the MEMBER properties and repainting ONCE per pulse is the whole
// cadence contract (the sibling ShaderEffect scenes tick their clocks
// at the same edge).
function pulseTick(p) {
time = p.time
beat = p.beat
level = p.level
levelSmooth = p.levelSmooth
energyLo = p.energyLo
energyHi = p.energyHi
primary = p.primary
secondary = p.secondary
accent = p.accent
update()
}
}
@@ -0,0 +1,43 @@
// Spectral Ribbon (immersive shader scene, mode 4) — the QML wrapper for
// the C++ `RibbonItem` (cxx/ribbon_item.*, the persistent-spectrogram
// QQuickRhiItem). Block A3 of the 2026-08-15 immersive-completion contract
// (spec 01 §2.4).
//
// Its own file (the LineBedScene.qml idiom) so the RHI item's contract is
// one screen of QML — and so the C++ type name only has to resolve when
// this file compiles, which the tier gate already ensures never happens
// where the RHI can't run it (the Loader in ShaderSceneLayer.qml activates
// only while `root.active && scene === 4`).
//
// THE PULSE LAW: the item repaints ONLY from `pulseTick()`, which
// ShaderSceneLayer calls on the shared shell pulse (QbzShell.pulseMs) with
// the ribbon frame it stashed on the viz tick. `frame` has no NOTIFY and
// nothing binds it.
import QtQuick
import QtQuick.Window
import com.blitzfc.qbz
RibbonItem {
id: root
// mirrorVertically rule (2026-08-15, verified BOTH ways today): mirror
// on Vulkan/Metal/D3D, NOT on OpenGL — the empirical matrix lives in
// LineBedScene.qml (owner's Vulkan + no mirror = flipped; Mesa GL +
// mirror = flipped). The feedback passes are self-consistent in texture
// space; this only affects the composite.
mirrorVertically: GraphicsInfo.api !== GraphicsInfo.OpenGL
// Called by ShaderSceneLayer on the pulse edge ONLY. `f` is the stashed
// 517-byte frame (QbzShaderScene.ribbonFrame, raw bytes) or null when
// the viz drain published nothing new (player paused); `peak` is the
// pack's energyHi (the real-time ceiling line). The repaint still runs
// on null so the item tracks resizes at the same cadence the sibling
// scenes tick their clocks.
function pulseTick(f, peak) {
if (f !== null)
frame = f
energyHi = peak
update()
}
}
@@ -0,0 +1,431 @@
// ShaderSceneLayer — the immersive GPU shader scenes (block A1 of the
// 2026-08-15 immersive-completion contract, spec 01-shader-scenes-port.md).
// The Qt counterpart of the Slint bottom-most `Image` bound to
// `shader-texture` (ImmersiveView.slint:1293-1300): when
// `QbzShaderScene.scene > 0` this layer REPLACES the atmosphere and all the
// FOCUS/SPLIT panels (their `visible` bindings gain `scene === 0` in
// ImmersiveView), while the chrome (header, player bar, song card) stays on
// top.
//
// Scenes shipped: 1 Plasma (A2 — the feedback QQuickRhiItem, its own
// loader below), 2 Tunnel, 3 Aurora, 4 Spectral Ribbon (A3 — the
// spectrogram QQuickRhiItem + axes overlay), 5 Line Bed (A4), 7 Ambient,
// 8 Tunnel Flow (B1 — the Qt-only Tauri port, feedback QQuickRhiItem fed by
// the Viz16 stream, NOT the shader pack) (6 Liquid Spectrum is parked in
// Slint too). Each ShaderEffect scene
// is its own Component, instantiated ONLY
// while active (the Loader): an invisible ShaderEffect that still ticks
// costs presents, so the inactive scenes don't exist at all.
//
// THE PULSE LAW (00-CONTRACT §3 — non-negotiable): every clock here advances
// on the shared shell pulse (QbzShell.pulseMs) via Connections, gated on
// `active` (visible && immersive open && scene > 0 && window showing — the
// AmbientField.qml:44-47 freeze rule). No Timer, no NumberAnimation, no
// FrameAnimation, no Behavior on data-fed properties anywhere in this file.
//
// THE DATA FLOW (spec 01 §1/§3). The viz drain (viz_qt.rs) derives the audio
// pack HOST-SIDE (bands8 pairing, level, level_smooth EMA, beat/transient
// envelopes, phase with the 4096 wrap, spectral_peak EMA) and publishes it as
// ONE batched `QbzShaderScene.packJson` per tick. This layer STASHES the
// parsed document on publish (nothing binds the stash — no scene dirty) and
// APPLIES it to the uniform properties on the pulse edge (the VizSettle
// pattern), so the shader's uniforms move in the same event-loop turn as
// every other animator and the window presents ONCE per pulse period with a
// scene active. `time` is a LOCAL pulse clock (the Slint `time` is
// seconds-since-start; the pack deliberately does not carry it).
//
// THE TIER GATE (spec 01 §4 — ONE source of truth): the picker rows and the
// `g` key read `QbzShell.shaderScenesAvailable`, seeded from the Rust
// renderer probe (renderer_qt::gpu_tier) — the exact analogue of Slint
// seeding `shader-scenes-available` from the wgpu tier. This layer owns only
// the shader-LOAD half: a ShaderEffect reporting Error latches
// `shaderFailed`, un-instantiates the loader and resets the scene to Off, so
// a load failure never blanks the screen (the ImmersiveAtmosphere.qml:123-128
// rule).
//
// RENDER SIZE (shader_underlay.rs:37-39 parity): the effect renders INLINE
// at the item's physical size (the same conclusion AmbientField reached —
// inline is ONE present per pulse, no FBO double-present), and the resX/resY
// uniforms are the item size × DPR CAPPED at 2560×1440 like the reference's
// offscreen target ceiling.
import QtQuick
import QtQuick.Window
import com.blitzfc.qbz
Item {
id: root
readonly property int scene: QbzShaderScene.scene
// --- The tier gate -------------------------------------------------------
// ONE SOURCE OF TRUTH for the picker/`g` gate: QbzShell.shaderScenesAvailable,
// seeded from the Rust renderer probe (renderer_qt::gpu_tier — the gate
// this feature was waiting on, shell_bridge.rs). This layer adds ONLY the
// shader-LOAD half for its own instantiation safety: a scene effect that
// reports Error latches `shaderFailed`, which un-instantiates the loader
// and hands the background back to the atmosphere (a load failure must
// never blank the screen — the ImmersiveAtmosphere.qml:123-128 rule).
// The picker flag is NEVER fed from here.
property bool shaderFailed: false
readonly property bool available: QbzShell.shaderScenesAvailable
&& !root.shaderFailed
function onShaderError(name, logText) {
console.warn("ShaderSceneLayer: " + name + " shader failed:", logText)
shaderFailed = true
// Hand the background back to the atmosphere instead of showing black.
QbzShaderScene.scene = 0
}
// --- The freeze gate -----------------------------------------------------
// True while the scene is actually on screen. Parent visibility does not
// reach `visible` (that is the LOCAL flag), so the open state is part of
// the predicate explicitly (ImmersiveView is self-gated on open anyway).
readonly property bool windowShowing: root.Window.window
? (root.Window.window.visibility !== Window.Minimized
&& root.Window.window.visibility !== Window.Hidden)
: true
readonly property bool active: root.visible && QbzImmersive.open
&& root.scene > 0 && root.available && root.windowShowing
// --- Render size (see the header) ---------------------------------------
readonly property real dpr: root.Screen.devicePixelRatio
readonly property real resW: Math.min(2560, Math.max(1, Math.round(width * dpr)))
readonly property real resH: Math.min(1440, Math.max(1, Math.round(height * dpr)))
// --- Clocks ---------------------------------------------------------------
// `tickMs` MUST match the pulse period (settings_qt::shell_pulse_ms,
// default 33) — the AmbientField/ImmersiveAtmosphere convention.
readonly property int tickMs: 33
// The scene clock in seconds. Seeded like AmbientField so two launches
// don't open on the same pose; never reset on re-activation (Slint's
// `time` is seconds-since-start, so a scene switch never rewinds either).
property real timeS: Math.random() * 40.0
// The APPLIED pack — the scene uniforms. Written ONLY on the pulse edge
// (see the header); the scene effects bind these. `transientAmp` is the
// pack's `transient` field — `transient` itself is a RESERVED QML keyword
// (qmlcachegen rejects it), so the QML-side identifier changes and the
// shader uniform is named to match.
property real phase: 0
property real beat: 0
property real level: 0
property real levelSmooth: 0
property real transientAmp: 0
property vector4d energyLo: Qt.vector4d(0, 0, 0, 0)
property vector4d energyHi: Qt.vector4d(0, 0, 0, 0)
property vector4d bandsLo: Qt.vector4d(0, 0, 0, 0)
property vector4d bandsHi: Qt.vector4d(0, 0, 0, 0)
// The STASH. Nothing binds it, so the publish-edge write below costs no
// scene dirty — the VizSettle pattern (a second, unsynchronised 30 Hz
// application clock is the exact regression the pulse exists to kill).
property var pendingPack: null
// A4: the Line Bed depth ring stash — same pattern, QByteArray this
// time. The C++ item reads it on the pulse edge via pulseTick().
property var pendingHeights: null
// A3: the Spectral Ribbon frame stash — same pattern again (the 517-byte
// [col][reset][row] blob; layout pinned with ribbon_qt.rs).
property var pendingRibbon: null
// B1: the Tunnel Flow Viz16 stash — the 16-band QList<real> QbzViz
// publishes every viz tick while immersive is open. Same zero-dirty
// pattern: TunnelFlowScene.qml runs its smoothing/kick/phase
// accumulators from the pulse edge, never from this notify.
property var pendingBars: null
// The pack handed to the RhiItem scenes (A2 Plasma; A4 Line Bed takes
// pendingHeights instead). Built on the pulse edge from the APPLIED
// properties — one JS object per pulse, never bound.
function rhiPack() {
return {
"time": root.timeS,
"beat": root.beat,
"level": root.level,
"levelSmooth": root.levelSmooth,
"energyLo": root.energyLo,
"energyHi": root.energyHi,
"primary": QbzShell.ambientPrimary,
"secondary": QbzShell.ambientSecondary,
"accent": QbzShell.ambientAccent
}
}
Connections {
target: QbzShaderScene
function onPackJsonChanged() {
try {
root.pendingPack = JSON.parse(QbzShaderScene.packJson)
} catch (e) {
// A malformed pack keeps the previous uniforms.
}
}
function onLinebedHeightsChanged() {
// Stash only (no binding consumes this — zero scene dirty).
root.pendingHeights = QbzShaderScene.linebedHeights
}
function onRibbonFrameChanged() {
// Stash only (same zero-dirty rule as the ring stash).
root.pendingRibbon = QbzShaderScene.ribbonFrame
}
function onSceneChanged() {
// A4/A3 publish gates: the viz drain only pushes/publishes the
// scene feeds while their scene is actually on screen (the Rust
// side reads an atomic; the drain thread cannot read the
// QObject property). Boot order note: this handler also covers
// every later write — menu rows, cycleScene, the open-reset,
// the shader-error latch below.
QbzShaderScene.setLinebedActive(QbzShaderScene.scene === 5)
QbzShaderScene.setRibbonActive(QbzShaderScene.scene === 4)
}
}
Connections {
target: QbzViz
function onBarsChanged() {
// B1: stash only (no binding consumes this — zero scene dirty,
// the pendingPack pattern). Tunnel Flow reads the Viz16 stream,
// not the shader pack.
root.pendingBars = QbzViz.bars
}
}
Connections {
target: QbzShell
function onPulseMsChanged() {
if (!root.active)
return
root.timeS += root.tickMs / 1000.0
// A4: Line Bed — apply the stashed ring and repaint ONCE per
// pulse (deliberately before the pendingPack early-return: the
// item ticks at pulse rate while active even when the audio
// feed is parked, exactly like timeS advances for the
// ShaderEffect scenes).
if (lineBedLoader.item) {
lineBedLoader.item.pulseTick(root.pendingHeights)
root.pendingHeights = null
}
// B1: Tunnel Flow — same pulse-edge repaint (the linebed
// cadence comment above covers this too); the wrapper computes
// the Viz16 smoothing/kick/phase accumulators itself.
if (tunnelFlowLoader.item) {
tunnelFlowLoader.item.pulseTick(root.timeS, root.pendingBars)
root.pendingBars = null
}
// A2: Plasma — same pulse-edge repaint; the pack rides the
// applied properties (no 200 KB ring, so no stash/gate).
if (plasmaLoader.item)
plasmaLoader.item.pulseTick(root.rhiPack())
// A3: Spectral Ribbon — apply the stashed frame + the ceiling
// EMA and repaint ONCE per pulse (the linebed cadence comment
// above covers this too).
if (ribbonLoader.item) {
ribbonLoader.item.pulseTick(root.pendingRibbon, root.energyHi)
root.pendingRibbon = null
}
var p = root.pendingPack
if (p === null)
return
root.pendingPack = null
root.phase = p.phase
root.beat = p.beat
root.level = p.level
root.levelSmooth = p.levelSmooth
root.transientAmp = p.transient
root.energyLo = Qt.vector4d(p.energyLo[0], p.energyLo[1], p.energyLo[2], p.energyLo[3])
root.energyHi = Qt.vector4d(p.energyHi[0], p.energyHi[1], p.energyHi[2], p.energyHi[3])
root.bandsLo = Qt.vector4d(p.bandsLo[0], p.bandsLo[1], p.bandsLo[2], p.bandsLo[3])
root.bandsHi = Qt.vector4d(p.bandsHi[0], p.bandsHi[1], p.bandsHi[2], p.bandsHi[3])
}
}
// --- The scenes -------------------------------------------------------------
// ONLY the active scene is instantiated (see the header). The uniforms map
// 1:1 to the spec 01 §1 block fields, matched BY NAME against the shader's
// reflection data — `primary/secondary/accent` ride the shell's ambient
// palette (the same ambient_qt source the Slint side feeds
// shader_underlay::set_palette with), `time` is the local clock, and the
// rest come from the applied pack.
Component {
id: tunnelScene
ShaderEffect {
blending: false // opaque output (alpha = qt_Opacity = 1)
property color primary: QbzShell.ambientPrimary
property color secondary: QbzShell.ambientSecondary
property color accent: QbzShell.ambientAccent
property vector4d energyLo: root.energyLo
property vector4d energyHi: root.energyHi
property vector4d bandsLo: root.bandsLo
property vector4d bandsHi: root.bandsHi
property real time: root.timeS
property real phase: root.phase
property real beat: root.beat
property real level: root.level
property real resX: root.resW
property real resY: root.resH
property real levelSmooth: root.levelSmooth
property real transientAmp: root.transientAmp
onStatusChanged: {
if (status === ShaderEffect.Error)
root.onShaderError("tunnel", log)
}
fragmentShader: "../assets/shaders/tunnel.frag.qsb"
// Paired vertex stage (Qt 6.11's built-in default emits no
// qt_TexCoord0). PAIRED, not shared: the GL program link requires
// both stages to declare the SAME uniform block (see
// scene_pack.vert), so tunnel/aurora no longer ride spectrum.vert.
vertexShader: "../assets/shaders/scene_pack.vert.qsb"
}
}
Component {
id: auroraScene
ShaderEffect {
blending: false
property color primary: QbzShell.ambientPrimary
property color secondary: QbzShell.ambientSecondary
property color accent: QbzShell.ambientAccent
property vector4d energyLo: root.energyLo
property vector4d energyHi: root.energyHi
property vector4d bandsLo: root.bandsLo
property vector4d bandsHi: root.bandsHi
property real time: root.timeS
property real phase: root.phase
property real beat: root.beat
property real level: root.level
property real resX: root.resW
property real resY: root.resH
property real levelSmooth: root.levelSmooth
property real transientAmp: root.transientAmp
onStatusChanged: {
if (status === ShaderEffect.Error)
root.onShaderError("aurora", log)
}
fragmentShader: "../assets/shaders/aurora.frag.qsb"
vertexShader: "../assets/shaders/scene_pack.vert.qsb"
}
}
Component {
id: ambientScene
// Ambient-as-scene (mode 7, spec 01 §2.6): the ALREADY-PORTED
// ambient.frag (the app-wide background's GPU arm) mounted at the
// immersive underlay slot with the scene uniform naming. Unlike the
// app background this mount gets the audio breathe (levelSmooth from
// the pack — the Slint ambient scene breathes too) and NO legibility
// dim (dim is a shell-background scrim; the reference's ambient.wgsl
// has no such term).
ShaderEffect {
blending: false
property color primary: QbzShell.ambientPrimary
property color secondary: QbzShell.ambientSecondary
property color accent: QbzShell.ambientAccent
property real time: root.timeS
property real levelSmooth: root.levelSmooth
property real resX: root.resW
property real resY: root.resH
property real dim: 0.0
onStatusChanged: {
if (status === ShaderEffect.Error)
root.onShaderError("ambient", log)
}
fragmentShader: "../assets/shaders/ambient.frag.qsb"
vertexShader: "../assets/shaders/ambient.vert.qsb"
}
}
Loader {
anchors.fill: parent
active: root.active
sourceComponent: root.scene === 2 ? tunnelScene
: root.scene === 3 ? auroraScene
: root.scene === 7 ? ambientScene
: null
}
// A4: the Line Bed scene (mode 5) — the QQuickRhiItem, mounted via its
// QML wrapper. Its OWN loader: the C++ item is not a ShaderEffect and
// shares nothing with the sourceComponent switch above. The `active`
// gate IS the pulse-law gate (visible && immersive open && scene === 5
// && tier — root.active), so the item exists only while it is on
// screen; every repaint inside it is driven by the pulse handler above.
Component {
id: linebedScene
LineBedScene {
}
}
Loader {
id: lineBedLoader
anchors.fill: parent
active: root.active && root.scene === 5
sourceComponent: linebedScene
}
// A2: the Plasma scene (mode 1) — the feedback-fluid QQuickRhiItem,
// same mount idiom as Line Bed (its own loader, gated on the pulse-law
// `active`).
Component {
id: plasmaScene
PlasmaScene {
}
}
Loader {
id: plasmaLoader
anchors.fill: parent
active: root.active && root.scene === 1
sourceComponent: plasmaScene
}
// A3: the Spectral Ribbon scene (mode 4) — the spectrogram
// QQuickRhiItem PLUS its green-axes overlay (the Slint
// ImmersiveSpectralOverlay, ImmersiveView.slint:1304-1309), same mount
// idiom as Line Bed.
Component {
id: ribbonScene
Item {
// The pulse handler calls `ribbonLoader.item.pulseTick(...)` —
// the item is THIS wrapper, so the tick must be forwarded to the
// RibbonItem inside (a plain Item has no pulseTick; the direct
// call on the wrapper threw TypeError every pulse and the
// spectrogram never received a frame — owner smoke 2026-08-15).
function pulseTick(f, peak) {
ribbonItem.pulseTick(f, peak)
}
RibbonScene {
id: ribbonItem
anchors.fill: parent
}
SpectralOverlay {
anchors.fill: parent
}
}
}
Loader {
id: ribbonLoader
anchors.fill: parent
active: root.active && root.scene === 4
sourceComponent: ribbonScene
}
// B1: the Tunnel Flow scene (mode 8, Qt-only — spec 02) — the feedback
// QQuickRhiItem, same mount idiom as Plasma. The `active` gate IS the
// pulse-law gate; the item exists only while on screen. The black base
// is inherent (the scene owns the background while active) and the
// 240 ms fade-in lives in the wrapper (a transient one-shot, allowed).
Component {
id: tunnelFlowScene
TunnelFlowScene {
}
}
Loader {
id: tunnelFlowLoader
anchors.fill: parent
active: root.active && root.scene === 8
sourceComponent: tunnelFlowScene
}
}
@@ -0,0 +1,114 @@
// Spectral Ribbon overlay (immersive scene mode 4) — green axes + labels +
// the stream header, drawn OVER the RibbonItem's GPU spectrogram. QML port
// of qbz-ui's ImmersiveSpectralOverlay.slint (B-block idiom: everything is
// positioned as FRACTIONS of the viewport so the axes grow/shrink with the
// window). The plot rectangle MUST match spectral_ribbon.frag
// (PLOT_X0..Y1); the overlay fractions are the Slint TOP-DOWN ones
// (0.070/0.780 = 1 - the shader's 0.930/0.220).
//
// No MouseArea anywhere — input passes through to the player bar below
// (the Slint overlay's "plain Rectangle, no TouchArea" rule).
import QtQuick
import com.blitzfc.qbz
Item {
id: root
anchors.fill: parent
// Plot rect — the Slint overlay's fractions (see the header).
readonly property real plotX0: width * 0.055
readonly property real plotX1: width * 0.970
readonly property real plotY0: height * 0.070
readonly property real plotY1: height * 0.780
readonly property real plotW: plotX1 - plotX0
readonly property real plotH: plotY1 - plotY0
readonly property color axis: "#5fb87a"
// Nyquist in kHz (delivered rate / 2). Falls back to 22.05 (44.1k)
// when nothing is reported yet (npEffRateHz 0).
readonly property real nyqKhz: QbzPlayer.npEffRateHz > 0
? QbzPlayer.npEffRateHz / 2000.0
: 22.05
readonly property int dur: QbzPlayer.npDurationSecs
// --- Stream header (top center, green box) ---------------------------
Rectangle {
// The immersive search cortinilla lives at the same height in the
// header row — while the search is open it wins the space (owner
// smoke 2026-08-15: they overlapped).
visible: !QbzImmersive.immSearchOpen
x: (root.width - width) / 2
y: root.height * 0.045
width: hdr.implicitWidth + 28
height: 22
radius: 5
border.width: 1
border.color: root.axis
color: "#e60a140d"
Text {
id: hdr
anchors.centerIn: parent
text: "Stream 1/1: Audio Stream, " + QbzPlayer.npEffRateHz + " Hz, "
+ QbzPlayer.npEffBits + " bits, FFT:4096, Bands:512"
color: root.axis
font.pixelSize: 12
}
}
// --- Axis frame (L-shape) --------------------------------------------
Rectangle { // vertical (frequency)
x: root.plotX0
y: root.plotY0
width: 1
height: root.plotH
color: root.axis
}
Rectangle { // horizontal (time)
x: root.plotX0
y: root.plotY1
width: root.plotW
height: 1
color: root.axis
}
// --- Frequency axis labels (Y, left) — 0 .. Nyquist ------------------
Repeater {
model: [0.0, 0.25, 0.5, 0.75, 1.0]
Text {
required property real modelData
x: root.plotX0 - 46
y: root.plotY1 - modelData * root.plotH - height / 2
width: 40
horizontalAlignment: Text.AlignRight
text: Math.round(root.nyqKhz * modelData) + "k"
color: root.axis
font.pixelSize: 11
}
}
// --- Time axis labels (X, bottom) — 30 s ticks -----------------------
Repeater {
model: 31
Text {
required property int index
visible: root.dur > 0 && (index * 30) <= root.dur
x: root.plotX0 + (root.dur > 0 ? root.plotW * ((index * 30) / root.dur) : 0) - width / 2
y: root.plotY1 + 6
text: Math.floor((index * 30) / 60) + ":"
+ ((index * 30) % 60 < 10 ? "0" : "") + ((index * 30) % 60)
color: root.axis
font.pixelSize: 10
}
}
// Final duration marker at the right edge.
Text {
visible: root.dur > 0
x: root.plotX1 - width / 2
y: root.plotY1 + 6
text: Math.floor(root.dur / 60) + ":"
+ (root.dur % 60 < 10 ? "0" : "") + (root.dur % 60)
color: root.axis
font.pixelSize: 10
}
}
+14 -1
View File
@@ -89,6 +89,19 @@ Rectangle {
readonly property real artSize: Math.max(160,
Math.min(Math.min(root.height * 0.45, root.width * 0.5), 360))
// D2 (contract 04 §4): size-aware large art — this card draws up to
// 360 CSS px, past what the thumbnail-tier small feed covers. Same
// bucketed request + fallback binding as StaticPanel/AlbumReactivePanel.
readonly property string artSource: QbzPlayer.npArtworkPathLarge !== ""
? QbzPlayer.npArtworkPathLarge : QbzPlayer.npArtworkPath
function requestArtSize() {
if (root.visible)
QbzPlayer.requestNpArtworkSize(Math.round(root.artSize))
}
onArtSizeChanged: requestArtSize()
onVisibleChanged: requestArtSize()
Component.onCompleted: requestArtSize()
Item {
anchors.fill: parent
anchors.topMargin: 70
@@ -122,7 +135,7 @@ Rectangle {
x: (parent.width - width) / 2
y: (parent.height - height) / 2
radius: 8
source: QbzPlayer.npArtworkPath
source: root.artSource
}
}
+23 -2
View File
@@ -28,6 +28,27 @@ import "../theme"
Item {
id: root
// D2 (contract 04 §4): size-aware large art. `artSource` prefers the
// size-resolved large feed and falls back to the small one while it
// resolves (the Slint `artwork-large : artwork` pattern); the probe reads
// the SAME source so the native cap tracks the image actually shown.
readonly property string artSource: QbzPlayer.npArtworkPathLarge !== ""
? QbzPlayer.npArtworkPathLarge : QbzPlayer.npArtworkPath
// The baseArt slot expression WITHOUT the native cap — the cap stays the
// final upscale safety; the request must reflect the SLOT so the feed can
// serve a variant big enough for it.
readonly property real artSlot: Math.max(180,
Math.min(Math.min(root.height - 364, root.width * 0.62), 640))
// Bucketed in Rust (one re-resolve per variant tier crossed, none per
// pixel); gated on visible so a hidden panel writes nothing (pulse law).
function requestArtSize() {
if (root.visible)
QbzPlayer.requestNpArtworkSize(Math.round(root.artSlot))
}
onArtSlotChanged: requestArtSize()
onVisibleChanged: requestArtSize()
Component.onCompleted: requestArtSize()
// Native source resolution — cap so the cover is never UPSCALED beyond
// its own size (:46-49). Hidden probe on the same file:// cache path
// (shared image cache; see AlbumReactivePanel.qml). Empty art -> 0 ->
@@ -35,7 +56,7 @@ Item {
Image {
id: artProbe
visible: false
source: QbzPlayer.npArtworkPath
source: root.artSource
}
readonly property real srcNative: artProbe.status === Image.Ready
? artProbe.implicitWidth : 0
@@ -88,7 +109,7 @@ Item {
x: (parent.width - width) / 2
y: (parent.height - height) / 2
radius: 8
source: QbzPlayer.npArtworkPath
source: root.artSource
}
}
@@ -0,0 +1,135 @@
// Tunnel Flow (immersive shader scene, mode 8 — Qt-only) — the QML wrapper
// for the C++ `TunnelFlowItem` (cxx/tunnelflow_item.*, the feedback-tunnel
// QQuickRhiItem). Block B1 of the 2026-08-15 immersive-completion contract
// (spec 02-tauri-tunnel-port.md): the legacy Tauri Canvas2D panel
// (TunnelFlowPanel.svelte) rewritten as qml/assets/shaders/tunnel_flow.frag.
//
// Its own file (the PlasmaScene.qml idiom) so the RHI item's contract is one
// screen of QML — and so the C++ type name only has to resolve when this
// file compiles (the Loader in ShaderSceneLayer.qml activates only while
// `root.active && scene === 8`).
//
// THE PULSE LAW: the item repaints ONLY from `pulseTick()`, which
// ShaderSceneLayer calls on the shared shell pulse (QbzShell.pulseMs) with
// the local scene clock and the Viz16 bars it stashed on the viz tick. The
// properties have no NOTIFY and nothing binds them.
//
// THE AUDIO STATE LIVES HERE (spec 02 §2): Tunnel Flow consumes the 16-band
// Viz16 stream, NOT the shader pack. This wrapper ports the Tauri frontend
// accumulators verbatim and runs them ONCE per pulse:
// - smoothing s = s*0.72 + new*0.28 per band (SMOOTHING = 0.72);
// - bass = mean(bands 0..3), mid = mean(4..9), high = mean(10..15);
// - kick detector: bassDelta > 0.05 || highDelta > 0.05 || bass > 0.7 ->
// kickPulse = clamp01(0.24 + bass*0.52 + high*0.34 + max(0,bassDelta)*1.8),
// then kickPulse *= 0.9 per frame;
// - the TAURI phase accumulator phase += 0.012 + bass*0.026 + high*0.014 +
// kickPulse*0.018 — deliberately SEPARATE from the pack's phase.
// The reference detects the kick on the 30 Hz viz event and decays per
// requestAnimationFrame; here both run on the ~30 Hz pulse — the same
// cadence, one accumulator site.
//
// THE PALETTE rides QbzShaderScene.tunnelPaletteJson (the tunnelflow_qt.rs
// port of extractLinePaletteFromArtwork, published per track): stashed on
// the notify (zero-dirty — nothing binds the stash), applied on the pulse
// edge like every other uniform.
import QtQuick
import QtQuick.Window
import com.blitzfc.qbz
TunnelFlowItem {
id: root
// mirrorVertically rule (2026-08-15, verified BOTH ways today): mirror
// on Vulkan/Metal/D3D, NOT on OpenGL — the empirical matrix lives in
// LineBedScene.qml (owner's Vulkan + no mirror = flipped; Mesa GL +
// mirror = flipped). The feedback passes are self-consistent in texture
// space; this only affects the composite.
mirrorVertically: GraphicsInfo.api !== GraphicsInfo.OpenGL
// Fade-in 240 ms on activation (spec 02 §5; TunnelFlowPanel.svelte
// :1005-1024) — a TRANSIENT one-shot, not a continuous animator, so the
// pulse law allows it.
opacity: 0
Component.onCompleted: fadeIn.start()
NumberAnimation {
id: fadeIn
target: root
property: "opacity"
from: 0
to: 1
duration: 240
}
// --- The JS audio accumulators (see the header) -------------------------
property var smooth: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
property real tfPhase: 0
property real kickPulse: 0
property real prevBass: 0
property real prevHigh: 0
// The palette stash (zero-dirty, the pendingPack pattern).
property var paletteStash: null
Connections {
target: QbzShaderScene
function onTunnelPaletteJsonChanged() {
try {
root.paletteStash = JSON.parse(QbzShaderScene.tunnelPaletteJson)
} catch (e) {
// A malformed palette keeps the previous colors.
}
}
}
// Called by ShaderSceneLayer on the pulse edge ONLY. `timeS` is the
// layer's local pulse clock (seconds); `bars` is the stashed Viz16 array
// or null when the viz drain published nothing new (player paused) — the
// repaint still runs so the feedback decay carries the motion (the idle
// drift: phase advances 0.012/pulse minimum, spec 02 §6).
function pulseTick(timeS, bars) {
var s = root.smooth
if (bars !== null && bars.length >= 16) {
for (var i = 0; i < 16; i++)
s[i] = s[i] * 0.72 + bars[i] * 0.28
// The kick detector fires on FRESH viz data only (the reference
// runs it in the viz-event handler): with the feed parked the
// deltas are stale and a held bass > 0.7 would retrigger forever.
var bass = (s[0] + s[1] + s[2] + s[3]) / 4
var high = (s[10] + s[11] + s[12] + s[13] + s[14] + s[15]) / 6
var bassDelta = bass - root.prevBass
var highDelta = high - root.prevHigh
root.prevBass = bass
root.prevHigh = high
if (bassDelta > 0.05 || highDelta > 0.05 || bass > 0.7) {
root.kickPulse = Math.max(0, Math.min(1,
0.24 + bass * 0.52 + high * 0.34 + Math.max(0, bassDelta) * 1.8))
}
}
var bass = (s[0] + s[1] + s[2] + s[3]) / 4
var mid = (s[4] + s[5] + s[6] + s[7] + s[8] + s[9]) / 6
var high = (s[10] + s[11] + s[12] + s[13] + s[14] + s[15]) / 6
// The palette, applied on the pulse edge like the uniforms.
var pal = root.paletteStash
if (pal !== null && pal.length >= 4) {
palette0 = pal[0]
palette1 = pal[1]
palette2 = pal[2]
palette3 = pal[3]
}
// Uniforms use the CURRENT phase/kick (the reference draws, then
// advances the accumulators at the end of render()).
time = timeS
phase = root.tfPhase
root.bass = bass
root.mid = mid
root.high = high
kick = root.kickPulse
root.tfPhase += 0.012 + bass * 0.026 + high * 0.014 + root.kickPulse * 0.018
root.kickPulse *= 0.9
update()
}
}
+4 -4
View File
@@ -192,10 +192,10 @@ Item {
}
fragmentShader: "../assets/shaders/ambient.frag.qsb"
// Shared default-equivalent vertex stage — Qt 6.11's built-in default
// emits no qt_TexCoord0, so the program link fails without an explicit
// one (the same file SpectrumBand uses).
vertexShader: "../assets/shaders/spectrum.vert.qsb"
// Paired vertex stage — Qt 6.11's built-in default emits no
// qt_TexCoord0, and the GL link requires both stages to declare the
// SAME uniform block (see ambient.vert / scene_pack.vert).
vertexShader: "../assets/shaders/ambient.vert.qsb"
}
// --- CPU fallback arm ---------------------------------------------------
+10 -12
View File
@@ -197,10 +197,10 @@ Rectangle {
// .qsb baked from qml/assets/shaders/spectrum_bars.frag — see the header.
fragmentShader: "../assets/shaders/spectrum_bars.frag.qsb"
// Shared default-equivalent vertex stage (Qt 6.11's
// built-in default emits no qt_TexCoord0, so the link
// fails without an explicit one).
vertexShader: "../assets/shaders/spectrum.vert.qsb"
// Paired vertex stage (Qt 6.11's built-in default emits no
// qt_TexCoord0); the GL link requires both stages to declare
// the SAME uniform block (see spectrum_bars.vert).
vertexShader: "../assets/shaders/spectrum_bars.vert.qsb"
}
// FALLBACK ARM — the pre-F3 delegates, verbatim. Geometry: x =
@@ -329,10 +329,9 @@ Rectangle {
// .qsb baked from qml/assets/shaders/spectrum_wave.frag — see the header.
fragmentShader: "../assets/shaders/spectrum_wave.frag.qsb"
// Shared default-equivalent vertex stage (Qt 6.11's
// built-in default emits no qt_TexCoord0, so the link
// fails without an explicit one).
vertexShader: "../assets/shaders/spectrum.vert.qsb"
// Paired vertex stage — same uniform block in both stages
// (the GL link requires it; see spectrum_wave.vert).
vertexShader: "../assets/shaders/spectrum_wave.vert.qsb"
}
// FALLBACK ARM — the pre-F3 delegates, verbatim. Geometry: x =
@@ -403,10 +402,9 @@ Rectangle {
// .qsb baked from qml/assets/shaders/spectrum_energy.frag — see the header.
fragmentShader: "../assets/shaders/spectrum_energy.frag.qsb"
// Shared default-equivalent vertex stage (Qt 6.11's
// built-in default emits no qt_TexCoord0, so the link
// fails without an explicit one).
vertexShader: "../assets/shaders/spectrum.vert.qsb"
// Paired vertex stage — same uniform block in both stages
// (the GL link requires it; see spectrum_energy.vert).
vertexShader: "../assets/shaders/spectrum_energy.vert.qsb"
}
// FALLBACK ARM — the pre-F3 delegates, verbatim. Geometry: x =
+17 -2
View File
@@ -385,12 +385,24 @@ pub fn update_for_artwork(artwork_url: &str) {
);
let glow = glow_hex_qt(glow_color(&tiny8));
let atmosphere = crate::atmosphere_qt::for_cover_blocking(&path);
Some((hex(primary), hex(secondary), hex(accent), glow, atmosphere))
// B1: the SAME decode feeds the Tunnel Flow palette — the Tauri
// extractLinePaletteFromArtwork port (tunnelflow_qt.rs) at its
// 36x36 sample size, off the Qt thread like the triad.
let tiny36 = image::imageops::resize(
&rgba,
crate::tunnelflow_qt::SAMPLE_SIZE,
crate::tunnelflow_qt::SAMPLE_SIZE,
image::imageops::FilterType::Triangle,
);
let tunnel = crate::tunnelflow_qt::line_palette_json(
&crate::tunnelflow_qt::line_palette(&tiny36),
);
Some((hex(primary), hex(secondary), hex(accent), glow, atmosphere, tunnel))
})
.await
.ok()
.flatten();
if let Some((primary, secondary, accent, glow, atmosphere)) = triad {
if let Some((primary, secondary, accent, glow, atmosphere, tunnel)) = triad {
log::info!("[qbz-qt] ambient palette: {primary} / {secondary} / {accent}");
crate::shell_bridge::ui(move |mut b| {
b.as_mut().set_ambient_primary(QString::from(primary.as_str()));
@@ -407,6 +419,9 @@ pub fn update_for_artwork(artwork_url: &str) {
x.as_mut().set_atmosphere_url(QString::from(url.as_str()));
}
});
// B1: the Tunnel Flow palette rides the same success-only rule
// (one batched QString on QbzShaderScene).
crate::shader_scene_bridge::publish_tunnel_palette(tunnel);
}
});
}
+32 -6
View File
@@ -159,9 +159,11 @@ impl Default for QbzImmersiveRust {
fn default() -> Self {
Self {
open: false,
view_mode: 0,
mode: 0,
split_panel: 0,
// Pre-first-open construction default — the same Split > Lyrics
// the remember-restore falls back to (see the DEFAULT_* consts).
view_mode: DEFAULT_VIEW_MODE,
mode: DEFAULT_MODE,
split_panel: DEFAULT_SPLIT_PANEL,
glow_color: QString::from(GLOW_DEFAULT_QT),
atmosphere_url: QString::from(""),
imm_search_open: false,
@@ -213,6 +215,16 @@ pub(crate) fn close() {
ui(|imm| imm.set_open(false));
}
/// Owner ruling 2026-08-15: "cuando no hay una escena activa por default
/// debemos caer siempre en Split>Lyrics" — with NOTHING remembered, a fresh
/// immersive open lands on viewMode=1 (SPLIT), splitPanel=0 (Lyrics), never
/// on a FOCUS panel. These are the FALLBACKS of the remember-last restore
/// (and the bridge's construction default): a saved triple still wins, so
/// existing users keep their remembered view.
const DEFAULT_VIEW_MODE: i32 = 1; // SPLIT
const DEFAULT_MODE: i32 = 0; // (meaningless under SPLIT; FOCUS AlbumReactive)
const DEFAULT_SPLIT_PANEL: i32 = 0; // Lyrics
/// §3.1 pinned map: a pinned default always lands on `view_mode=0` + the
/// matching FOCUS `mode` (never WaveBed). `None` = "remember"/unknown — the
/// caller restores the persisted triple / does nothing respectively.
@@ -272,9 +284,9 @@ fn apply_open(mut this: Pin<&mut QbzImmersive>, value: bool) {
// string writes would poison its whole-document load. (The
// contract's "pref_str i32-parse" would read NEITHER app's
// numbers; pref_i32 is the compatible reader — delivery notes.)
let vm = crate::settings_qt::pref_i32("immersive_last_view_mode", 0);
let m = crate::settings_qt::pref_i32("immersive_last_mode", 0);
let sp = crate::settings_qt::pref_i32("immersive_last_split_panel", 0);
let vm = crate::settings_qt::pref_i32("immersive_last_view_mode", DEFAULT_VIEW_MODE);
let m = crate::settings_qt::pref_i32("immersive_last_mode", DEFAULT_MODE);
let sp = crate::settings_qt::pref_i32("immersive_last_split_panel", DEFAULT_SPLIT_PANEL);
this.as_mut().set_view_mode(vm);
this.as_mut().set_mode(m);
this.as_mut().set_split_panel(sp);
@@ -285,6 +297,10 @@ fn apply_open(mut this: Pin<&mut QbzImmersive>, value: bool) {
}
// Unknown key: Slint's `_ => {}` — leave the current view alone.
crate::viz_qt::immersive_opened();
// Shader scenes (block A1): entering immersive force-resets the
// scene to Off — parity main.rs:10300-10301, a documented no-op in
// v1 (the scenes were parked), REAL now that QbzShaderScene exists.
crate::shader_scene_bridge::reset_on_immersive_open();
// §3.4 open-edge hygiene: a stale-true desktop cortinillaOpen is
// possible in theory — close it deterministically (the Rust
// equivalent of QbzBridge.cortinillaDismiss, bridge.rs:359-361; the
@@ -399,6 +415,16 @@ mod tests {
assert_eq!(pinned_view("queue"), Some((0, 5)));
}
#[test]
fn fresh_open_defaults_to_split_lyrics() {
// Owner ruling 2026-08-15: with no remembered triple, the
// remember-restore fallbacks AND the bridge construction default land
// on viewMode=1 (SPLIT), splitPanel=0 (Lyrics) — never a FOCUS panel.
assert_eq!((DEFAULT_VIEW_MODE, DEFAULT_MODE, DEFAULT_SPLIT_PANEL), (1, 0, 0));
assert_eq!(QbzImmersiveRust::default().view_mode, 1);
assert_eq!(QbzImmersiveRust::default().split_panel, 0);
}
#[test]
fn remember_and_unknown_keys_are_not_pinned() {
assert_eq!(pinned_view("remember"), None);
+307
View File
@@ -0,0 +1,307 @@
//! Line Bed (shader scene, mode 5) — the CPU half. Block A4 of the
//! 2026-08-15 immersive-completion contract (spec
//! `01-shader-scenes-port.md` §2.5).
//!
//! Line-faithful port of the Slint `LineBedState` +
//! `reshape_512_to_256`/`apply_average`/`smooth3`
//! (`crates/qbz/src/shader_underlay.rs:149-175,193-267`): a 512-band
//! receive-IIR accumulator, the Tauri LinebedPanel reshaping chain
//! (freq-warp bin map bins 4-460 → peak-preserving smoothing → low-end
//! roll-off → 3-point box → gamma + soft clip, heights in [0.1, 84]), and a
//! 200-deep ring with row 0 = newest.
//!
//! The GPU half is the C++ `LineBedItem` (`cxx/linebed_item.{h,cpp}`, the
//! project's first `QQuickRhiItem`), which receives the ring as raw f32
//! bytes and samples it in the VERTEX stage (the `line_bed.wgsl` port).
//!
//! THE DATA FLOW (pulse law, 00-CONTRACT §3): the viz drain feeds `push()`
//! with the SAME latched `Spectral512` frame the A1 shader pack already
//! consumes (`viz_qt.rs` — the stream is latched under MARSHAL_ALL but
//! deliberately NOT marshalled to QML; 512 floats x 30 Hz of QList churn is
//! what the pack exists to avoid), and publishes the ready 256x200 ring ONCE
//! per tick as one `QByteArray` property on `QbzShaderScene`
//! (`linebedHeights`, one notify per tick — the pack's batching pattern).
//! Both the push and the publish are gated on the scene actually being on
//! screen (`shader_scene_bridge::linebed_active`, mirrored from QML):
//! 200 KB x 30 Hz for a scene nobody is looking at is exactly what the
//! pulse law forbids. The state PERSISTS across scene switches (Slint's
//! thread-local does the same) — a re-opened Line Bed resumes its history
//! instead of restarting flat.
//!
//! This module touches NONE of the audio backend: it is pure math over the
//! read-only latched cell.
/// Line-bed lattice: 200 depth lines x 256 frequency points (matches the
/// Tauri LinebedPanel NUM_LINES / VISUAL_BANDS and the Slint consts,
/// `shader_underlay.rs:47-50`). The C++ item and the shaders pin the same
/// numbers.
pub(crate) const LINEBED_LINES: usize = 200;
pub(crate) const LINEBED_BANDS: usize = 256;
/// Backend FFT bands per spectral frame (the `Spectral512` stream).
const SPECTRO_BANDS: usize = 512;
/// The reshaping + depth ring. Lives on the viz DRAIN thread as a plain/// local (the `ShaderPackState` pattern): per-tick state, never shared,
/// never locked. `Default` = the reference's `new()`: zeroed accumulator,
/// zeroed ring (a fresh bed starts flat and fills over the next 200
/// spectral frames).
#[derive(Clone)]
pub(crate) struct LineBedState {
/// 512-band receive-IIR accumulator.
smoothed: Vec<f32>,
/// LINEBED_LINES*LINEBED_BANDS, depth-ordered (row 0 = newest).
ring: Vec<f32>,
}
impl Default for LineBedState {
fn default() -> Self {
Self {
smoothed: vec![0.0; SPECTRO_BANDS],
ring: vec![0.0; LINEBED_LINES * LINEBED_BANDS],
}
}
}
impl LineBedState {
/// Receive-IIR a 512-band frame, reshape to 256 heights, push at the
/// near row (shader_underlay.rs:163-174 — verbatim, including the
/// 0.03/0.97 coefficient order: the accumulator keeps 3% and takes 97%
/// of the new frame).
pub(crate) fn push(&mut self, bins: &[f32]) {
let n = self.smoothed.len().min(bins.len());
for i in 0..n {
self.smoothed[i] = self.smoothed[i] * 0.03 + bins[i] * 0.97;
}
let row = reshape_512_to_256(&self.smoothed);
// Shift every row one slot deeper, then write the newest at row 0.
self.ring
.copy_within(0..(LINEBED_LINES - 1) * LINEBED_BANDS, LINEBED_BANDS);
self.ring[0..LINEBED_BANDS].copy_from_slice(&row);
}
/// The ready ring as raw f32 bytes (256x200, R32F texture layout: row =
/// depth line, column = band — the VS reads texel (band, line)).
/// Soundness: plain `f32` storage, no padding holes — the same cast the
/// reference does for its `write_texture` (`f32_bytes`,
/// shader_underlay.rs:145-147).
pub(crate) fn ring_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(
self.ring.as_ptr() as *const u8,
std::mem::size_of_val(self.ring.as_slice()),
)
}
}
}
/// 512 backend bands → 256 line heights in [0.1, 84] — Tauri's
/// LinebedPanel chain (the backend bands are intentionally flat; this is
/// what makes the ridges): frequency-warp bin map → peak-preserving
/// smoothing → low-end tail roll-off → 3-point box → per-band gamma + soft
/// clip. Verbatim port of `shader_underlay.rs:193-231` (which is itself the
/// Tauri chain).
fn reshape_512_to_256(data: &[f32]) -> [f32; 256] {
let mut vis = [0.0f32; 256];
for i in 0..256 {
let seg_start = (i as f32 / 256.0).powf(1.32);
let seg_end = ((i + 1) as f32 / 256.0).powf(1.32);
let s = 4.0 + (460.0 - 4.0) * seg_start;
let e = 4.0 + (460.0 - 4.0) * seg_end;
let lower = (s.floor() as usize).max(4);
let upper = (e.ceil() as usize).min(460);
let (mut sum, mut peak, mut cnt) = (0.0f32, 0.0f32, 0u32);
let mut j = lower;
while j <= upper && j < data.len() {
sum += data[j];
if data[j] > peak {
peak = data[j];
}
cnt += 1;
j += 1;
}
let avg = if cnt > 0 { sum / cnt as f32 } else { 0.0 };
vis[i] = (avg * 0.52 + peak * 0.48) * 770.0;
}
apply_average(&mut vis);
// Low-end tail roll-off (first 7 bins).
for i in 0..7usize {
vis[i] *= 0.013_334_120_966_221_101 * ((i + 1) as f32).powf(1.6) + 0.7;
}
smooth3(&mut vis);
// Per-band gamma + soft clip + cap → [0.1, 84].
for i in 0..256 {
let frac = i as f32 / 255.0;
let exp = 1.35 + (0.9 - 1.35) * frac * frac;
let norm = (vis[i] / 770.0).max(0.0);
let shaped = norm.powf(exp);
let comp = 1.0 - (-shaped * 3.25).exp();
vis[i] = (comp * 84.0).clamp(0.1, 84.0);
}
vis
}
/// Two-pass peak-preserving smoothing (Tauri applyAverageTransform).
fn apply_average(d: &mut [f32; 256]) {
let src = *d;
for i in 0..256 {
let prev = if i > 0 { src[i - 1] } else { src[i] };
let next = if i < 255 { src[i + 1] } else { src[i] };
let cur = src[i];
d[i] = if cur >= prev && cur >= next {
cur
} else {
(cur + prev.max(next)) / 2.0
};
}
let src2 = *d;
for i in 0..256 {
let prev = if i > 0 { src2[i - 1] } else { src2[i] };
let next = if i < 255 { src2[i + 1] } else { src2[i] };
let cur = src2[i];
d[i] = if cur >= prev && cur >= next {
cur
} else {
cur / 2.0 + prev.max(next) / 3.0 + prev.min(next) / 6.0
};
}
}
/// 3-point box smooth, one pass (Tauri smoothSpectrum).
fn smooth3(d: &mut [f32; 256]) {
let src = *d;
for i in 0..256 {
let prev = if i > 0 { src[i - 1] } else { src[i] };
let next = if i < 255 { src[i + 1] } else { src[i] };
d[i] = (prev + src[i] + next) / 3.0;
}
}
// ---------------------------------------------------------------------------
// QML type registration anchor
// ---------------------------------------------------------------------------
extern "C" {
/// Defined in `cxx/linebed_item.cpp`. Registers `LineBedItem` with the
/// QML type system (idempotent — guarded C++ side).
fn qbz_linebed_register_qml_type();
}
/// Call the C++ registration. The registration normally runs on its own at
/// QGuiApplication construction (`Q_COREAPP_STARTUP_FUNC`, which is BEFORE
/// the engine loads any QML — required, because ShaderSceneLayer.qml's
/// LineBedScene reference resolves at component load). This Rust call
/// exists because the C++ lives in a STATIC LIB: the linker only pulls its
/// object files to resolve an undefined symbol, and nothing else references
/// one. The call from `QbzShaderScene::boot` (which Main.qml runs on every
/// startup) is that reference — the registration itself is the guarded
/// no-op on this second pass.
pub(crate) fn register_qml_item() {
// SAFETY: `qbz_linebed_register_qml_type` takes no arguments, touches
// only Qt's global type registry (thread-safe, and we are on the GUI
// thread anyway — boot() runs from QML), and is idempotent.
unsafe { qbz_linebed_register_qml_type() };
}
#[cfg(test)]
mod tests {
use super::*;
/// Silence reshapes to the floor: every band clamps to 0.1 (the gamma +
/// soft clip of a zero signal is 0, clamped up to 0.1).
#[test]
fn silence_reshapes_to_the_floor() {
let vis = reshape_512_to_256(&[0.0; SPECTRO_BANDS]);
assert!(vis.iter().all(|&h| h == 0.1), "not all floor: {vis:?}");
}
/// The heights contract: [0.1, 84] for ANY input — including absurd
/// ones (the soft clip, not the clamp, is what does the real work at
/// the top; the clamp is the floor guard).
#[test]
fn heights_stay_in_bounds() {
for data in [
vec![0.0f32; SPECTRO_BANDS],
vec![1.0f32; SPECTRO_BANDS],
vec![100.0f32; SPECTRO_BANDS],
] {
let vis = reshape_512_to_256(&data);
for (i, &h) in vis.iter().enumerate() {
assert!((0.1..=84.0).contains(&h), "band {i} out of range: {h}");
}
}
}
/// A single-bin spike lands in the right output region: bin 100 of 512
/// maps through the freq warp (4 + 456*(i/256)^1.32) to output ≈ 78-79.
/// The peak-preserving smoothing keeps a lone spike alive.
#[test]
fn single_bin_spike_lands_in_the_right_region() {
let mut data = [0.0f32; SPECTRO_BANDS];
data[100] = 1.0;
let vis = reshape_512_to_256(&data);
let peak = vis
.iter()
.enumerate()
.max_by(|a, b| a.1.total_cmp(b.1))
.map(|(i, _)| i)
.unwrap();
assert!(
(72..=85).contains(&peak),
"spike at bin 100 peaked at output {peak}, expected ≈78"
);
assert!(vis[peak] > 40.0, "the spike must tower: {}", vis[peak]);
// Far from the spike the bed stays at the floor.
assert_eq!(vis[10], 0.1);
assert_eq!(vis[200], 0.1);
}
/// The receive-IIR: new frame takes 97%, the accumulator keeps 3%
/// (coefficient ORDER matters — this is what the reference does, and a
/// swapped pair would read as instant attack + slow release, the
/// opposite of the intended behavior).
#[test]
fn receive_iir_coefficients() {
let mut lb = LineBedState::default();
let mut bins = vec![0.0f32; SPECTRO_BANDS];
bins[300] = 1.0;
lb.push(&bins);
assert!((lb.smoothed[300] - 0.97).abs() < 1e-6);
lb.push(&vec![0.0f32; SPECTRO_BANDS]);
assert!((lb.smoothed[300] - 0.97 * 0.03).abs() < 1e-6);
}
/// The depth ring: row 0 = newest, every push shifts the previous rows
/// one slot deeper. Push a spike, then silence: row 0 flattens, row 1
/// keeps the spike's reshape.
#[test]
fn ring_shifts_newest_first() {
let mut lb = LineBedState::default();
let mut spike = vec![0.0f32; SPECTRO_BANDS];
spike[100] = 1.0;
lb.push(&spike);
let after_spike = lb.ring[0..LINEBED_BANDS].to_vec();
let spiked = after_spike.iter().any(|&h| h > 40.0);
assert!(spiked, "the spike reshape never reached the ring");
lb.push(&vec![0.0f32; SPECTRO_BANDS]);
// Row 0 is the silence reshape (near floor: the IIR keeps 3% of the
// spike, which reshapes well under the old peak)...
let row0_max = lb.ring[0..LINEBED_BANDS]
.iter()
.copied()
.fold(0.0f32, f32::max);
let row1 = &lb.ring[LINEBED_BANDS..2 * LINEBED_BANDS];
assert!(row0_max < after_spike.iter().copied().fold(0.0f32, f32::max));
// ...and row 1 is EXACTLY the previous row 0 (the shift).
assert_eq!(row1, after_spike.as_slice());
}
/// `ring_bytes` is the whole 256x200 f32 ring, R32F texture size.
#[test]
fn ring_bytes_is_the_full_texture() {
let lb = LineBedState::default();
assert_eq!(
lb.ring_bytes().len(),
LINEBED_LINES * LINEBED_BANDS * std::mem::size_of::<f32>()
);
}
}
+7
View File
@@ -30,6 +30,10 @@ mod viz_bridge;
// QbzImmersive singleton (§3) — open funnel + view persistence + the §3.4
// search surface. The QML overlay lands in B2.
mod immersive_bridge;
// Shader scenes (2026-08-15 immersive-completion contract, block A1): the
// QbzShaderScene singleton — scene mode + tier gate + the batched audio
// pack. `scene_bridge.rs` was TAKEN by ArtistScene (spec 01 §4 name check).
mod shader_scene_bridge;
// Immersive Suggestions (the same contract, block B4, §4.5): the
// QbzSuggestions singleton — the one genuinely absent domain.
mod suggestions_bridge;
@@ -229,6 +233,9 @@ mod album_info_qt;
mod cover_artwork_qt;
mod external_reco_qt;
mod ambient_qt;
// Tunnel Flow scene (B1, 2026-08-15 immersive-completion contract): the
// Tauri line-palette extraction, published on QbzShaderScene per track.
mod tunnelflow_qt;
mod artist_qt;
mod lyrics_qt;
mod playback_qt;
+8 -1
View File
@@ -84,7 +84,14 @@ pub fn set_active_api(api: &str) -> bool {
if api.is_empty() || api == "unknown" {
return false;
}
let tier = api_is_gpu(&api);
// Headless-verification override: the VNC/offscreen platforms report a
// "null" probe api even when the scene graph renders through a real RHI
// (e.g. QSG_RHI_BACKEND=vulkan offscreen), which would hide the shader
// scenes from exactly the verification runs that need them.
// QBZ_FORCE_GPU_TIER=1 forces the tier on; it changes nothing else (the
// resolved api string still reports what the probe saw).
let forced = std::env::var_os("QBZ_FORCE_GPU_TIER").is_some_and(|v| v == "1");
let tier = api_is_gpu(&api) || forced;
let previous_tier = GPU_TIER.swap(tier, Ordering::SeqCst);
let first = !RESOLVED.swap(true, Ordering::SeqCst);
{
+142
View File
@@ -0,0 +1,142 @@
//! Spectral Ribbon (immersive shader scene, mode 4) — the CPU half.
//!
//! Block A3 of the 2026-08-15 immersive-completion contract (spec 01 §2.4).
//! Ports the publisher side of the Slint spectrogram feed
//! (`crates/qbz/src/visualizer.rs:240-256` + `shader_underlay.rs:855-929`):
//! per fresh Spectral512 frame, one 512-byte row (u8 per band,
//! `clamp(0,1)*255`), written at the playback-time column
//! `progress * (COLS-1)`, with a reset (full clear) on track change / seek.
//!
//! The GPU half is the C++ `RibbonItem` (`cxx/ribbon_item.{h,cpp}`), which
//! owns the persistent R8 texture, the gap-fill (the Slint SPECTRO_LAST_COL
//! logic lives renderer-side here, next to the texture it describes) and
//! the one-pass colorizer draw. This module only builds the self-describing
//! frame the item consumes (the layout is pinned between the two files and
//! `shader_scene_bridge.rs`):
//!
//! ```text
//! bytes 0..4 column (u32 LE) — playback-time column, 0..2047
//! byte 4 reset flag (0/1) — full clear, applied BEFORE the row write
//! bytes 5..517 the 512-band row
//! ```
/// Pinned with `cxx/ribbon_item.cpp` and the Slint reference
/// (`shader_underlay.rs:44-45`).
pub(crate) const SPECTRO_BANDS: usize = 512;
pub(crate) const SPECTRO_COLS: u32 = 2048;
pub(crate) const FRAME_BYTES: usize = 4 + 1 + SPECTRO_BANDS;
/// Drain-local ribbon state (the viz drain thread — the linebed_qt.rs
/// pattern: per-tick state, never shared, never locked). The reference keeps
/// `last_track_id`/`last_progress` as drain-closure locals
/// (visualizer.rs:114-116); the Slint thread-local SPECTRO_LAST_COL moves
/// renderer-side with the texture (see the header).
#[derive(Default)]
pub(crate) struct RibbonState {
last_track_id: u64,
last_progress: f32,
}
impl RibbonState {
/// Build the frame for one fresh Spectral512 row, or `None` when the row
/// is empty. `cursor` is `(track_id, progress 0..1)` from
/// `now_playing::ribbon_cursor` (second-granular, like the reference's
/// NowPlayingState read).
///
/// Reset rule VERBATIM from visualizer.rs:248-250: track change, a
/// backward step past 0.01, or a forward JUMP past 0.15 (a seek — the
/// ~1 Hz progress granularity means normal playback never moves more
/// than that between ticks except on VERY short tracks... exactly as the
/// reference has it).
pub(crate) fn frame(&mut self, bins: &[f32], cursor: (u64, f32)) -> Option<Vec<u8>> {
if bins.is_empty() {
return None;
}
let (track_id, progress) = cursor;
let reset = track_id != self.last_track_id
|| progress + 0.01 < self.last_progress
|| progress > self.last_progress + 0.15;
self.last_track_id = track_id;
self.last_progress = progress;
let col = (progress.clamp(0.0, 1.0) * (SPECTRO_COLS - 1) as f32) as u32;
let mut out = Vec::with_capacity(FRAME_BYTES);
out.extend_from_slice(&col.to_le_bytes());
out.push(u8::from(reset));
for i in 0..SPECTRO_BANDS {
let v = if i < bins.len() {
(bins[i].clamp(0.0, 1.0) * 255.0) as u8
} else {
0
};
out.push(v);
}
Some(out)
}
}
// ---------------------------------------------------------------------------
// QML type registration anchor
// ---------------------------------------------------------------------------
extern "C" {
/// Defined in `cxx/ribbon_item.cpp`. Registers `RibbonItem` with the
/// QML type system (idempotent — guarded C++ side).
fn qbz_ribbon_register_qml_type();
}
/// Call the C++ registration — the linebed_qt.rs idiom: the C++ lives in a
/// STATIC LIB, so the linker only pulls its object file to resolve an
/// undefined symbol; the call from `QbzShaderScene::boot` is that reference
/// (the registration itself already ran at QGuiApplication construction via
/// Q_COREAPP_STARTUP_FUNC).
pub(crate) fn register_qml_item() {
// SAFETY: no arguments, touches only Qt's global type registry (we are
// on the GUI thread — boot() runs from QML), idempotent.
unsafe { qbz_ribbon_register_qml_type() };
}
#[cfg(test)]
mod tests {
use super::*;
/// The frame layout is pinned with cxx/ribbon_item.cpp: 4-byte col,
/// 1-byte reset, 512-byte row.
#[test]
fn frame_layout_is_pinned() {
let mut st = RibbonState::default();
let bins = vec![0.5f32; 512];
let f = st.frame(&bins, (7, 0.25)).expect("non-empty row");
assert_eq!(f.len(), FRAME_BYTES);
let col = u32::from_le_bytes([f[0], f[1], f[2], f[3]]);
assert_eq!(col, (0.25 * (SPECTRO_COLS - 1) as f32) as u32);
assert_eq!(f[4], 1, "first frame for a track resets");
assert!(f[5..].iter().all(|&b| b == 127)); // 0.5 * 255 = 127.5 -> 127
}
/// The reset rule (visualizer.rs:248-250 verbatim): same track + small
/// forward progress does NOT reset; a backward step, a forward jump past
/// 0.15, or a track change DO.
#[test]
fn reset_rule_matches_the_reference() {
let mut st = RibbonState::default();
let bins = vec![0.1f32; 8]; // shorter than 512 — zero-padded
let f = st.frame(&bins, (1, 0.0)).unwrap();
assert_eq!(f[4], 1, "first ever frame resets (track 0 -> 1)");
let f = st.frame(&bins, (1, 0.05)).unwrap();
assert_eq!(f[4], 0, "normal progress keeps the texture");
let f = st.frame(&bins, (1, 0.045)).unwrap();
assert_eq!(f[4], 0, "a sub-0.01 backward nudge is NOT a seek");
let f = st.frame(&bins, (1, 0.02)).unwrap();
assert_eq!(f[4], 1, "a backward step past 0.01 is a seek");
let f = st.frame(&bins, (1, 0.20)).unwrap();
assert_eq!(f[4], 1, "a forward jump past 0.15 is a seek");
let f = st.frame(&bins, (2, 0.20)).unwrap();
assert_eq!(f[4], 1, "a track change resets");
let f = st.frame(&bins, (2, 0.21)).unwrap();
assert_eq!(f[4], 0);
// Rows shorter than 512 pad with zeros.
assert!(f[5 + 8..].iter().all(|&b| b == 0));
assert!(st.frame(&[], (2, 0.22)).is_none(), "an empty row skips");
}
}
+431
View File
@@ -0,0 +1,431 @@
//! QbzShaderScene — immersive shader-scenes domain bridge (viz_bridge.rs
//! exemplar: OnceLock<CxxQtThread>, `ui()` no-op pre-boot, `boot()`
//! invokable, `impl Default` for construction-seeded values).
//!
//! Block A1 of the immersive-completion contract
//! (`qbz-nix-docs/qt-frontend/2026-08-15-immersive-completion/00-CONTRACT.md`
//! §5, spec `01-shader-scenes-port.md` §1/§4). The Qt counterpart of the
//! Slint `ImmersiveState.shader-mode` + `shader-scenes-available` pair
//! (`ImmersiveView.slint:1293-1405`, menu rows `:654-711`, `g` ring
//! `:1245-1256`).
//!
//! NAME CHECK (spec 01 §4): `src/scene_bridge.rs` is TAKEN by the ArtistScene
//! domain ("artists from the same place", `QbzScene`) — hence
//! `shader_scene_bridge.rs` / `QbzShaderScene`.
//!
//! Scene numbering follows the Slint modes verbatim
//! (`shader_underlay.rs:330-337`): 0 Off, 1 Plasma (shipped by A2 — the
//! feedback `QQuickRhiItem` in cxx/plasma_item.cpp), 2 Tunnel, 3 Aurora,
//! 4 Spectral Ribbon (shipped by A3 — the spectrogram `QQuickRhiItem` in
//! cxx/ribbon_item.cpp fed by `ribbon_qt.rs`),
//! 5 Line Bed (shipped by A4 — the `QQuickRhiItem` in cxx/linebed_item.cpp
//! fed by `linebed_qt.rs`), 6 Liquid Spectrum (PARKED in Slint too), 7
//! Ambient. B1 adds 8 Tunnel Flow — a QT-ONLY scene (the Tauri Canvas2D
//! tunnel ported to the feedback `QQuickRhiItem` in cxx/tunnelflow_item.cpp,
//! spec 02-tauri-tunnel-port.md), menu-only like Ambient-in-Slint: it is NOT
//! in the `g` ring (spec 02 §5). The shipped set is now 1/2/3/4/5/7/8, so
//! the `g` ring is 0→1→2→3→4→5→7→0 (the Slint ring is mod-6 over modes 0..5;
//! the parked scenes are unreachable here and their menu rows DO NOT appear —
//! per the contract's cheap→hard block cut). Ambient (7) is reachable from
//! the ring here; in Slint it is menu-only. That is the one deliberate
//! divergence and it is logged in the block report.
//!
//! A4 (Line Bed): the ready 256x200 f32 depth ring publishes ONCE per viz
//! tick as `linebed_heights` (a QByteArray — ONE notify per tick, the pack's
//! batching pattern; the 512-float Spectral512 stream itself is deliberately
//! never marshalled to QML). The publish is gated on `scene == 5` via the
//! `set_linebed_active` mirror (QML reports the scene edge; the drain reads
//! the atomic — 200 KB at 30 Hz for a scene nobody is looking at is what
//! the pulse law forbids). boot() also forces the C++ item's QML type
//! registration — the `extern "C"` call is what pulls the linebed object
//! file out of the static lib at link time (the registration itself already
//! ran earlier, at QGuiApplication construction, via
//! Q_COREAPP_STARTUP_FUNC; the boot call is the link anchor and a guarded
//! no-op fallback).
//!
//! The audio pack (`pack_json`) is ONE batched update per viz drain tick —
//! a single QString property, not a dozen individual qproperties: every
//! property notify dirties its bindings, and 20 notifies at 30 Hz is 20x the
//! binding churn for the same picture (spec 01 §3). The QML side
//! (ShaderSceneLayer.qml) stashes the parsed document on publish and APPLIES
//! it on the shared shell pulse (`QbzShell.pulseMs`) — the VizSettle pattern —
//! so the scene's uniforms move in the same event-loop turn as every other
//! animator and the window presents ONCE per pulse period (THE PULSE LAW,
//! 00-CONTRACT §3).
//!
//! The palette is NOT part of the pack: it already lives on
//! `QbzShell.ambientPrimary/Secondary/Accent` (shell_bridge.rs, published on
//! track change by playback_qt.rs from the same `ambient_qt` source the
//! Slint side feeds `shader_underlay::set_palette` with). The QML layer binds
//! those three directly (spec 01 §1 — no new Rust for palette).
//!
//! The tier gate is NOT a property of this bridge: it already exists as
//! `QbzShell.shaderScenesAvailable` (shell_bridge.rs, seeded from the Rust
//! renderer probe `renderer_qt::gpu_tier()` — documented there as "the gate
//! the immersive shader scenes were waiting on"). That is the ONE source of
//! truth the FOCUS menu rows and the `g` handler read, exactly like Slint
//! seeds `shader-scenes-available` from the wgpu tier (spec 01 section 4).
//! The shader-LOAD half of the gate (a ShaderEffect reporting Error on a
//! GPU-tier box) lives in ShaderSceneLayer.qml, which owns the effects: on
//! failure it latches itself off and resets `scene` to Off, handing the
//! background back to the atmosphere — but it never feeds the picker flag.
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use cxx_qt::CxxQtThread;
use cxx_qt::Threading as _;
use cxx_qt_lib::{QByteArray, QString};
/// Full-shape default for the audio pack — every field present at zero, so
/// the QML layer can parse it before the first real publish without a guard.
const PACK_EMPTY: &str = "{\"phase\":0,\"beat\":0,\"level\":0,\"levelSmooth\":0,\
\"transient\":0,\"energyLo\":[0,0,0,0],\"energyHi\":[0,0,0,0],\
\"bandsLo\":[0,0,0,0],\"bandsHi\":[0,0,0,0]}";
/// B1: the Tunnel Flow palette default — the Tauri fallback
/// (`DEFAULT_LINE_PALETTE`, TunnelFlowPanel.svelte:63-68), so the scene has
/// a valid palette before the first artwork extraction lands.
const TUNNEL_PALETTE_DEFAULT: &str =
"[\"#ff6a6a\",\"#ffcd5c\",\"#68dcaa\",\"#6eb0ff\"]";
#[cxx_qt::bridge]
pub mod qbz_shader_scene {
extern "C++" {
include!("cxx-qt-lib/qstring.h");
type QString = cxx_qt_lib::QString;
include!("cxx-qt-lib/qbytearray.h");
type QByteArray = cxx_qt_lib::QByteArray;
}
#[auto_cxx_name]
extern "RustQt" {
#[qobject]
#[qml_element]
#[qml_singleton]
// The active scene (Slint `shader-mode`): 0 Off, 1 Plasma (A2),
// 2 Tunnel, 3 Aurora, 4 Spectral Ribbon (A3), 5 Line Bed (A4), 6
// parked, 7 Ambient. Written from QML (menu rows) and from Rust
// (cycle_scene, the immersive open-reset). NOT persisted — Slint
// keeps shader-mode session-only.
#[qproperty(i32, scene)]
// The batched audio pack (the §1 uniform contract minus time/
// resolution/palette), one JSON publish per viz drain tick. READ +
// NOTIFY only — QML never writes it.
#[qproperty(QString, pack_json, READ, NOTIFY)]
// A4: the Line Bed depth ring, 256x200 f32 (row 0 = newest) as raw
// bytes — one publish per viz tick while scene == 5. READ + NOTIFY
// only; the C++ item's QML wrapper (LineBedScene.qml) applies it on
// the pulse edge, never on this notify (the VizSettle pattern).
#[qproperty(QByteArray, linebed_heights, READ, NOTIFY)]
// A3: the Spectral Ribbon frame — [col u32 LE][reset u8][512-byte
// row], one publish per viz tick while scene == 4 (layout pinned
// with ribbon_qt.rs and cxx/ribbon_item.cpp). READ + NOTIFY only;
// RibbonScene.qml applies it on the pulse edge.
#[qproperty(QByteArray, ribbon_frame, READ, NOTIFY)]
// B1: the Tunnel Flow palette (scene 8) — four hex colors as a JSON
// array (`["#ff6a6a",...]`, the tunnelflow_qt.rs port of the Tauri
// extractLinePaletteFromArtwork), ONE batched publish per track
// change from ambient_qt::update_for_artwork. READ + NOTIFY only;
// TunnelFlowScene.qml stashes the parse and applies it on the pulse
// edge.
#[qproperty(QString, tunnel_palette_json, READ, NOTIFY)]
type QbzShaderScene = super::QbzShaderSceneRust;
/// Registers this object's Qt-thread hop (Main.qml boots EVERY
/// domain singleton; only QbzSession.boot also fires crate::on_boot).
/// Also anchors the Line Bed item's QML type registration (see the
/// module header).
#[qinvokable]
fn boot(self: Pin<&mut QbzShaderScene>);
/// The `g` ring over the shipped scenes: 0→1→2→3→4→5→7→0 (Off →
/// Plasma → Tunnel → Aurora → Spectral Ribbon → Line Bed → Ambient
/// → Off). Anything outside the
/// shipped set (a parked mode number that could never be selected)
/// falls back to Off. The availability gate lives at the call site
/// (the QML key handler), like Slint's `if shader-scenes-available`
/// guard.
#[qinvokable]
fn cycle_scene(self: Pin<&mut QbzShaderScene>);
/// A4 publish gate: ShaderSceneLayer reports scene==5 edges here so
/// the viz drain only pushes/publishes the 200 KB depth ring while
/// the scene is actually on screen (the pulse law). Writes an
/// atomic the drain reads; never touches the object itself.
#[qinvokable]
fn set_linebed_active(self: Pin<&mut QbzShaderScene>, active: bool);
/// A3 publish gate, same shape as set_linebed_active: scene==4
/// edges gate the 517-byte ribbon frame publish.
#[qinvokable]
fn set_ribbon_active(self: Pin<&mut QbzShaderScene>, active: bool);
}
impl cxx_qt::Threading for QbzShaderScene {}
}
use qbz_shader_scene::QbzShaderScene;
/// Rust side of the shader-scene bridge (plain storage, phase-1 pattern).
pub struct QbzShaderSceneRust {
scene: i32,
pack_json: QString,
linebed_heights: QByteArray,
ribbon_frame: QByteArray,
tunnel_palette_json: QString,
}
impl Default for QbzShaderSceneRust {
fn default() -> Self {
Self {
scene: 0,
pack_json: QString::from(PACK_EMPTY),
linebed_heights: QByteArray::default(),
ribbon_frame: QByteArray::default(),
tunnel_palette_json: QString::from(TUNNEL_PALETTE_DEFAULT),
}
}
}
// ---------------------------------------------------------------------------
// The UI hop (viz_bridge.rs pattern)
// ---------------------------------------------------------------------------
static QT_THREAD: OnceLock<CxxQtThread<QbzShaderScene>> = OnceLock::new();
/// Queue a shader-scene-bridge mutation onto the Qt event loop (no-op before
/// boot registers the thread).
pub(crate) fn ui(f: impl FnOnce(Pin<&mut QbzShaderScene>) + Send + 'static) {
if let Some(thread) = QT_THREAD.get() {
let _ = thread.queue(f);
}
}
/// The viz drain's batched pack publish (viz_qt.rs, ~30 Hz while immersive is
/// open and the tap runs). ONE property write = ONE notify per tick. The
/// property is READ+NOTIFY (no WRITE, so no generated setter): store +
/// notify by hand, the apply_open pattern.
pub(crate) fn publish_pack(json: String) {
ui(move |mut s| {
use cxx_qt::CxxQtType as _;
s.as_mut().rust_mut().pack_json = QString::from(&json);
s.as_mut().pack_json_changed();
});
}
// ---------------------------------------------------------------------------
// A4: the Line Bed depth ring (scene 5)
// ---------------------------------------------------------------------------
/// True while the Line Bed scene is on screen. Mirrored from QML
/// (`set_linebed_active`, fired on scene edges by ShaderSceneLayer) because
/// the viz drain thread cannot read the QObject property: this atomic is
/// what gates the 200 KB ring publish (the pulse law — an invisible scene
/// writes nothing).
static LINEBED_ACTIVE: AtomicBool = AtomicBool::new(false);
/// The drain-side read of the gate (viz_qt.rs).
pub(crate) fn linebed_active() -> bool {
LINEBED_ACTIVE.load(Ordering::Relaxed)
}
/// One ring publish per viz tick (the pack's batching pattern): store the
/// QByteArray + ONE notify. The QML side stashes and applies on the pulse
/// edge, so this notify never dirties the scene by itself.
pub(crate) fn publish_linebed(bytes: &[u8]) {
let buf = QByteArray::from(bytes);
ui(move |mut s| {
use cxx_qt::CxxQtType as _;
s.as_mut().rust_mut().linebed_heights = buf;
s.as_mut().linebed_heights_changed();
});
}
// ---------------------------------------------------------------------------
// A3: the Spectral Ribbon frame (scene 4)
// ---------------------------------------------------------------------------
/// True while the Spectral Ribbon scene is on screen — the linebed gate's
/// twin (the viz drain thread cannot read the QObject property, so QML
/// mirrors the scene edge into this atomic; an invisible scene publishes
/// nothing — the pulse law).
static RIBBON_ACTIVE: AtomicBool = AtomicBool::new(false);
/// The drain-side read of the gate (viz_qt.rs).
pub(crate) fn ribbon_active() -> bool {
RIBBON_ACTIVE.load(Ordering::Relaxed)
}
/// One frame publish per viz tick (the pack's batching pattern): store the
/// QByteArray + ONE notify. The QML side stashes and applies on the pulse
/// edge, so this notify never dirties the scene by itself.
pub(crate) fn publish_ribbon(bytes: Vec<u8>) {
let buf = QByteArray::from(bytes.as_slice());
ui(move |mut s| {
use cxx_qt::CxxQtType as _;
s.as_mut().rust_mut().ribbon_frame = buf;
s.as_mut().ribbon_frame_changed();
});
}
// ---------------------------------------------------------------------------
// B1: the Tunnel Flow palette (scene 8)
// ---------------------------------------------------------------------------
/// One batched palette publish per track change (ambient_qt::
/// update_for_artwork, which already opens the cached cover): store the JSON
/// array + ONE notify. Track-change cadence, not per-tick — no scene gate
/// needed (the pulse law is about the 30 Hz streams).
pub(crate) fn publish_tunnel_palette(json: String) {
ui(move |mut s| {
use cxx_qt::CxxQtType as _;
s.as_mut().rust_mut().tunnel_palette_json = QString::from(&json);
s.as_mut().tunnel_palette_json_changed();
});
}
/// Immersive open-reset (parity `main.rs:10300-10301` — a documented no-op in
/// v1 because the scenes were parked; REAL here): entering the immersive
/// overlay always lands on scene Off. Called from the immersive open funnel
/// (immersive_bridge.rs apply_open true edge). No-op when already Off so the
/// common path emits no notify.
pub(crate) fn reset_on_immersive_open() {
ui(|mut s| {
if s.scene != 0 {
s.as_mut().set_scene(0);
}
});
}
/// The `g` ring map, free-standing so the unit test can pin it without a
/// QObject: 0→1→2→3→4→5→7→0, everything else → 0.
fn ring_next(scene: i32) -> i32 {
match scene {
0 => 1, // Off -> Plasma (A2)
1 => 2, // Plasma -> Tunnel
2 => 3, // Tunnel -> Aurora
3 => 4, // Aurora -> Spectral Ribbon (A3)
4 => 5, // Spectral Ribbon -> Line Bed (A4)
5 => 7, // Line Bed -> Ambient
_ => 0, // Ambient (and anything unexpected) -> Off
}
}
// ---------------------------------------------------------------------------
// A2: the Plasma item registration anchor
// ---------------------------------------------------------------------------
extern "C" {
/// Defined in `cxx/plasma_item.cpp`. Registers `PlasmaItem` with the QML
/// type system (idempotent — guarded C++ side).
fn qbz_plasma_register_qml_type();
/// Defined in `cxx/tunnelflow_item.cpp`. Registers `TunnelFlowItem` with
/// the QML type system (idempotent — guarded C++ side).
fn qbz_tunnelflow_register_qml_type();
}
/// Call the C++ registration — the linebed_qt.rs idiom: the C++ lives in a
/// STATIC LIB, so the linker only pulls its object file to resolve an
/// undefined symbol; the call from `boot` is that reference (the
/// registration itself already ran at QGuiApplication construction via
/// Q_COREAPP_STARTUP_FUNC).
pub(crate) fn register_plasma_qml_item() {
// SAFETY: no arguments, touches only Qt's global type registry (we are
// on the GUI thread — boot() runs from QML), idempotent.
unsafe { qbz_plasma_register_qml_type() };
}
/// B1: the same static-lib link anchor for the Tunnel Flow item
/// (cxx/tunnelflow_item.cpp).
pub(crate) fn register_tunnelflow_qml_item() {
// SAFETY: no arguments, touches only Qt's global type registry (we are
// on the GUI thread — boot() runs from QML), idempotent.
unsafe { qbz_tunnelflow_register_qml_type() };
}
impl qbz_shader_scene::QbzShaderScene {
pub fn boot(self: Pin<&mut Self>) {
if QT_THREAD.set(self.qt_thread()).is_err() {
log::warn!("[qbz-qt] shader-scene Qt thread already registered");
}
// A4: anchor the Line Bed C++ object file into the link (see the
// module header) and double-check the QML type registration. The
// registration itself already ran at QGuiApplication construction
// (Q_COREAPP_STARTUP_FUNC in cxx/linebed_item.cpp, BEFORE the
// engine loads any QML); this call is guarded and idempotent.
crate::viz_qt::linebed_qt::register_qml_item();
// A2: same static-lib link anchor for the Plasma item
// (cxx/plasma_item.cpp).
register_plasma_qml_item();
// A3: same anchor for the Spectral Ribbon item
// (cxx/ribbon_item.cpp).
crate::viz_qt::ribbon_qt::register_qml_item();
// B1: same anchor for the Tunnel Flow item
// (cxx/tunnelflow_item.cpp).
register_tunnelflow_qml_item();
}
/// The `g` ring over the shipped scenes (0→2→3→5→7→0 — A4 added Line
/// Bed between Aurora and Ambient, the Slint menu order). Anything else
/// (parked modes 1/4/6, out-of-range junk) snaps to Off — the ring is
/// defined over what EXISTS, not over the Slint mode space.
pub fn cycle_scene(mut self: Pin<&mut Self>) {
let next = ring_next(self.scene);
self.as_mut().set_scene(next);
}
/// The A4 publish gate (see LINEBED_ACTIVE). Runs on the Qt thread but
/// touches only the atomic.
pub fn set_linebed_active(self: Pin<&mut Self>, active: bool) {
LINEBED_ACTIVE.store(active, Ordering::Relaxed);
}
/// The A3 publish gate (see RIBBON_ACTIVE). Runs on the Qt thread but
/// touches only the atomic.
pub fn set_ribbon_active(self: Pin<&mut Self>, active: bool) {
RIBBON_ACTIVE.store(active, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The pack default is full-shape JSON: every field the QML layer reads
/// is present (and zero) before the first viz publish.
#[test]
fn pack_default_is_full_shape() {
let doc: serde_json::Value = serde_json::from_str(PACK_EMPTY).unwrap();
for key in ["phase", "beat", "level", "levelSmooth", "transient"] {
assert!(doc.get(key).is_some(), "missing {key}");
}
for key in ["energyLo", "energyHi", "bandsLo", "bandsHi"] {
assert!(
doc.get(key)
.and_then(|v| v.as_array())
.is_some_and(|a| a.len() == 4),
"missing/short {key}"
);
}
}
/// The `g` ring over the shipped scenes: 0→1→2→3→4→5→7→0 (A2 added
/// Plasma, A3 the Ribbon, A4 Line Bed); parked modes and junk snap to
/// Off.
#[test]
fn g_ring_visits_the_shipped_scenes() {
assert_eq!(ring_next(0), 1);
assert_eq!(ring_next(1), 2);
assert_eq!(ring_next(2), 3);
assert_eq!(ring_next(3), 4);
assert_eq!(ring_next(4), 5);
assert_eq!(ring_next(5), 7);
assert_eq!(ring_next(7), 0);
for junk in [6, -1, 42] {
assert_eq!(ring_next(junk), 0, "junk mode {junk} must snap to Off");
}
}
}
+280
View File
@@ -0,0 +1,280 @@
//! Tunnel Flow palette (block B1 of the 2026-08-15 immersive-completion
//! contract, spec 02-tauri-tunnel-port.md §4) — the Rust port of the legacy
//! Tauri panel's `extractLinePaletteFromArtwork`
//! (`qbz-worktrees/legacy-tauri .../panels/TunnelFlowPanel.svelte:108-197`).
//!
//! The constants are ported EXACTLY so the picks match the reference:
//! - the artwork is sampled at 36x36 (the caller resizes; Tauri drew to a
//! 36x36 canvas — `image::imageops::resize`/Triangle is the decode-side
//! equivalent the ambient pipeline already uses);
//! - pixels with alpha < 120 or luminance < 0.05 / > 0.97 are skipped
//! (luminance = 0.2126/0.7152/0.0722 over 255);
//! - RGB quantize to 32-step buckets; a bucket's color is its mean;
//! - rank by `count * (0.72 + avgSaturation * 1.28)` descending (saturation =
//! (max-min)/max on the 0..255 scale);
//! - dedup: skip a candidate whose saturation < 0.12 once the first pick
//! exists, and any candidate within RGB distance < 44 of a pick;
//! - pad to 4 by repeating the last pick; empty -> the DEFAULT palette
//! (TunnelFlowPanel.svelte:63-68).
//!
//! The JS Map preserves insertion order and V8's sort is stable, so ties in
//! the ranking resolve by first-seen order — reproduced here with a Vec +
//! key->index map and `sort_by` (also stable). `Math.round` on non-negative
//! values equals `f32::round` (half away from zero), which is what the mean
//! rounding uses.
//!
//! This palette is deliberately SEPARATE from the ambient triad
//! (`ambient_qt.rs`): the Tauri scene ranks raw RGB buckets, the Slint
//! `spectrum_colors` votes hue bins — different pictures on the same cover.
//! It is published per track as ONE batched `QbzShaderScene.tunnelPaletteJson`
//! (the pack_json batching pattern) from `ambient_qt::update_for_artwork`,
//! which already opens the cached cover on every track change.
use std::collections::HashMap;
/// The Tauri fallback (`DEFAULT_LINE_PALETTE`, TunnelFlowPanel.svelte:63-68):
/// #ff6a6a / #ffcd5c / #68dcaa / #6eb0ff.
pub const DEFAULT_LINE_PALETTE: [(u8, u8, u8); 4] = [
(255, 106, 106),
(255, 205, 92),
(104, 220, 170),
(110, 176, 255),
];
/// The Tauri sample size (`:123`).
pub const SAMPLE_SIZE: u32 = 36;
fn color_saturation(r: u8, g: u8, b: u8) -> f32 {
let max = r.max(g).max(b) as f32;
let min = r.min(g).min(b) as f32;
if max <= 0.0 {
return 0.0;
}
(max - min) / max
}
fn color_distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> f32 {
let dr = a.0 as f32 - b.0 as f32;
let dg = a.1 as f32 - b.1 as f32;
let db = a.2 as f32 - b.2 as f32;
(dr * dr + dg * dg + db * db).sqrt()
}
struct Bucket {
count: u32,
red: u64,
green: u64,
blue: u64,
sat_sum: f32,
}
/// The port of `extractLinePaletteFromArtwork` operating on the 36x36 sample.
/// Always returns exactly 4 colors.
pub fn line_palette(img: &image::RgbaImage) -> Vec<(u8, u8, u8)> {
let mut buckets: Vec<Bucket> = Vec::new();
let mut index: HashMap<(u8, u8, u8), usize> = HashMap::new();
for px in img.pixels() {
let [r, g, b, a] = px.0;
if a < 120 {
continue;
}
let luminance = (r as f32 * 0.2126 + g as f32 * 0.7152 + b as f32 * 0.0722) / 255.0;
if !(0.05..=0.97).contains(&luminance) {
continue;
}
let sat = color_saturation(r, g, b);
let key = (r / 32 * 32, g / 32 * 32, b / 32 * 32);
match index.get(&key) {
Some(&i) => {
let bk = &mut buckets[i];
bk.count += 1;
bk.red += r as u64;
bk.green += g as u64;
bk.blue += b as u64;
bk.sat_sum += sat;
}
None => {
index.insert(key, buckets.len());
buckets.push(Bucket {
count: 1,
red: r as u64,
green: g as u64,
blue: b as u64,
sat_sum: sat,
});
}
}
}
if buckets.is_empty() {
return DEFAULT_LINE_PALETTE.to_vec();
}
// Rank by count * (0.72 + avgSat * 1.28) descending; stable on ties.
let mut order: Vec<usize> = (0..buckets.len()).collect();
order.sort_by(|&a, &b| {
let score = |bk: &Bucket| {
let avg_sat = bk.sat_sum / bk.count as f32;
bk.count as f32 * (0.72 + avg_sat * 1.28)
};
score(&buckets[b])
.partial_cmp(&score(&buckets[a]))
.unwrap_or(std::cmp::Ordering::Equal)
});
let mut palette: Vec<(u8, u8, u8)> = Vec::new();
for &i in &order {
let bk = &buckets[i];
let candidate = (
(bk.red as f32 / bk.count as f32).round() as u8,
(bk.green as f32 / bk.count as f32).round() as u8,
(bk.blue as f32 / bk.count as f32).round() as u8,
);
let candidate_sat = color_saturation(candidate.0, candidate.1, candidate.2);
if candidate_sat < 0.12 && !palette.is_empty() {
continue;
}
if palette
.iter()
.any(|&existing| color_distance(existing, candidate) < 44.0)
{
continue;
}
palette.push(candidate);
if palette.len() >= 4 {
break;
}
}
if palette.is_empty() {
return DEFAULT_LINE_PALETTE.to_vec();
}
while palette.len() < 4 {
palette.push(palette[palette.len() - 1]);
}
palette
}
/// The batched publish form: `["#ff6a6a","#ffcd5c","#68dcaa","#6eb0ff"]` —
/// one JSON document, one notify (the pack_json batching pattern).
pub fn line_palette_json(palette: &[(u8, u8, u8)]) -> String {
let parts: Vec<String> = palette
.iter()
.map(|c| format!("\"#{:02x}{:02x}{:02x}\"", c.0, c.1, c.2))
.collect();
format!("[{}]", parts.join(","))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 36x36 image tiled from the given pixels (the ambient_qt.rs test
/// idiom, at the Tauri sample size).
fn img_from(pixels: &[(u8, u8, u8)]) -> image::RgbaImage {
let mut img = image::RgbaImage::new(SAMPLE_SIZE, SAMPLE_SIZE);
for (i, px) in img.pixels_mut().enumerate() {
let (r, g, b) = pixels[i % pixels.len()];
*px = image::Rgba([r, g, b, 255]);
}
img
}
#[test]
fn coverage_beats_saturation_speck() {
// 3/4 muted red + 1/4 vivid blue: score = count*(0.72+avgSat*1.28) —
// the red bucket (count ~972, sat ~0.5) must outrank the blue speck
// (count ~324, sat ~0.97).
let img = img_from(&[
(140, 70, 70),
(140, 70, 70),
(140, 70, 70),
(30, 40, 235),
]);
let palette = line_palette(&img);
assert_eq!(palette[0], (140, 70, 70));
assert_eq!(palette[1], (30, 40, 235));
}
#[test]
fn dedup_drops_colors_closer_than_44() {
// Two reds 30 apart (distance 30 < 44) collapse to one pick; the
// second pick must be the distant green.
let img = img_from(&[
(200, 40, 40),
(200, 40, 40),
(170, 40, 40), // same 32-bucket family, distance 30 from the first
(40, 200, 40),
]);
let palette = line_palette(&img);
assert_eq!(palette.len(), 4);
let red = palette[0];
assert!((200 - red.0 as i32).abs() <= 30 && red.1 == 40);
// No second pick within distance 44 of the first.
assert!(color_distance(palette[1], red) >= 44.0);
}
#[test]
fn low_saturation_candidates_are_skipped_after_the_first_pick() {
// Dominant vivid red + several grays: the grays (sat 0 < 0.12) may
// never follow the first pick, so the palette pads by repeating.
let img = img_from(&[
(220, 30, 30),
(220, 30, 30),
(220, 30, 30),
(120, 120, 120),
]);
let palette = line_palette(&img);
assert_eq!(palette[0], (220, 30, 30));
assert!(palette.iter().all(|&c| c == palette[0]));
}
#[test]
fn first_pick_may_be_low_saturation() {
// An all-gray cover: no chroma at all. The first bucket is kept
// (the sat<0.12 skip only applies once a pick exists) and then pads.
// NOTE the ambient triad falls back on gray covers; the Tauri line
// palette deliberately does NOT.
let img = img_from(&[(120, 120, 120)]);
let palette = line_palette(&img);
assert_eq!(palette[0], (120, 120, 120));
assert_eq!(palette.len(), 4);
}
#[test]
fn alpha_and_luminance_gates_feed_the_fallback() {
// Every pixel skipped: alpha < 120, luminance < 0.05, luminance >
// 0.97 -> the DEFAULT palette, not an empty/gray one.
let mut img = image::RgbaImage::new(SAMPLE_SIZE, SAMPLE_SIZE);
for (i, px) in img.pixels_mut().enumerate() {
*px = match i % 3 {
0 => image::Rgba([200, 30, 30, 60]), // alpha gate
1 => image::Rgba([8, 8, 10, 255]), // luminance < 0.05
_ => image::Rgba([252, 252, 250, 255]), // luminance > 0.97
};
}
assert_eq!(line_palette(&img), DEFAULT_LINE_PALETTE.to_vec());
}
#[test]
fn quantize_and_mean_match_the_reference() {
// 32-step buckets: (35,…) and (63,…) share bucket 32; the bucket
// color is the ROUNDED mean of its members. (A same-family neighbor
// bucket would sit inside the 44 dedup radius, so the second pick
// here is a distant red.)
let img = img_from(&[(35, 200, 40), (63, 200, 40), (250, 40, 40)]);
let palette = line_palette(&img);
// Bucket (32,192,32): mean r = (35+63)/2 = 49 -> (49,200,40).
assert_eq!(palette[0], (49, 200, 40));
assert!(palette.contains(&(250, 40, 40)));
}
#[test]
fn json_is_the_batched_four_hex_array() {
let json = line_palette_json(&DEFAULT_LINE_PALETTE);
assert_eq!(json, "[\"#ff6a6a\",\"#ffcd5c\",\"#68dcaa\",\"#6eb0ff\"]");
let doc: serde_json::Value = serde_json::from_str(&json).unwrap();
assert_eq!(doc.as_array().unwrap().len(), 4);
}
}
+333 -18
View File
@@ -27,7 +27,18 @@
//! marshalled into a `QList` (in Bars mode the 512-float waveform is latched
//! for an instant mode switch but never published) — UNLESS the immersive
//! overlay is open, which owns the marshalling set and publishes all three
//! streams every frame (§4.2 of the immersive-port contract).
//! streams every frame (§4.2 of the immersive-port contract). Block A1
//! (2026-08-15 immersive-completion) extends the immersive set: `Spectral512`
//! and `Transient1` are LATCHED too (still never dock-marshalled), and the
//! drain derives the shader-scenes uniform pack from them HOST-SIDE
//! (visualizer.rs:172-269 parity — bands8 pairing, level, the level_smooth
//! EMA, the beat/transient envelopes, the phase accumulator with the 4096
//! wrap, the spectral_peak EMA) and publishes it as ONE batched JSON property
//! on `QbzShaderScene` per fresh FFT frame (spec 01 §3: a single property
//! bag, not 20 individual notifies — each notify dirties). Block A4 consumes
//! the SAME latched `Spectral512` Rust-side for the Line Bed depth ring
//! (`linebed_qt.rs` — the 512 floats never reach QML; the ready 256x200
//! ring publishes once per tick, gated on the scene being on screen).
//!
//! Protected-audio note: this lives entirely downstream of the read-only ring
//! buffer. It touches none of the device/stream init (CLAUDE.md "Audio
@@ -43,6 +54,20 @@ use qbz_audio::VisualizerTap;
use crate::viz_bridge;
// A4 (Line Bed, mode 5): the scene's CPU half (LineBedState + the
// 512→256 reshape, fed from the latched Spectral512 cell). Declared HERE
// with #[path] rather than in main.rs because main.rs sits outside this
// block's file ownership (a second agent is working the tree) — the drain
// is its only consumer anyway.
#[path = "linebed_qt.rs"]
pub(crate) mod linebed_qt;
// A3 (Spectral Ribbon, mode 4): the scene's CPU half (RibbonState — the
// 512-byte row + the playback column/reset header, fed from the SAME
// latched Spectral512 cell). Same #[path] rationale as linebed_qt.
#[path = "ribbon_qt.rs"]
pub(crate) mod ribbon_qt;
/// Single-slot, latest-wins frame store shared with the FFT producer thread.
/// A stalled UI drops intermediate frames instead of growing a queue.
#[derive(Default)]
@@ -50,6 +75,14 @@ struct VizCells {
bars: Mutex<Option<[f32; 16]>>,
energy: Mutex<Option<[f32; 5]>>,
waveform: Mutex<Option<Box<[f32; 512]>>>,
// A1 (shader scenes): latched ONLY while the immersive overlay is open
// (MARSHAL_ALL) — the dock renders neither, so the dock path keeps
// dropping them exactly like before. Neither stream WAKES the drain:
// they hitchhike on the bars/energy/waveform wakes, the way the Slint
// 33 ms timer drain takes whatever the cells happen to hold
// (visualizer.rs:146-178).
spectral: Mutex<Option<Vec<f32>>>,
transient: Mutex<Option<f32>>,
}
/// Producer-side sink: latches frames into the shared cells and signals the
@@ -64,9 +97,10 @@ impl VizSink for QtVizSink {
// energy, transient, waveform). Waking the drain on each of them would
// cost 3-4 wakeups per frame for one useful publish, so only the
// stream the visible mode renders signals — UNLESS the immersive
// overlay is open (MARSHAL_ALL, §4.2b), which consumes all three. The
// other cells are still latched so a mode switch has a frame ready
// immediately.
// overlay is open (MARSHAL_ALL, §4.2b), whose wake table covers every
// signalled stream; A1's two scene-only streams latch WITHOUT
// signalling (see their match arms). The other cells are still
// latched so a mode switch has a frame ready immediately.
let mode = ACTIVE_MODE.load(Ordering::Relaxed);
let all = MARSHAL_ALL.load(Ordering::Relaxed);
let wake = match frame {
@@ -82,9 +116,25 @@ impl VizSink for QtVizSink {
*self.cells.energy.lock().unwrap() = Some(b);
stream_wakes(mode, all, Stream::Energy)
}
// The dock renders none of these; ignoring them costs nothing (the
// producer computes the spectral ribbon only for the shader scenes).
VizFrame::Spectral512(_) | VizFrame::Transient1(_) => false,
// The dock renders neither stream, so off-immersive they are
// still dropped for free. While the immersive overlay is open
// (MARSHAL_ALL, A1) they are LATCHED — Transient1 feeds every
// scene's beat punch and Spectral512 feeds the spectral-peak
// EMA (the future mode 4) — but neither WAKES the drain: they
// ride the next bars/energy/waveform-signalled pass, so the
// wake/publish cadence is unchanged.
VizFrame::Spectral512(b) => {
if all {
*self.cells.spectral.lock().unwrap() = Some(b);
}
false
}
VizFrame::Transient1(x) => {
if all {
*self.cells.transient.lock().unwrap() = Some(x);
}
false
}
};
if wake {
wake_drain();
@@ -193,27 +243,188 @@ fn to_qlist(values: &[f32]) -> QList<f32> {
list
}
// ---------------------------------------------------------------------------
// A1: the host-side shader pack (visualizer.rs:172-269 parity)
// ---------------------------------------------------------------------------
/// Derivation state for the shader-scenes uniform pack — the Qt twin of the
/// Slint drain's `last_*` locals (qbz/src/visualizer.rs). Lives on the DRAIN
/// thread (a plain local, no locking): every field is per-tick state derived
/// from the latched cells. Energy/bars arrive ALREADY smoothed upstream
/// (qbz-audio) and are passed through raw — no double EMA
/// (shader_underlay.rs FrameAudio doc).
#[derive(Default)]
struct ShaderPackState {
last_bars16: [f32; 16],
last_energy: [f32; 5],
level_smooth: f32,
beat: f32,
transient: f32,
phase: f32,
spectral_peak: f32,
}
/// The 4096 phase wrap: an integer multiple of 8 so the Tunnel's `& 7` ring
/// math stays seamless across the wrap (tunnel.wgsl:66-69). The Qt port MUST
/// keep it (spec 01 §1).
const PHASE_WRAP: f32 = 4096.0;
impl ShaderPackState {
/// Advance ONE drain tick (~30 Hz, gated on a fresh Viz16 — the cadence
/// carrier) and return the batched JSON pack. Mirrors
/// visualizer.rs:203-269 EXACTLY, including the ORDER: the fresh
/// transient maxes into both envelopes first, then the envelopes decay
/// (beat ×0.88, transient ×0.85), then level/bands/phase derive from the
/// DECAYED values.
fn tick(&mut self, new_transient: Option<f32>, new_spectral: Option<&[f32]>) -> String {
if let Some(x) = new_transient {
self.transient = x.max(self.transient);
self.beat = x.max(self.beat);
}
self.transient *= 0.85;
self.beat *= 0.88;
// 8 log bands paired from the 16 bars (visualizer.rs:205-208).
let mut bands8 = [0.0f32; 8];
for i in 0..8 {
bands8[i] = (self.last_bars16[2 * i] + self.last_bars16[2 * i + 1]) * 0.5;
}
// level = mean(energy5); level_smooth = slow EMA (×0.96 + 0.04·level).
let level = (self.last_energy[0]
+ self.last_energy[1]
+ self.last_energy[2]
+ self.last_energy[3]
+ self.last_energy[4])
* 0.2;
self.level_smooth = self.level_smooth * 0.96 + level * 0.04;
// Forward-motion clock: host-side (rate is audio-dependent), wrapped
// at an integer so fract()-based ring patterns stay continuous across
// the wrap (visualizer.rs:219-222).
self.phase += 0.012 + level * 0.02 + self.beat * 0.02;
if self.phase >= PHASE_WRAP {
self.phase -= PHASE_WRAP;
}
// Real-time ceiling (the future mode 4): highest band with signal,
// EMA-smoothed so the line tracks without jitter (visualizer.rs:
// 223-239). Derived whenever a fresh spectral frame is latched,
// mode-agnostic — the shipped scenes ignore it.
if let Some(bins) = new_spectral {
let n = bins.len();
if n > 1 {
let mut hi = 0usize;
for (i, &v) in bins.iter().enumerate() {
if v > 0.05 {
hi = i;
}
}
let target = hi as f32 / (n - 1) as f32;
self.spectral_peak = self.spectral_peak * 0.85 + target * 0.15;
}
}
// ONE batched publish per tick (spec 01 §3: a single property bag,
// not 20 individual notifies — each notify dirties). The vec4 fields
// of the uniform contract map as: energy_lo = sub/bass/mid/presence,
// energy_hi = air/spectral_peak/0/0 (shader_underlay.rs:844-845),
// bands_lo/hi = bands8 0..3 / 4..7. time/resolution/palette are NOT
// in the pack: time is the QML layer's local pulse clock, resolution
// is the item size, palette is QbzShell.ambient*.
format!(
"{{\"phase\":{},\"beat\":{},\"level\":{},\"levelSmooth\":{},\
\"transient\":{},\
\"energyLo\":[{},{},{},{}],\"energyHi\":[{},{},0,0],\
\"bandsLo\":[{},{},{},{}],\"bandsHi\":[{},{},{},{}]}}",
self.phase,
self.beat,
level,
self.level_smooth,
self.transient,
self.last_energy[0],
self.last_energy[1],
self.last_energy[2],
self.last_energy[3],
self.last_energy[4],
self.spectral_peak,
bands8[0],
bands8[1],
bands8[2],
bands8[3],
bands8[4],
bands8[5],
bands8[6],
bands8[7],
)
}
}
/// Take the pending frame(s) of the stream(s) the current marshalling set
/// renders and hop them onto the Qt thread. Each cell's guard is released by
/// the end of its `let` statement — the mutex is NEVER held across the
/// `viz_bridge::ui` hop, so the producer never blocks on the drain.
fn publish_active(cells: &VizCells) {
fn publish_active(cells: &VizCells, pack: &mut ShaderPackState, linebed: &mut linebed_qt::LineBedState, ribbon: &mut ribbon_qt::RibbonState) {
// §4.2b: immersive open -> publish ALL THREE streams each frame (the
// immersive panels consume bars + energy + waveform simultaneously, like
// the Slint immersive does). ACTIVE_MODE is irrelevant here.
if MARSHAL_ALL.load(Ordering::Relaxed) {
let bars = cells.bars.lock().unwrap().take();
// Viz16 is emitted on EVERY producer frame, so a fresh bars cell is
// the cadence carrier for the pack tick below: a wake that found the
// cells already drained (the sink unparks once per stream variant,
// the park permit coalesces) must NOT tick — the envelopes and the
// phase accumulator are per-tick, and ticking on empty passes would
// run the decay faster than the reference's 30 Hz drain.
let fresh_frame = bars.is_some();
if let Some(b) = bars {
pack.last_bars16 = b;
viz_bridge::ui(move |mut v| v.as_mut().set_bars(to_qlist(&b)));
}
let energy = cells.energy.lock().unwrap().take();
if let Some(b) = energy {
pack.last_energy = b;
viz_bridge::ui(move |mut v| v.as_mut().set_energy(to_qlist(&b)));
}
let waveform = cells.waveform.lock().unwrap().take();
if let Some(b) = waveform {
viz_bridge::ui(move |mut v| v.as_mut().set_waveform(to_qlist(b.as_ref())));
}
// A1: the scene-only streams, latched by the sink without waking.
let spectral = cells.spectral.lock().unwrap().take();
let transient = cells.transient.lock().unwrap().take();
if fresh_frame {
crate::shader_scene_bridge::publish_pack(
pack.tick(transient, spectral.as_deref()),
);
}
// A4 (Line Bed, mode 5): push the SAME latched Spectral512 frame
// into the depth ring (fresh frames only, like the reference's
// per-spectral-frame push — shader_underlay.rs:934-939) and publish
// the ready 256x200 ring ONCE per tick, one QByteArray notify. Both
// are gated on the scene being on screen (the bridge's atomic
// mirror of scene == 5): 200 KB at 30 Hz for a scene nobody is
// looking at is exactly what the pulse law forbids. The state
// persists across scene switches, like Slint's thread-local.
if crate::shader_scene_bridge::linebed_active() {
if let Some(bins) = spectral.as_deref() {
linebed.push(bins);
}
crate::shader_scene_bridge::publish_linebed(linebed.ring_bytes());
}
// A3 (Spectral Ribbon, mode 4): one self-describing frame per fresh
// Spectral512 (the 512-byte row + playback column + reset header —
// ribbon_qt.rs), gated on the scene exactly like the linebed ring
// (517 B at 30 Hz for a scene nobody is looking at is still the
// pulse law's "invisible writes nothing"). FRESH frames only: a
// re-publish at the same progress would re-stamp the same columns
// (the C++ gap-fill cursor never moves backward on its own).
if crate::shader_scene_bridge::ribbon_active() {
if let Some(bins) = spectral.as_deref() {
if let Some(frame) =
ribbon.frame(bins, crate::now_playing::ribbon_cursor())
{
crate::shader_scene_bridge::publish_ribbon(frame);
}
}
}
return;
}
match ACTIVE_MODE.load(Ordering::Relaxed) {
@@ -256,18 +467,27 @@ pub fn install(tap: VisualizerTap) {
let drain_cells = cells.clone();
let drain_thread = std::thread::Builder::new()
.name("qbz-qt-viz-drain".to_string())
.spawn(move || loop {
if !ENABLED.load(Ordering::Relaxed) {
// Disabled: block until `set_enabled(true)` unparks us. A
// leftover permit only costs one extra trip round this check.
.spawn(move || {
// A1: the shader-pack derivation state lives and dies with the
// drain thread — per-tick state, never shared, never locked.
let mut pack = ShaderPackState::default();
// A4: the Line Bed depth ring, same drain-local pattern.
let mut linebed = linebed_qt::LineBedState::default();
// A3: the Spectral Ribbon cursor/reset state, same pattern.
let mut ribbon = ribbon_qt::RibbonState::default();
loop {
if !ENABLED.load(Ordering::Relaxed) {
// Disabled: block until `set_enabled(true)` unparks us. A
// leftover permit only costs one extra trip round this check.
std::thread::park();
continue;
}
publish_active(&drain_cells, &mut pack, &mut linebed, &mut ribbon);
// Wait for the next produced frame. If the sink unparked us while
// we were publishing, the permit is already set and this returns
// immediately — no wakeup is lost, we just re-check the cell.
std::thread::park();
continue;
}
publish_active(&drain_cells);
// Wait for the next produced frame. If the sink unparked us while
// we were publishing, the permit is already set and this returns
// immediately — no wakeup is lost, we just re-check the cell.
std::thread::park();
})
.expect("spawn viz drain thread")
.thread()
@@ -479,4 +699,99 @@ mod tests {
set_enabled(false);
assert_eq!(ENABLED_MASK.load(Ordering::Relaxed), 0);
}
// --- A1: the shader-pack derivation (visualizer.rs:203-269 parity) -----
/// bands8 pairing + level/level_smooth math, checked against the JSON the
/// QML layer parses (the pack's ONLY consumer contract).
#[test]
fn pack_bands_pairing_and_level_ema() {
let mut p = ShaderPackState {
last_bars16: [
0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 0.1, 0.3, 0.5, 0.7, 0.9, 0.2, 0.4, 0.6, 0.8, 1.0,
],
// mean = (0.1+0.2+0.3+0.4+0.5)*0.2 = 0.3
last_energy: [0.1, 0.2, 0.3, 0.4, 0.5],
..Default::default()
};
let json = p.tick(None, None);
let doc: serde_json::Value = serde_json::from_str(&json).unwrap();
// bands8[0] = (0.0+0.2)/2 = 0.1; bands8[7] = (0.8+1.0)/2 = 0.9.
let bands_lo = doc["bandsLo"].as_array().unwrap();
let bands_hi = doc["bandsHi"].as_array().unwrap();
assert!((bands_lo[0].as_f64().unwrap() - 0.1).abs() < 1e-6);
assert!((bands_hi[3].as_f64().unwrap() - 0.9).abs() < 1e-6);
assert!((doc["level"].as_f64().unwrap() - 0.3).abs() < 1e-6);
// First tick: level_smooth = 0*0.96 + 0.3*0.04 = 0.012.
assert!((doc["levelSmooth"].as_f64().unwrap() - 0.012).abs() < 1e-6);
// Second tick: 0.012*0.96 + 0.012 = 0.02352.
let doc2: serde_json::Value = serde_json::from_str(&p.tick(None, None)).unwrap();
assert!((doc2["levelSmooth"].as_f64().unwrap() - 0.02352).abs() < 1e-5);
// energy_hi = [air, spectral_peak, 0, 0] (shader_underlay.rs:845).
let energy_hi = doc["energyHi"].as_array().unwrap();
assert!((energy_hi[0].as_f64().unwrap() - 0.5).abs() < 1e-6);
assert_eq!(energy_hi[2].as_f64().unwrap(), 0.0);
}
/// The envelopes: a fresh transient MAXES into beat AND transient first,
/// then both decay (×0.88 / ×0.85) — and the pack carries the DECAYED
/// values, exactly like visualizer.rs:176-189.
#[test]
fn pack_envelopes_max_in_then_decay() {
let mut p = ShaderPackState::default();
let doc: serde_json::Value = serde_json::from_str(&p.tick(Some(0.5), None)).unwrap();
assert!((doc["beat"].as_f64().unwrap() - 0.44).abs() < 1e-6); // 0.5*0.88
assert!((doc["transient"].as_f64().unwrap() - 0.425).abs() < 1e-6); // 0.5*0.85
// A weaker transient mid-decay does NOT lower the envelope (max-in).
let doc: serde_json::Value = serde_json::from_str(&p.tick(Some(0.1), None)).unwrap();
assert!((doc["beat"].as_f64().unwrap() - 0.44 * 0.88).abs() < 1e-5);
assert!((doc["transient"].as_f64().unwrap() - 0.425 * 0.85).abs() < 1e-5);
}
/// The forward-motion clock: +0.012 + level*0.02 + beat*0.02 per tick,
/// wrapping at 4096 (a multiple of 8, so the Tunnel's `& 7` ring math is
/// seamless across the wrap — spec 01 §1).
#[test]
fn pack_phase_advances_and_wraps_at_4096() {
let mut p = ShaderPackState {
phase: 4096.0 - 0.005,
..Default::default()
};
// level = 0, beat = 0 -> +0.012 -> 4096.007 -> wraps to 0.007.
// Tolerance 2e-3, not tighter: at the 4096 scale an f32 ulp is
// ~4.9e-4, so the pre-wrap addition rounds by a few ulps — the test
// pins the WRAP (and continuity), not the exact residue.
let doc: serde_json::Value = serde_json::from_str(&p.tick(None, None)).unwrap();
assert!((doc["phase"].as_f64().unwrap() - 0.007).abs() < 2e-3);
// With level 0.5 and a decayed beat 0.44: +0.012+0.010+0.0088.
let mut p = ShaderPackState {
last_energy: [0.5; 5],
..Default::default()
};
let doc: serde_json::Value =
serde_json::from_str(&p.tick(Some(0.5), None)).unwrap();
let expected = 0.012 + 0.5 * 0.02 + 0.44 * 0.02;
assert!((doc["phase"].as_f64().unwrap() - expected).abs() < 1e-4);
}
/// The spectral-peak EMA (the future mode 4): the highest bin above 0.05
/// as a fraction, smoothed ×0.85 + 0.15·target (visualizer.rs:223-239).
/// A single-bin / empty frame is ignored (the n > 1 guard).
#[test]
fn pack_spectral_peak_ema() {
let mut p = ShaderPackState::default();
let mut bins = vec![0.0f32; 101];
bins[75] = 0.5; // highest active: 75/100 = 0.75
let doc: serde_json::Value =
serde_json::from_str(&p.tick(None, Some(&bins))).unwrap();
assert!((doc["energyHi"][1].as_f64().unwrap() - 0.75 * 0.15).abs() < 1e-5);
// Empty of signal: target 0, the EMA decays toward it.
let doc: serde_json::Value =
serde_json::from_str(&p.tick(None, Some(&vec![0.0f32; 101]))).unwrap();
assert!((doc["energyHi"][1].as_f64().unwrap() - 0.75 * 0.15 * 0.85).abs() < 1e-4);
// The n > 1 guard: a one-bin frame changes nothing.
let before = p.spectral_peak;
p.tick(None, Some(&[1.0]));
assert_eq!(p.spectral_peak, before);
}
}
@@ -4329,6 +4329,9 @@ msgstr "Los"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Musik-Link öffnen"
@@ -801,3 +801,6 @@ msgstr "Unable to verify this musician's catalog. The information shown is based
msgid "This musician appears in album credits."
msgstr "This musician appears in album credits."
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
@@ -4386,6 +4386,9 @@ msgstr "Ir"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Abrir enlace de música"
@@ -4329,6 +4329,9 @@ msgstr "Aller"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Ouvrir un lien musical"
@@ -4273,6 +4273,9 @@ msgstr "移動"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "音楽リンクを開く"
@@ -4372,6 +4372,9 @@ msgstr "Ga"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Muzieklink openen"
@@ -4329,6 +4329,9 @@ msgstr "Ir"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Abrir link de música"
@@ -4303,6 +4303,9 @@ msgstr "Перейти"
msgid "Line Bed"
msgstr "Line Bed"
msgid "Tunnel Flow"
msgstr "Tunnel Flow"
msgid "Open Music Link"
msgstr "Открыть музыкальную ссылку"