Add buildable C engine, shaders and music source

This commit is contained in:
CRTkafa 2026-09-05 04:16:54 +00:00
parent 63c10fad07
commit 3d526b8566
44 changed files with 23427 additions and 3 deletions

11
.gitattributes vendored Normal file
View file

@ -0,0 +1,11 @@
* text=auto
*.c text eol=lf
*.h text eol=lf
*.hlsl text eol=lf
*.hlsli text eol=lf
*.py text eol=lf
*.md text eol=lf
*.bat text eol=crlf
*.txt text eol=crlf
*.nfo text eol=crlf
*.jpg binary

10
.gitignore vendored
View file

@ -6,3 +6,13 @@
.omc/
.claude/
.codex/
*.pdb
*.ilk
*.bmp
__pycache__/
fx/out/
shaders.h
gputest.txt
export-provenance.json
delivery.json
qa/

View file

@ -2,7 +2,7 @@
![CRTkafa inside the spiral](assets/cover.jpg)
**2:54 · Windows x64 · Direct3D 11**
**Windows x64 · Direct3D 11**
A standalone real-time demo. The music is synthesized as it runs;
shaders and model data are embedded in the executable.
@ -37,7 +37,7 @@ Release downloads are separate files, not a ZIP:
- **RUNME.txt** — controls, requirements and playback notes.
- **CREDITS.md** — model creators, licenses and modifications.
This repository contains release documentation. Source code is not included.
The C engine, HLSL shaders, synthesizer, score and baked model data are included.
Model data comes from the creators listed in [CREDITS.md](CREDITS.md);
please retain their attribution when redistributing.
@ -45,6 +45,34 @@ Release checks cover silent rendering, audio measurements and complete video
decoding. Interactive window/audio playback and a listening-based mix review
have not been verified.
## Build
Install Visual Studio with the **Desktop development with C++** workload and
a Windows SDK containing `fxc.exe`. Python 3 is needed only for score tools
and tests; video export also needs FFmpeg on `PATH`.
The build script checks the default Community-edition paths for Visual Studio
2022 and Visual Studio 18. For another edition or install location, update the
`VS` path near the top of `buildgfx.bat`.
```bat
buildgfx.bat
```
This compiles the shaders and produces `CRTkafa.exe`. Generated shader headers
are build outputs, not checked-in source. No downloaded models are needed to
build: the converted mesh tables are already included.
```bat
python -m unittest discover -s tools -p "test_*.py"
python tools/export_song.py --check
buildgfx.bat offline
```
`gfxoffline.exe` runs silent graphics tests and writes diagnostic frames.
`makevideo_gpu.bat` builds the video renderer and exports without playback.
The optional `tools/audio_audit.py` analyzer needs NumPy.
---
[crt.fyi](https://crt.fyi) · [hi@crt.fyi](mailto:hi@crt.fyi)

View file

@ -1,6 +1,6 @@
# crtkafa, cracktro #1
2:54. Windows x64. One executable.
Windows x64. One executable.
Download **CRTkafa.exe** directly; no ZIP or installation needed.

95
buildgfx.bat Normal file
View file

@ -0,0 +1,95 @@
@echo off
rem ---------------------------------------------------------------------------
rem D3D11 engine. Shaders are compiled here, at build time, and fxc writes
rem the C byte array itself (/Fh + /Vn) - so d3dcompiler_47.dll is never a
rem runtime dependency and there is no generator to maintain.
rem
rem buildgfx.bat release, windowed subsystem
rem buildgfx.bat offline no window, no sound: renders to bitmaps
rem ---------------------------------------------------------------------------
setlocal
cd /d "%~dp0"
set "VS=C:\Program Files\Microsoft Visual Studio\2022\Community"
if not exist "%VS%\VC\Auxiliary\Build\vcvars64.bat" set "VS=C:\Program Files\Microsoft Visual Studio\18\Community"
call "%VS%\VC\Auxiliary\Build\vcvars64.bat" >nul
set "FXC="
for /f "delims=" %%d in ('dir /b /ad /o-n "C:\Program Files (x86)\Windows Kits\10\bin\10.*" 2^>nul') do (
if not defined FXC if exist "C:\Program Files (x86)\Windows Kits\10\bin\%%d\x64\fxc.exe" set "FXC=C:\Program Files (x86)\Windows Kits\10\bin\%%d\x64\fxc.exe"
)
if not defined FXC ( echo [!] fxc.exe not found in the Windows SDK & exit /b 1 )
if not exist fx\out mkdir fx\out
rem /O3 optimises, /Ges enforces strict mode, /Qstrip_reflect and
rem /Qstrip_debug keep the blobs small - reflection data is dead weight in a
rem build that never queries it.
set "FXFLAGS=/nologo /O3 /Ges /Qstrip_reflect /Qstrip_debug"
echo [1/3] shaders
"%FXC%" %FXFLAGS% /T vs_5_0 /E main /Fh fx\out\fullscreen.h /Vn g_vsFullscreen fx\fullscreen.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T vs_5_0 /E main /Fh fx\out\mesh.h /Vn g_vsMeshBlob fx\mesh.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\meshps.h /Vn g_psMeshBlob fx\meshps.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\scene.h /Vn g_psSceneBlob fx\scene.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\logo.h /Vn g_psLogoBlob fx\logo.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\reactor.h /Vn g_psReactorBlob fx\reactor.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\orbital.h /Vn g_psOrbitalBlob fx\orbital.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\eye.h /Vn g_psEyeBlob fx\eye.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\void.h /Vn g_psVoidBlob fx\voidshot.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\horizon.h /Vn g_psHorizonBlob fx\horizon.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\kaleido.h /Vn g_psKaleidoBlob fx\kaleido.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\designframe.h /Vn g_psFramesBlob fx\designframe.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\plinths.h /Vn g_psPlinthBlob fx\plinths.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\drive.h /Vn g_psDriveBlob fx\drive.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\corridor.h /Vn g_psCorridorBlob fx\corridor.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\poweroff.h /Vn g_psPowerOffBlob fx\poweroff.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\burst.h /Vn g_psBurstBlob fx\burst.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\bloom.h /Vn g_psBloomBlob fx\bloom.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\c64.h /Vn g_psC64Blob fx\c64.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\signoff.h /Vn g_psSignBlob fx\signoff.hlsl || exit /b 1
"%FXC%" %FXFLAGS% /T ps_5_0 /E main /Fh fx\out\post.h /Vn g_psPostBlob fx\post.hlsl || exit /b 1
> shaders.h echo /* generated by buildgfx.bat - do not edit */
>> shaders.h echo #include "fx/out/fullscreen.h"
>> shaders.h echo #include "fx/out/mesh.h"
>> shaders.h echo #include "fx/out/meshps.h"
>> shaders.h echo #include "fx/out/scene.h"
>> shaders.h echo #include "fx/out/logo.h"
>> shaders.h echo #include "fx/out/reactor.h"
>> shaders.h echo #include "fx/out/orbital.h"
>> shaders.h echo #include "fx/out/eye.h"
>> shaders.h echo #include "fx/out/void.h"
>> shaders.h echo #include "fx/out/horizon.h"
>> shaders.h echo #include "fx/out/kaleido.h"
>> shaders.h echo #include "fx/out/designframe.h"
>> shaders.h echo #include "fx/out/plinths.h"
>> shaders.h echo #include "fx/out/drive.h"
>> shaders.h echo #include "fx/out/corridor.h"
>> shaders.h echo #include "fx/out/poweroff.h"
>> shaders.h echo #include "fx/out/burst.h"
>> shaders.h echo #include "fx/out/bloom.h"
>> shaders.h echo #include "fx/out/c64.h"
>> shaders.h echo #include "fx/out/signoff.h"
>> shaders.h echo #include "fx/out/post.h"
set "DEF="
set "SUB=WINDOWS"
set "OUT=CRTkafa.exe"
if /i "%~1"=="offline" ( set "DEF=/DOFFLINE" & set "SUB=WINDOWS" & set "OUT=gfxoffline.exe" )
if /i "%~1"=="video" ( set "DEF=/DVIDEO" & set "SUB=CONSOLE" & set "OUT=gfxvideo.exe" )
echo [2/3] compile
cl /nologo /c /O2 /Oi /GS- /fp:fast /std:c11 /W3 /wd4018 %DEF% /Fo:gfx.obj gfx.c || exit /b 1
echo [3/3] link
rem dxguid.lib is pure const GUID data with no CRT references, so it is safe
rem under /NODEFAULTLIB. d3d11.lib is deliberately NOT linked: the DLL is
rem resolved with LoadLibrary so a machine without it sees our message rather
rem than the loader's.
link /nologo /SUBSYSTEM:%SUB% /ENTRY:entry /NODEFAULTLIB /INCREMENTAL:NO ^
/OPT:REF /OPT:ICF ^
gfx.obj kernel32.lib user32.lib winmm.lib dxguid.lib /OUT:%OUT% || exit /b 1
for %%f in (%OUT%) do echo [ok] %%f = %%~zf bytes
for %%f in (fx\out\scene.h) do echo scene shader blob source = %%~zf bytes

54
c64_font.h Normal file
View file

@ -0,0 +1,54 @@
/* --------------------------------------------------------------------------
The boot screen, baked. Generated by tools/bake_font.py - do not edit.
THE TEXT IS THE AUTHOR'S. It is read out of g_boot[] in crtkafa.c at bake
time rather than retyped here, so it cannot drift from what they wrote.
The font is drawn in the baker rather than lifted from a ROM: a Commodore
character set is somebody's copyright, and an eight by eight uppercase
grid is a shape anyone may draw. It is that era without being a copy.
-------------------------------------------------------------------------- */
#define C64_COLS 40
#define C64_ROWS 16
#define C64_GLYPHS 47
/* two uints per glyph: rows 0-3 in the first, 4-7 in the second, eight bits
to a row, most significant bit leftmost */
static const unsigned int g_c64Font[] = {
0x00000000u, 0x00000000u, 0x3C66C3C3u, 0xFFC3C300u, 0xFCC6C6FCu, 0xC6C6FC00u, 0x3E63C0C0u, 0xC0633E00u,
0xF8CCC6C6u, 0xC6CCF800u, 0xFFC0C0FCu, 0xC0C0FF00u, 0xFFC0C0FCu, 0xC0C0C000u, 0x3E63C0CFu, 0xC3673E00u,
0xC3C3C3FFu, 0xC3C3C300u, 0x3C181818u, 0x18183C00u, 0x0F060606u, 0xC6C67C00u, 0xC3C6CCF8u, 0xCCC6C300u,
0xC0C0C0C0u, 0xC0C0FF00u, 0xC3E7FFDBu, 0xC3C3C300u, 0xC3E3F3DBu, 0xCFC7C300u, 0x3C66C3C3u, 0xC3663C00u,
0xFCC6C6FCu, 0xC0C0C000u, 0x3C66C3C3u, 0xDB663B00u, 0xFCC6C6FCu, 0xCCC6C300u, 0x3E63603Cu, 0x06C67C00u,
0xFF181818u, 0x18181800u, 0xC3C3C3C3u, 0xC3C37E00u, 0xC3C3C3C3u, 0x663C1800u, 0xC3C3C3DBu, 0xFFE7C300u,
0xC3663C18u, 0x3C66C300u, 0xC3663C18u, 0x18181800u, 0xFF03063Cu, 0x60C0FF00u, 0x3C66C7DBu, 0xE3663C00u,
0x18387818u, 0x18187E00u, 0x3C66061Cu, 0x3060FF00u, 0x3C66061Cu, 0x06663C00u, 0x0E1E3666u, 0xFF060600u,
0xFFC0FC06u, 0x06C67C00u, 0x3C66C0FCu, 0xC6C67C00u, 0xFFC60C18u, 0x30303000u, 0x3C66663Cu, 0x66663C00u,
0x3C66663Eu, 0x06663C00u, 0x00663CFFu, 0x3C660000u, 0x00000000u, 0x00181800u, 0x00000000u, 0x18183000u,
0x66666600u, 0x00000000u, 0x6666FF66u, 0xFF666600u, 0x00181800u, 0x18180000u, 0x000000FFu, 0x00000000u,
0x3C66DEDBu, 0xDE603E00u, 0x03060C18u, 0x3060C000u, 0x18181818u, 0x18001800u,
};
/* the screen: four cells to a uint, each an index into the font */
static const unsigned int g_c64Text[] = {
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x25252525u, 0x0D0F0300u, 0x0F040F0Du, 0x21000512u, 0x0102001Fu,
0x00030913u, 0x25001D16u, 0x00252525u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x0B1F2100u, 0x0D011200u,
0x13191300u, 0x000D0514u, 0x24231E00u, 0x02001C1Cu, 0x03091301u, 0x14190200u, 0x06001305u, 0x00050512u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x04010512u, 0x00002619u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x04010F0Cu, 0x12032800u, 0x06010B14u, 0x23272801u,
0x00001C27u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x12010513u, 0x0E090803u, 0x0F060007u, 0x12030012u, 0x06010B14u, 0x00000001u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x04010F0Cu, 0x00070E09u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x04010512u, 0x00002619u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x000E1512u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u,
};

3280
cats_mesh.h Normal file

File diff suppressed because it is too large Load diff

57
fx/bloom.hlsl Normal file
View file

@ -0,0 +1,57 @@
// Threshold/downsample -> bloom[0], vertical -> bloom[1], horizontal -> bloom[0].
// Blur offsets are half-resolution texels and are ONLY used on half-res inputs.
cbuffer Bloom : register(b0) { float4 gStep; float4 gParam; };
Texture2D gSrc : register(t0);
SamplerState gLin : register(s1);
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
static const float VOFF[2] = { 1.3730788, 3.2295113 };
static const float VW[2] = { 0.3171515, 0.0646567 };
static const float VC = 0.2363835;
static const float HOFF[4] = { 1.4415567, 3.3767077, 5.3550101, 7.3868203 };
static const float HW[4] = { 0.2503180, 0.1212263, 0.0394885, 0.0133097 };
static const float HC = 0.1513151;
float3 knee(float3 c)
{
c = min(max(c, 0.0), 32.0);
float l = max(c.r, max(c.g, c.b));
float t = gParam.x, k = max(gParam.y, 1e-4);
float s = clamp(l - t + k, 0.0, 2.0 * k);
s = s * s / (4.0 * k + 1e-6);
return c * (max(s, l - t) / max(l, 1e-4));
}
float3 brightPass(float2 uv)
{
// Threshold four full-res texel centres BEFORE averaging: retain thin light.
float2 d = gStep.xy * 0.5;
return (knee(gSrc.Sample(gLin, uv + float2(-d.x, -d.y)).rgb)
+ knee(gSrc.Sample(gLin, uv + float2( d.x, -d.y)).rgb)
+ knee(gSrc.Sample(gLin, uv + float2(-d.x, d.y)).rgb)
+ knee(gSrc.Sample(gLin, uv + float2( d.x, d.y)).rgb)) * 0.25;
}
float3 blurV(float2 uv)
{
float3 c = gSrc.Sample(gLin, uv).rgb * VC;
[unroll] for (int j = 0; j < 2; j++) {
float2 d = float2(0.0, VOFF[j] * gStep.y);
c += (gSrc.Sample(gLin, uv + d).rgb + gSrc.Sample(gLin, uv - d).rgb) * VW[j];
}
return c;
}
float3 blurH(float2 uv)
{
float3 c = gSrc.Sample(gLin, uv).rgb * HC;
[unroll] for (int j = 0; j < 4; j++) {
float2 d = float2(HOFF[j] * gStep.x, 0.0);
c += (gSrc.Sample(gLin, uv + d).rgb + gSrc.Sample(gLin, uv - d).rgb) * HW[j];
}
return c;
}
float4 main(VSOut i) : SV_Target
{
float3 c;
if (gParam.w < 0.5) c = brightPass(i.uv);
else if (gParam.w < 1.5) c = blurV(i.uv);
else c = blurH(i.uv);
return float4(c, 1.0);
}

668
fx/burst.hlsl Normal file
View file

@ -0,0 +1,668 @@
// THE BURST.
//
// The fastest passage in the demo, under the second solo. Matter tearing
// past the camera at a speed nothing else in the demo goes.
//
// What the viewer sees in the first half second: a black frame with the
// direction of travel somewhere in it, and everything else in the shot flying
// out of that point. Near it the particles are end-on and read as dots; the
// further from it they get the longer they stretch, until at the corners they
// are streaks a third of the screen long leaving frame. There is no lighting
// model here at all. Depth is carried entirely by brightness, because that is
// the only channel the ten step quantiser in the post pass still has left.
//
// gTune.x speed, world units per second. 40 is a drift, 130 is the solo.
// gTune.y density, 0..1 - how full the field is. 1 is as busy as this scene
// is allowed to get, not as busy as the lattice could be; see below.
// gTune.z colour temperature, 0 cold blue .. 0.5 amber .. 1 phosphor green
// gTune.w EXTRA flare at the vanishing point, 0..1.5, on top of the shot's
// own. Every burst row in the edit passes 0 here.
//
// ===========================================================================
// F I V E B U R S T S , N O T O N E B U R S T F I V E T I M E S
//
// The edit cuts here five times: bars 31, 45, 67, 73 and 78. Those rows
// differ only in speed (45, 90, 100, 110, 118), density (0.30 .. 0.42) and
// temperature - and post.hlsl regrades every frame through a per section
// palette, so temperature buys nothing at all. Speed alone is not a shot.
// Measured pairwise as luminance thumbnails, the five appearances were the
// most repetitive multi appearance scene in the demo: five near identical
// fields of streaks at five brightnesses.
//
// So the three knobs the table does vary are hashed into a SIGNATURE, and
// the signature decides what SHAPE the field is - not what colour it is.
// Five topologies, one per appearance as the table stands:
//
// OPEN the full isotropic field. The scene as it was.
// TUNNEL the throat is cleared. A dark aperture with a thin rim of
// light around it and the debris ripping past outside.
// SHEET the field collapses into one band through the axis: a bar of
// streaks across black, turning as the field rolls.
// ARMS three or six vanes, twisted along the depth axis, so the
// matter arrives in wedges with clean gaps between them.
// SHOAL occupancy clumped into blocks a dozen cells across and ten
// planes deep, which sweep past as gusts with holes in.
//
// Every appearance also gets its own roll rate and direction, its own drift
// of the vanishing point off frame centre, its own surge in the flow so a
// held shot is not a constant blur, its own lattice scale, streak length,
// streak width, hero/dust balance, and a shock ring on its own period that
// crosses the frame outward through the debris. Behind all of it, a fixed
// far field of pinpoints that does NOT flow, which is the only thing in a
// scene of streaks that can give it parallax.
//
// THE HASH IS NOT CHAINED. s2 is not hash(s1): four separate calls on four
// well conditioned inputs. Chaining costs everything - the last frac() in
// the hash works on products around 5000, which in fp32 leaves about 5e-4 of
// output precision, and feeding that back in amplifies it until the answer
// depends on the driver. Unchained, the fp32 and fp64 selectors agree to
// 4e-3 while the nearest shot sits 0.2 of a bucket from an edge, so which
// shape a row gets is a property of the row, not of the machine.
//
// Change a row in shots.h and that appearance is reshuffled to another
// shape. It is still a shape, and the five are still five pictures.
// ===========================================================================
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect (w/h)
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look direction, w roll
float4 gTune; // per shot knobs
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// ---- the signature, decoded once per pixel into these --------------------
// Per SHOT, not per pixel: every pixel derives the same values from the same
// gTune, so every branch on gMode below is uniform across the whole draw and
// costs a branch rather than a mask.
static int gMode; // 0 open, 1 tunnel, 2 sheet, 3 arms, 4 shoal
static float gCoreR; // TUNNEL: cleared radius, tan units
static float gSheetHW; // SHEET: half width of the band, tan units
static float2 gSheetN; // SHEET: band normal in the lattice frame
static float gTwist; // ARMS: radians of twist per world unit of depth
static float gArmPh; // ARMS: phase, spins over the shot
static float gArm6; // ARMS: 0 -> three vanes, 1 -> six
static float gBlockS; // SHOAL: 1/clump size across, in cells
static float gBlockZ; // SHOAL: 1/clump size along, in planes
static float gBlockT; // SHOAL: how much of the field a clump keeps
float sq(float x) { return x * x; }
// Hoskins' three-in three-out hash. No texture, and stable: a cell keeps the
// same particle for as long as it is on screen, which matters more than it
// sounds. A particle that re-rolls its seed does not move, it flickers, and
// against the ordered dither flicker turns into crawling grain.
float3 hash33(float3 p)
{
p = frac(p * float3(0.1031, 0.1030, 0.0973));
p += dot(p, p.yxz + 33.33);
return frac((p.xxy + p.yxx) * p.zyx);
}
// The palette knob. Three anchors, because these are the three the demo
// actually lives in: cold blue, warm amber, phosphor green.
float3 tempColour(float t)
{
float3 cold = float3(0.34, 0.62, 1.00);
float3 amber = float3(1.00, 0.66, 0.26);
float3 green = float3(0.36, 1.00, 0.48);
return t < 0.5 ? lerp(cold, amber, t * 2.0)
: lerp(amber, green, t * 2.0 - 1.0);
}
// Complex multiply, used to advance an angle without a transcendental.
float2 cmul(float2 a, float2 b)
{
return float2(a.x * b.x - a.y * b.y, a.y * b.x + a.x * b.y);
}
// ---------------------------------------------------------------------------
// W H A T S H A P E T H E F I E L D I S
//
// Asked once per cell per depth plane, BEFORE the cell is hashed, and from
// the cell's own centre rather than from the particle inside it. That
// ordering is the whole reason this is affordable: a cleared cell costs a
// dot product and returns, and never pays for the hash or the segment solve.
// SHEET throws away three quarters of the lattice, so at the shot level the
// shaped modes are CHEAPER than the open one, not dearer.
//
// The answer is a weight, not a yes. It multiplies the streak's amplitude,
// so a particle near the edge of the shape fades as the shape turns.
// Thresholding the occupancy instead would be cheaper and would pop: the
// cell hash is fixed, so a particle crossing the boundary would blink rather
// than dim, and forty of them blinking is the lattice announcing itself.
//
// `rot` is (cos, sin) of the ARMS phase at this depth, advanced by the
// caller with a complex multiply so the loop never touches a sine.
// ---------------------------------------------------------------------------
float fieldMask(float2 ci, float pn, float cell, float zc, float2 rot)
{
if (gMode == 0) return 1.0; // OPEN: the whole lattice
float2 cc = (ci + 0.5) * cell; // cell centre, camera space
float iz = 1.0 / zc; // ...read as an angle off axis
if (gMode == 1) // TUNNEL
return smoothstep(gCoreR * 0.42, gCoreR, length(cc) * iz);
if (gMode == 2) // SHEET
return 1.0 - smoothstep(gSheetHW * 0.52, gSheetHW,
abs(dot(cc, gSheetN)) * iz);
if (gMode == 3) // ARMS
{
// cos/sin of N.theta straight out of the cell direction. Chebyshev
// for three, one doubling for six. atan2 in here would be fifty
// transcendentals a pixel; this is four multiplies.
float2 d = cc * rsqrt(dot(cc, cc) + 1.0e-6);
float c3 = d.x * (4.0 * d.x * d.x - 3.0);
float s3 = d.y * (3.0 - 4.0 * d.y * d.y);
float ca = lerp(c3, 2.0 * c3 * c3 - 1.0, gArm6);
float sa = lerp(s3, 2.0 * s3 * c3, gArm6);
return smoothstep(-0.35, 0.40, ca * rot.x - sa * rot.y);
}
// SHOAL. A second hash on a COARSE index - twenty cells across, a dozen
// planes deep. Big and deep on purpose: a ray crosses thirty six cells,
// so clumps smaller than this average out along it and the shot looks
// exactly like the open field. The index is absolute - the plane NUMBER,
// not its depth - so the clumps are nailed to the field and sweep past
// the camera instead of sitting still in front of it.
float3 b = hash33(float3(floor(ci.x * gBlockS), floor(ci.y * gBlockS),
floor(pn * gBlockZ)) + 3.1);
return smoothstep(gBlockT, gBlockT + 0.35, b.x);
}
// ---------------------------------------------------------------------------
// ONE LATTICE OF STREAKS
//
// This is the whole trick, and it is the non-obvious part, so at length.
//
// There is no particle system. There is an infinite lattice of cells, each
// holding at most one particle at a hashed position inside itself, and the
// pixel shader asks: which of those particles does MY ray pass close to?
//
// Everything below is in the camera's own frame - x right, y up, z forward -
// so the ray starts at the origin and the camera's motion is straight down
// +z. That choice is what nails the expansion centre to the direction of
// travel, which is the whole composition. Main tilts that frame off the
// optical axis before handing it over, which is how the vanishing point gets
// to sit somewhere other than the middle of the picture.
//
// Cells are addressed as (lateral cell, depth plane). Depth planes sit every
// `cell` units along z and slide towards the camera as `flow` grows, so the
// particles are what is standing still and the camera is what is moving -
// which is also why the lattice never has to be updated or stored.
//
// The ray crosses each depth plane at exactly one point, so there is a
// single lateral cell per plane to test, and the loop is one particle per
// step with no traversal and no misses. That is the reason for slicing the
// grid into planes rather than marching it: a fixed step through a 3D grid
// skips cells and visits others twice.
//
// A STREAK, not a point. During the time the shutter is open the camera
// travels forward, so relative to the camera the particle sweeps a segment -
// and since the camera only moves along +z, that segment runs from the
// particle straight out along +z, away from us, for `len` units. Projected,
// that is a line pointing back at the vanishing point, which is exactly what
// a radial motion streak looks like. So the shading question is the distance
// from the view ray to a segment, in closed form:
//
// ray P(s) = e * s e unit, s >= 0
// streak Q(u) = (px, py, z0 + u) u in [0, len]
//
// Setting the connecting vector perpendicular to both and using the fact
// that the segment is axis aligned along z, nearly all of the usual algebra
// cancels and the closest point on the streak is just
//
// u = e.z * (e.x*px + e.y*py) / (e.x^2 + e.y^2) - z0
//
// clamped to [0, len]. The closest point on the ray is then the projection
// of Q(u) onto e, and the distance between the two falls straight out.
// ---------------------------------------------------------------------------
// One cell, tested. Split out of the loop because the wide layer walks four
// cells per plane and this is the part that gets done four times.
// Returns (energy, the part of that energy that came from close in).
float2 streakAt(float3 e, float2 ci, float pn, float cell, float len,
float invLen, float wide, float dens, float3 sofs,
float zc, float zf, float g, float mk)
{
float3 h = hash33(float3(ci.x, ci.y, pn) + sofs);
// Two more decorrelated numbers out of the same hash, which is a lot
// cheaper than hashing twice and plenty for a field this busy.
float r1 = frac(h.x * 57.31 + h.z * 13.77); // occupancy roll
float r2 = frac(h.y * 91.73 + h.x * 29.31); // size and brightness
if (r1 > dens) return float2(0.0, 0.0); // this cell is empty
// The particle inside its cell. Kept clear of the cell wall: a particle
// sitting on a wall would pop in and out as the ray crossed it. 0.62 of a
// cell of travel leaves a margin wider than the streak everywhere the far
// fade has not already taken the streak to nothing.
float2 pxy = (ci + 0.5 + (h.xy - 0.5) * 0.62) * cell;
// Depth is jittered across a whole cell, not part of one. At less than
// that the planes still show: the first render of this scene had visible
// horizontal rows of dashes across the middle of frame, which is the
// lattice announcing itself. The floor of a third of a unit is not
// cosmetic - at zero depth the closest point on the ray is the camera
// itself, every pixel gets the same distance, and one particle flashes
// the entire frame white.
float z0 = max(zc + (h.z - 0.5) * cell, 0.33);
// ---- nearest approach of the ray to this streak ---------------------
float m = e.x * pxy.x + e.y * pxy.y;
float u = clamp(e.z * m / g - z0, 0.0, len);
float s = max(m + e.z * (z0 + u), 0.02);
float3 d = float3(e.x * s - pxy.x, e.y * s - pxy.y, e.z * s - z0 - u);
float d2 = dot(d, d);
// Width is an ANGLE, not a world size: the radius grows with distance so
// every streak is the same handful of pixels wide wherever it is. At 640
// x360 a streak thinner than a pixel does not get thinner, it gets noisy,
// and the dither turns that noise into crawling grain. `wide` is a half
// width in radians; at fov 0.62 the two layers come out 2.8 and 2.3
// pixels wide at half maximum, which is the floor for a 360 line frame
// that then goes through a CRT resample.
float rw = wide * max(s, 0.4);
float w = rw * rw / (d2 + rw * rw);
w *= w; // solid core, fast edge
// Nothing here is lit, so brightness is the only thing separating near
// from far, and it has to survive ten quantiser steps - hence a steep
// falloff and a short near fade rather than anything physical.
float t01 = saturate(z0 / zf);
float fade = (1.0 - t01 * t01) * smoothstep(0.30, 1.60, z0);
// A streak has a head and a tail. u = 0 is where the particle is now,
// u = len is where it was when the shutter opened, so the energy has to
// fall off along the trail - otherwise a corner streak is a uniform bar
// as bright at its far end as at its head, the value structure goes flat
// exactly where the composition wants it steepest, and the ends terminate
// on a hard edge instead of dissolving.
float tail = 1.0 - 0.62 * u * invLen;
// r2 SQUARED, so most streaks are dim and a few are hero bright. A flat
// spread of brightnesses quantises into one grey band and the whole frame
// turns into television snow; this keeps a handful of streaks up at the
// top of the ramp with darkness between them.
// mk SQUARED for the same reason it exists: the shape's edge wants to be
// narrow in the picture even though it has to be wide in the maths to
// stay pop free, and squaring buys that for one multiply.
float amp = (0.14 + 0.86 * r2 * r2) * fade * tail * mk * mk;
return float2(w * amp, w * amp * (1.0 - t01));
}
float2 streakLayer(float3 e, float cell, float flow, int slabs, float len,
float wide, float dens, float seed, bool pair)
{
// Streak length is capped against the CELL. A streak is only ever found
// by rays whose cell is the streak's own cell at one of the depths tested
// below; let it run much longer than the span those cover and the middle
// of every long streak falls in cells nobody looks at, and the field
// turns into rows of dashes with holes in.
len = min(len, cell * (pair ? 1.35 : 0.95));
// e.x^2 + e.y^2, since e is unit. It is zero only for the ray that goes
// exactly down the axis, and the guard keeps that one pixel finite - the
// clamp on u does the rest.
float g = max(1.0 - e.z * e.z, 1.0e-4);
float ez = max(e.z, 1.0e-3);
float zf = float(slabs) * cell; // far plane of this lattice
float rc = 1.0 / cell;
float invL = 1.0 / max(len, 1.0e-3);
float3 sofs = float3(seed, seed * 1.7, seed * 0.3);
// Where the lattice sits right now. n0 is the ABSOLUTE index of the first
// plane in front of the camera, and carrying it into the hash is what
// stops the entire field re-rolling every time a plane passes. Without it
// the shot strobes at the plane crossing rate, which at these speeds is
// about fifteen times a second.
float fz = flow / cell;
float n0 = floor(fz);
float ph = fz - n0;
// ARMS advances its phase one step per depth plane and one third of a
// streak per walk step. Angle addition by complex multiply, seeded by two
// sincos outside the loop, so a twisted field costs six multiplies a
// plane instead of two sines a plane.
float2 rot = float2(1.0, 0.0);
float2 drot = float2(1.0, 0.0); // one plane
float2 qrot = float2(1.0, 0.0); // one third of a streak
if (gMode == 3)
{
sincos(gTwist * ((1.0 - ph) * cell) + gArmPh, rot.y, rot.x);
sincos(gTwist * cell, drot.y, drot.x);
sincos(gTwist * len * (1.0 / 3.0), qrot.y, qrot.x);
}
float2 acc = float2(0.0, 0.0);
// [loop], never [unroll]: `slabs` is a literal at both call sites, so an
// unrolled body would be 36 copies of the body in the blob.
[loop] for (int k = 0; k < slabs; k++)
{
// Depth of this plane in camera space. (1 - ph) slides the whole set
// towards us as flow grows; k pushes it out towards the far plane.
float zc = (float(k) + 1.0 - ph) * cell;
float pn = n0 + float(k);
// The lateral cell the ray is inside when it crosses that plane.
float2 ci = floor(e.xy * (zc / ez) * rc);
float mk = fieldMask(ci, pn, cell, zc, rot);
if (mk > 0.06)
acc += streakAt(e, ci, pn, cell, len, invL, wide, dens, sofs,
zc, zf, g, mk);
// ONE CELL PER PLANE IS NOT ENOUGH FOR THE LONG ONES.
//
// A streak is only ever found by the rays whose cell at `zc` is the
// streak's own cell, so it is visible only inside the screen space
// footprint of that cell - roughly cell/zc radians across, the same
// angular size everywhere. Its projected LENGTH, on the other hand,
// grows with distance from the vanishing point: about tan(theta)
// times len/cell cells. Dead centre that is nothing. At the corner of
// a 0.8 lens it is close to two cells, and with the vanishing point
// pushed off centre it is three - so the middle of every corner
// streak was landing in cells nobody tested. That is what the blocky
// shearing in the corners of the old renders was: not aliasing, whole
// streaks chopped into dashes, and chopped at the same radius for
// every cell, which puts a ring of streak-ends through the frame.
//
// So walk the streak instead of sampling its ends: quarter steps from
// head to tail, each one skipped when it lands in a cell already
// done, which over most of the frame is all of them. The branch pays
// for itself everywhere the streaks are short, and the corners - the
// part of the frame this whole scene exists for - stop shearing.
if (pair)
{
float2 ca = ci, cb = ci;
float2 rq = rot;
[unroll] for (int q = 1; q <= 3; q++)
{
float zq = zc + len * (float(q) * (1.0 / 3.0));
float2 cq = floor(e.xy * (zq / ez) * rc);
rq = cmul(rq, qrot);
if ((cq.x != ci.x || cq.y != ci.y) &&
(cq.x != ca.x || cq.y != ca.y) &&
(cq.x != cb.x || cq.y != cb.y))
{
float mq = fieldMask(cq, pn, cell, zq, rq);
if (mq > 0.06)
acc += streakAt(e, cq, pn, cell, len, invL, wide,
dens, sofs, zc, zf, g, mq);
}
cb = ca; ca = cq;
}
}
if (gMode == 3) rot = cmul(rot, drot);
}
return acc;
}
float4 main(VSOut i) : SV_Target
{
float2 uv = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y is FLIPPED here on purpose. The fullscreen triangle emits
// uv.y = 0 at the top of the screen, so i.uv*2-1 gives -1 up
// there and the top of the frame ended up looking DOWNWARD -
// the cathedral vault springs at y=+12 and was rendering in the
// lower half, the monolith hung from the ceiling.
uv.x *= gTime.w;
// The standard setup, so this scene frames identically to every other
// one. The world-up fallback is not decoration: CAM_CRANE rows aim very
// close to straight up, and cross((0,1,0), fw) is the zero vector there,
// which normalize() turns into NaN and NaN painted over the whole frame.
float3 fw = normalize(gDir.xyz);
float3 wup = abs(fw.y) > 0.999 ? float3(0.0, 0.0, 1.0) : float3(0.0, 1.0, 0.0);
float3 rt = normalize(cross(wup, fw));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 rx = rt * cr + up * sr;
float3 ry = up * cr - rt * sr;
float3 rd = normalize(fw + (uv.x * rx + uv.y * ry) * gCam.w);
// Straight back into the camera frame, because that is where the lattice
// lives. (rx, ry, fw) is orthonormal and rd is unit, so e is unit too.
// gCam.xyz never appears: the field is defined relative to the camera on
// purpose, so that a shot can orbit or roll through the burst without the
// expansion centre sliding off the direction it is travelling in.
float3 e = float3(dot(rd, rx), dot(rd, ry), dot(rd, fw));
float speed = max(gTune.x, 0.0);
float flare = max(gTune.w, 0.0);
float t = gTime.x;
// ---- T H E S H O T S I G N A T U R E ----------------------------
// Twelve decorrelated numbers out of the three knobs that actually differ
// between the five appearances. Four separate hashes, never fed into each
// other - see the note at the top of the file. All of it is per shot, so
// every branch below is uniform over the draw.
float3 kk = float3(gTune.x * 0.089, gTune.y * 11.90, gTune.z * 2.30);
float3 s1 = hash33(kk + 1.7);
float3 s2 = hash33(kk.yzx * 2.11 + 5.9);
float3 s3 = hash33(kk.zxy * 1.37 + 11.7);
float3 s4 = hash33(kk * 0.83 + 41.3);
gMode = (int)min(4.0, floor(s1.x * 5.0));
// How much of the lattice each shape throws away, put back so a shaped
// shot is not simply an emptier one. Not a full area compensation - the
// black a shape makes IS the composition and must not be filled in. This
// restores the density INSIDE the shape to about what the open field has,
// measured off the mean of the mask over a frame.
float densK = 1.00;
if (gMode == 1) densK = 1.10;
if (gMode == 2) densK = 2.15;
if (gMode == 3) densK = 1.25;
if (gMode == 4) densK = 1.90;
gCoreR = (0.24 + 0.26 * s2.y) * gCam.w;
gSheetHW = (0.34 + 0.34 * s2.y) * gCam.w;
float sang = s4.z * 3.14159;
gSheetN = float2(cos(sang), sin(sang));
float tw = (s4.z - 0.5) * 0.40;
gTwist = tw < 0.0 ? min(tw, -0.022) : max(tw, 0.022);
gArmPh = t * (s3.y - 0.5) * 2.20;
gArm6 = s4.y > 0.5 ? 1.0 : 0.0;
gBlockS = 0.05 + 0.05 * s4.x;
gBlockZ = 0.06 + 0.06 * s4.y;
gBlockT = 0.20 + 0.20 * s4.y;
// A directional shape has to TURN or it is wallpaper, so SHEET and ARMS
// get a floor under the roll rate; the isotropic shapes do not need one
// and a rolling isotropic field looks identical to a still one anyway.
float roll = (s4.z - 0.5) * 1.60;
if (gMode == 2 || gMode == 3) roll += roll < 0.0 ? -0.30 : 0.30;
float tiltAmp = 0.05 + 0.11 * s2.y; // rad off the optical axis
float tiltRate = 0.30 + 0.70 * s1.z;
float lenMul = 0.55 + 1.10 * s3.x;
float cellMul = 0.80 + 0.55 * s3.y;
float wideMul = 0.80 + 0.55 * s2.z;
float heroW = 0.62 + 0.42 * s2.x;
float dustW = 0.50 + 0.62 * s4.x;
float surgeA = 0.18 + 0.50 * s3.z;
float surgeW = 2.00 + 4.20 * s4.y;
float ringAmp = 0.22 + 0.40 * s1.y;
float ringRate = 0.45 + 0.95 * s4.z;
float starW = 0.30 + 0.70 * s1.z;
float glow = 0.05 + 0.10 * s3.z;
// ---- W H E R E T H E V A N I S H I N G P O I N T S I T S ----
// The lattice frame is tilted off the optical axis and rolled about it.
// Both are exact rotations, so e stays unit and every line of the solve
// is untouched - but the expansion centre moves off the middle of the
// picture and wanders, and the whole field turns. Three sincos for the
// frame, and it is the single biggest difference between two appearances.
//
// The tilt is capped at 0.16 rad and that ceiling is load bearing. Push
// the vanishing point further and the far corner passes 70 degrees off
// axis, where a streak projects longer than the four cells the walk in
// streakLayer covers and the corner shears into dashes again. Measured:
// at 0.32 rad the pairwise spread between the five appearances is a fifth
// better and two of them have a broken corner, which is not a trade.
float ax = cos(t * tiltRate + s1.y * 6.2832) * tiltAmp;
float ay = sin(t * tiltRate * 0.73 + 1.7) * tiltAmp;
float cy, sy, cp, sp, cz, sz;
sincos(ax, sy, cy);
sincos(ay, sp, cp);
sincos(t * roll, sz, cz);
float3 e1 = float3(cy * e.x - sy * e.z, e.y, sy * e.x + cy * e.z);
float3 e2 = float3(e1.x, cp * e1.y - sp * e1.z, sp * e1.y + cp * e1.z);
e = float3(cz * e2.x - sz * e2.y, sz * e2.x + cz * e2.y, e2.z);
// ---- H O W F A S T , A N D H O W S T E A D I L Y ------------
// How far the camera has flown since the shot began. The scene owns its
// own speed instead of reading it off the shot's camera, because the
// burst wants a hundred units a second while the camera itself barely
// moves. If they were the same number the shot would have to fly a
// kilometre and every `at` in the row would be nonsense.
// gTime.x must be SHOT time, not song time: n0 is floor(flow/cell), and
// at song time with speed 130 that index is in the thousands, where the
// hash starts to lose its low bits.
//
// Not linear any more. This is the integral of speed*(1 + A sin(Wt)), so
// the field surges and eases instead of running at one rate for the whole
// shot - two bars of a constant blur is a still frame with noise on it.
// A is well under one, so the derivative never goes negative and nothing
// ever runs backwards. The solo envelope shoves a unit or so on top, far
// too small against a hundred a second to reverse anything.
float flow = speed * (t + surgeA * (1.0 - cos(surgeW * t)) / surgeW)
+ gVoice.y * 1.2;
// Streak length is the shutter, exaggerated. The layers clamp it against
// their own cell size; this is the shot's taste in it - dashes at one end
// of the knob, threads at the other - and the solo stretches it.
float baseLen = clamp(speed * 0.032, 0.40, 4.40);
float len = baseLen * lenMul * (1.0 + 0.18 * gVoice.y);
// Distance from the direction of travel, 0 at the vanishing point and 1
// at the top and bottom of frame. Measured against the TILTED axis, so
// the flare and the shock ring stay concentric with the burst wherever
// the burst has drifted to.
float rn = length(e.xy / max(e.z, 1.0e-3)) / max(gCam.w, 1.0e-3);
float rr = rn * rn;
// Two lattices, not one. A single grid at a single scale reads as a grid.
// A coarse one carrying long bright streaks and a fine one carrying dust
// gives the frame a bold shape with a texture under it, and bold shape
// plus texture is the only thing that survives being dithered into ten
// levels at 360 lines.
// The occupancy the knob asks for is scaled well down, because the useful
// range turned out to be far narrower than 0..1: a quarter of the cells
// carrying a particle already fills the frame, and a field with no black
// in it has no streaks in it either, only texture.
// cellMul moves BOTH lattices together, so one appearance is a coarse
// field of big slow slabs of matter and another is fine grit.
float hc = 3.40 * cellMul;
float dc = 1.75 * cellMul;
// HOW MUCH INK IS ON THE FRAME, held roughly where the shot table asked.
// Coverage per plane goes as wide * len / cell, so the three knobs above
// do not just change the SCALE of the streaks, they change how full the
// frame is - and left alone they compound: the appearance that happened
// to draw a fine lattice with long fat streaks came out twice as bright
// as the row asked for, milky instead of streaks on black. The square
// root is deliberate and is not a rounding: correct it fully and every
// appearance sits at the same exposure, which throws away variation the
// edit wants; correct it not at all and one of the five washes out. Half
// leaves gTune.y in charge of fullness and lets the lattice be felt.
float inkK = wideMul * (min(len, hc * 1.35) / baseLen) / cellMul;
float dens = saturate(gTune.y * densK / sqrt(max(inkK, 0.35)));
float2 hero = streakLayer(e, hc, flow, 20, len,
0.0076 * wideMul, dens * 0.28, 0.0, true);
float2 dust = streakLayer(e, dc, flow, 16, len * 0.35,
0.0062 * wideMul, dens * 0.22, 37.0, false);
float3 tint = tempColour(saturate(gTune.z));
float3 hot = float3(1.00, 0.94, 0.86);
// Near black, slightly blue, so the darkest thing on screen is still the
// demo's black and not a hole.
float3 col = float3(0.010, 0.012, 0.024);
// ---- T H E S H O C K R I N G ------------------------------------
// A ring of extra energy born at the vanishing point and swept out past
// the corners on its own period, brightening the debris it crosses. It is
// multiplicative on a base of one, and it is a ring rather than a frame,
// so the floor never moves and no more than a fifth of the picture is
// lifted at once - a wave through the field, not a flash. Born and killed
// at zero by the sine, because a ring that appeared at full strength on
// the flare would be exactly the pop this is avoiding.
float rp = frac(t * ringRate);
float ring = exp(-sq(rn - rp * 2.40) * 22.0) * sin(rp * 3.14159);
float lift = 1.0 + ringAmp * ring;
// Streaks that came from close in go white hot while distant ones keep
// the tint - acc.y is the share of the energy that arrived from near, so
// the ratio is the mix, per pixel, for free. The bias on that ratio is
// there because the near streaks dominate almost every pixel: mapped
// straight, the whole frame went white and the temperature knob did
// nothing at all.
// The two layers carry their own weights now, so one appearance is a
// handful of big threads over black and another is a sandstorm. Both
// audio terms are base + k*s and never scale the frame: the floor holds.
float heroA = heroW * lift * (1.0 + 0.22 * gSync.x);
float dustA = dustW * lift * (1.0 + 0.45 * gSync.z);
col += hero.x * lerp(tint, hot, saturate(hero.y / max(hero.x, 1.0e-4) * 1.5 - 0.45)) * 1.75 * heroA;
col += dust.x * lerp(tint, hot, 0.20) * 0.26 * dustA;
// ---- T H E F A R F I E L D --------------------------------------
// Pinpoints locked to the lattice frame rather than flowing through it.
// One hash, no loop, and they buy the one thing a field of streaks cannot
// give itself: parallax. Everything else in the shot is ripping past;
// these barely move, and that is what says the streaks are near rather
// than merely fast. base + k*high, so the hats shimmer them without ever
// taking them out.
float2 sptr = e.xy / max(e.z, 0.25) * 7.0;
float2 scel = floor(sptr);
float3 hs = hash33(float3(scel, 11.0));
float2 sd = sptr - scel - 0.15 - hs.xy * 0.70;
float star = exp(-dot(sd, sd) * 260.0) * step(hs.z, 0.30);
col += lerp(tint, hot, 0.45) * star * starW * 0.36 * (0.55 + 0.45 * gSync.z);
// ---- T H E L I G H T ----------------------------------------------
// Everything in frame is coming out of one point, so that point is the
// only thing in the shot allowed to blow out. It is a hard core and
// nothing else: the wide bloom that used to sit under it is driven by
// gTune.w alone, which every burst row in the edit sets to zero, and
// adding one back lifted the black off the middle third of the frame and
// turned the scene from streaks on black into a smudge. So the shot's own
// flare is small and tight - an anchor for the eye, about twenty pixels
// across, not a light source.
// In TUNNEL it is tighter still and the throat gets a thin rim, so the
// cleared centre reads as a shaft with something at the end of it rather
// than as a hole somebody forgot to fill.
float tight = gMode == 1 ? 210.0 : 130.0;
col += tint * exp(-rr * 10.0) * 0.40 * flare;
col += hot * exp(-rr * tight) * 0.85 * (flare + glow * (1.0 + 0.25 * gSync.w));
if (gMode == 1)
col += tint * 0.08 * exp(-sq(rn - gCoreR / max(gCam.w, 1.0e-3)) * 190.0)
* (0.70 + 0.50 * gSync.y);
// Shot fade only. No dither, no scanlines, no ramp, no exposure, no
// tonemap: post.hlsl owns every one of those and doing any of it twice
// is how the quantiser ends up with five usable steps instead of ten.
return float4(col * gTime.z, 1.0);
}

324
fx/c64.hlsl Normal file
View file

@ -0,0 +1,324 @@
// The boot screen, in the middle of the demo.
//
// It was at the START once, and the author cut it: fourteen seconds of text
// before anything happens is a bad opening. But the breakdown at bar 53 is
// the middle of the piece both by the clock and by the form, and a half-time
// bar is exactly where a demo can afford to stop and be a computer for a
// moment. So it lives there now, and it is over in four bars.
//
// The text is theirs, baked out of crtkafa.c by tools/bake_font.py rather
// than retyped, so it cannot drift from what they wrote. NOTHING in here
// touches a word or an order of it. Everything below is about the MACHINE
// the words are printed on: how far the boot has got, what the drive is
// doing, whether the tube has warmed up, and who owns the raster.
//
// The scene is cut TWICE, at bar 53 and bar 55, and the shot table hands the
// second one a later boot than the first. So the two appearances are not two
// looks at the same screen - they are one boot, continued. The first takes
// the machine from a cold tube to the middle of a load. The second picks up
// exactly where that left off, watches READY. and RUN arrive, and then hands
// the raster over to the program, which is the shot the dissolve into the
// corridor is cut against.
//
// gTune.x the progress the boot has reached by the END of this shot, 0..1.
// The shot animates INTO it from x - BOOT_STEP, so consecutive
// entries in the table chain rather than repeat. Line arrival is on
// the schedule below, which is the author's own g_bootAt.
// gTune.y screen brightness
// gTune.z barrel of the tube's own curvature, on top of the post pass
// gTune.w tube age: extra warm-up droop and roll that never quite settles.
// 0 is a healthy set, and both current shots are healthy.
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
// b1, uploaded once and never touched again - b0 is rewritten every frame for
// every shot and this has no business being in it.
cbuffer Font : register(b1)
{
uint4 gFont[24]; // 47 glyphs x 2 uints, padded to float4 rows
uint4 gText[40]; // 40x16 cells, four to a uint
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
#define COLS 40
#define ROWS 16
// How much of the whole boot one shot of this scene gets through. It is the
// gap between the two gTune.x values in shots.h (0.55 and 1.00) written down
// once, so a shot starts where the shot before it stopped.
#define BOOT_STEP 0.45
// How long a shot takes to travel that distance, in seconds. Shorter than
// either shot on purpose: the boot finishes and the picture then SITS in the
// state it reached, which is what gives the second appearance its handover.
#define BOOT_SPAN 2.2
// When each line arrives, as a fraction of the whole boot. This is the same
// schedule as g_bootAt[] in crtkafa.c - the author's pacing, not mine - kept
// in step by hand because a shader cannot read that array. Rows past the end
// of the text never arrive.
static const float kBootAt[16] = {
0.02, 0.02, 0.02, 0.02, 0.02, 0.02, // the banner, up the instant it is on
0.14, 0.14, // LOAD, typed
0.22, // SEARCHING
0.32, // LOADING - and then the long wait
0.74, // READY.
0.86, // RUN
9.0, 9.0, 9.0, 9.0 // blank glass
};
uint cellAt(uint col, uint row)
{
uint i = row * COLS + col; // which cell
uint w = i >> 2; // which uint
uint b = (i & 3u) * 8u; // which byte in it
uint v = gText[w >> 2][w & 3u];
return (v >> b) & 0xFFu;
}
bool glyphBit(uint gi, uint x, uint y)
{
uint w = gi * 2u + (y >> 2); // rows 0-3 in the first uint, 4-7 in the second
uint v = gFont[w >> 2][w & 3u];
uint row = (v >> (8u * (3u - (y & 3u)))) & 0xFFu;
return ((row >> (7u - x)) & 1u) != 0u;
}
float hash1(float n)
{
return frac(sin(n * 91.3458) * 47453.5453);
}
float4 bootRaster(VSOut i)
{
float t = gTime.x;
// ---- where the boot has got to ------------------------------------
// One clock for the whole scene. Everything else - the drive, the tube,
// the cursor, the margin, who owns the raster - is read off it, so a
// shot handed a different gTune.x is a different picture and not a
// different colour.
float pEnd = saturate(gTune.x);
float pStart = pEnd - BOOT_STEP;
float u = saturate(t / BOOT_SPAN);
float p = lerp(pStart, pEnd, u);
float age = saturate(gTune.w);
// A set that has only just been switched on. True of the first shot,
// false of the second, because the second starts halfway through a load.
float cold = saturate(1.0 - pStart * 2.2);
float warm = saturate(cold * saturate(1.0 - u * 0.9) + age * 0.55);
// The drive is working between SEARCHING and READY. - which is most of
// the first appearance and only the head of the second.
float load = saturate((p - 0.19) * 22.0) * saturate((0.74 - p) * 16.0);
// RUN is away and the program has the machine.
float ran = saturate((p - 0.90) * 10.0);
// ---- the glass ----------------------------------------------------
float2 uv = i.uv;
// A raster line stolen by the drive comes out short. Coherent per line
// and only while the drive is actually turning.
float ln = floor(uv.y * 240.0);
float torn = hash1(ln * 3.13 + floor(t * 24.0) * 71.7);
float tear = (torn > 0.962) ? (hash1(ln + 5.0) - 0.5) * 0.030 : 0.0;
float2 c = uv - 0.5;
// The tube's own curvature, under the post pass. Zero is flat.
c *= 1.0 + gTune.z * dot(c, c) * 2.0;
// The yoke is cold, so the raster starts short and creeps out to size;
// the high tension sags on the bass and the picture breathes wider with
// it. Geometry, not brightness - none of this touches the floor.
float squeeze = 1.0 - 0.34 * warm;
float sag = 1.0 + 0.012 * gSync.x;
float rattle = load * (0.0016 * sin(t * 61.0) + 0.0009 * sin(t * 23.7));
c.x = c.x / sag + rattle + tear * load;
c.y = c.y / squeeze;
uv = c + 0.5;
// The raster grows into the tube as the machine settles: a screen that
// has just come up sits in a fat margin, and a screen about to hand over
// to a demo does not. This is the difference you see first.
float mgn = lerp(0.150, 0.048, saturate(p));
mgn = lerp(mgn, 0.016, ran); // and the program goes for the edges
float2 m = float2(mgn, mgn * 1.10);
float2 in01 = (uv - m) / (1.0 - 2.0 * m);
float3 border = float3(0.24, 0.22, 0.62);
float3 paper = float3(0.16, 0.14, 0.50);
float3 ink = float3(0.62, 0.60, 0.94);
// ---- the border ---------------------------------------------------
// A fastloader talks to the drive by writing the border register every
// few raster lines, so a machine that is LOADING wears bands and a
// machine that is not wears none. They scroll rather than blink: the
// mean over the border never moves, which is the only honest way to do
// this. The high band nudges the phase, not the level.
float3 col;
{
float band = floor(uv.y * 34.0 - t * 9.0 - gSync.z * 1.6);
float k = 0.74 + 0.58 * hash1(band);
float3 hue = float3(0.86 + 0.32 * hash1(band + 7.0),
0.82 + 0.28 * hash1(band + 19.0),
1.00);
col = lerp(border, border * k * hue, load);
}
// Once RUN is away the program owns the border too, and the first thing
// any of them ever did was make it agree with the screen.
col = lerp(col, paper, ran * 0.92);
// ---- the screen ---------------------------------------------------
if (all(in01 >= 0.0) && all(in01 < 1.0))
{
col = paper;
float2 cell = in01 * float2(COLS, ROWS);
uint cx = (uint)cell.x;
uint glass= (uint)cell.y; // the row on the tube
float2 f = frac(cell);
uint px = (uint)(f.x * 8.0);
uint py = (uint)(f.y * 8.0);
// The program starts printing and the terminal scrolls what was
// there off the top, a whole line at a time the way it must.
uint cy = glass + (uint)floor(ran * 3.0);
// The reveal is per LINE, not per character: this machine printed a
// line at a time and a per-character crawl would be a different
// decade's idea of a computer. A line that has only just landed
// still has the beam's heat in it for a moment.
if (cy < (uint)ROWS)
{
float thr = kBootAt[cy];
uint gi = cellAt(cx, cy);
if (p >= thr && gi != 0u && glyphBit(gi, px, py))
{
float fresh = saturate(1.0 - (p - thr) * 14.0);
col = ink * (1.0 + 0.45 * fresh);
}
}
// The cursor sits at the head of the first line that has not arrived
// and blinks on the demo's own clock rather than on a wall clock - a
// blink that ignores the music is a screensaver. While the drive is
// turning the machine is not listening, so it stops blinking and
// just sits there; once RUN is away there is no cursor at all,
// because the cursor belongs to BASIC and BASIC is no longer here.
{
uint cur = 0u;
[unroll] for (uint r = 0u; r < (uint)ROWS; r++)
if (kBootAt[r] <= p) cur = r + 1u;
float blink = frac(t * 1.7) < 0.55 ? 1.0 : 0.0;
float on = lerp(blink, 1.0, load) * (1.0 - ran);
if (cy == cur && cx == 0u && on > 0.5) col = ink;
}
}
// Phosphor bloom around the lit cells, cheap: the border picks up a
// little of the paper colour near the edge of the text box.
{
float2 d = abs(in01 - 0.5) - 0.5;
float e = length(max(d, 0.0));
col += paper * 0.35 * exp(-e * 26.0);
}
// The frame a cold set has not locked yet: the seam walks down the tube
// and stops walking once the machine is warm. A moving band, never a
// flashing one - the mean barely moves, and the floor never drops out.
//
// No scanlines here on purpose. The post pass owns those and draws them
// in virtual space; a second set drawn in this one would beat against
// them.
{
float rb = frac(uv.y + t * (0.11 + 0.25 * age));
float x0 = (rb - 0.50) * 16.0;
float x1 = (rb - 0.58) * 44.0;
col *= 1.0 + (0.26 * exp(-x0 * x0) - 0.11 * exp(-x1 * x1)) * warm;
}
// The program is writing to the screen faster than the beam can get off
// it, and the beam shows it. Only after RUN, so it is the second
// appearance's alone.
{
float hb = 0.5 + 0.5 * sin(uv.y * 62.0 + t * 26.0);
col *= 1.0 + 0.15 * hb * ran;
}
col *= gTune.y;
// A cold cathode does not emit. It comes up, it does not flash up.
col *= 1.0 - 0.20 * warm;
// The whole tube is very slightly brighter when the organ is holding a
// chord - the same mains that runs the machine runs the amplifier.
col *= 1.0 + gVoice.z * 0.05;
return float4(col * gTime.z, 1.0);
}
float caseBox(float3 p, float3 b) {
float3 q=abs(p)-b;
return length(max(q,0))+min(max(q.x,max(q.y,q.z)),0);
}
float machine(float3 p) {
float body=caseBox(p-float3(0,.45,.5),float3(3.95,2.95,.9))-.12;
float base=caseBox(p-float3(0,-2.85,.3),float3(1.5,.35,1.0))-.08;
float keyboard=caseBox(p-float3(0,-3.22,-1.9),float3(3.75,.23,1.15))-.09;
return min(body,min(base,keyboard));
}
float4 main(VSOut i, out float depth:SV_Depth):SV_Target {
float t=gTime.x;
float3 ro=float3(2.3-1.1*t,.8+ .15*t,-11.2+.5*t);
float3 fw=normalize(float3(0,-.15,0)-ro);
float3 rt=normalize(cross(float3(0,1,0),fw)), up=cross(fw,rt);
float2 uv=float2(i.uv.x*2-1,1-i.uv.y*2);
float lens=max(.43,.60/max(gTime.w,.25));
float3 rd=normalize(fw+lens*(uv.x*gTime.w*rt+uv.y*up));
float travel=.05; bool hit=false;
[loop] for(int k=0;k<64;k++) {
float d=machine(ro+rd*travel);
if(d<.002) {hit=true;break;}
travel+=max(d*.85,.001);
if(travel>35)break;
}
float3 col=float3(.008,.013,.018); depth=0;
if(hit) {
float3 p=ro+rd*travel; float2 e=float2(.003,0);
float3 n=normalize(float3(machine(p+e.xyy)-machine(p-e.xyy),
machine(p+e.yxy)-machine(p-e.yxy),machine(p+e.yyx)-machine(p-e.yyx)));
float lit=saturate(dot(n,normalize(float3(-.5,.8,-.7))));
col=float3(.32,.30,.24)*(.16+.72*lit);
col+=float3(.03,.13,.11)*pow(1-saturate(dot(n,-rd)),3);
if(p.y < -2.92 && p.z < -.7 && n.y>.5) {
float2 key=frac(float2(p.x*3.4,p.z*4.0));
float gap=step(.14,key.x)*step(.14,key.y);
col*=lerp(.3,1.25,gap);
}
depth=saturate(.05/(travel*dot(rd,fw)));
if(p.z<-.38 && abs(p.x)<3.53 && abs(p.y-.50)<2.51) {
VSOut screen=i;
screen.uv=float2(p.x/7.06+.5,.5-(p.y-.50)/5.02);
col=bootRaster(screen).rgb*1.25;
}
}
return float4(col,1);
}

1285
fx/corridor.hlsl Normal file

File diff suppressed because it is too large Load diff

1131
fx/designframe.hlsl Normal file

File diff suppressed because it is too large Load diff

1375
fx/drive.hlsl Normal file

File diff suppressed because it is too large Load diff

433
fx/eye.hlsl Normal file
View file

@ -0,0 +1,433 @@
// Shot 01 - COLD OPEN: CAT EYE MACRO. And ten more after it.
//
// The demo opens on an eye that fills the frame, close enough that you read
// it as a landscape before you read it as an eye. No geometry: this is a
// two dimensional field, which is the point - not every shot has to be a
// space you fly through, and the cheapest shot in the demo is also the one
// that has to earn the first ten seconds.
//
// It is also the scene the edit leans on hardest: ELEVEN appearances, more
// than any other. That was fine as a plan and a disaster as a picture,
// because the first version of this file read gTune for a pupil width, a
// rotation and a glow, and drew the same photograph eleven times. Measured
// pairwise as luminance thumbnails the eleven shots sat 12.7 apart - the
// second most repetitive scene in the production.
//
// gTune.x pupil width (0 = a slit, 1 = fully round and blown)
// gTune.y lid closure (0 = open, 1 = shut) - arms the blink
// gTune.z iris rotation
// gTune.w glow strength
//
// Those four now carry a fifth thing nobody asked them for: an IDENTITY.
// The shot table hands eleven distinct (x, z, w) triples, so seven decorrelated
// hashes of them give every appearance a stable fingerprint, and the fingerprint
// decides the things a photographer decides - how tight the crop is, where the
// eye sits in frame, how far the lids are apart, what shape the eye is, how
// dense the veins are, and, most of all, WHAT THE CORNEA IS REFLECTING. The
// multipliers below are not decoration: they were solved so that across the
// eleven real triples every seed lands at least 0.056 from its nearest
// neighbour, against a theoretical best of 0.1, with a worst pairwise
// correlation of 0.02. That is what stops two appearances colliding.
//
// Nothing here is on a wall clock that outlives a shot. Every animation reads
// gTime.x, which restarts at each cut, so a four bar hold plays a saccade
// pattern, a dilation and a lid settle instead of being a still frame.
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look, w roll
float4 gTune;
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
float hash12(float2 p)
{
float3 q = frac(float3(p.xyx) * 0.1031);
q += dot(q, q.yzx + 33.33);
return frac((q.x + q.y) * q.z);
}
float hash11(float n)
{
n = frac(n * 0.1031);
n *= n + 33.33;
n *= n + n;
return frac(n);
}
float noise2(float2 p)
{
float2 i = floor(p), f = frac(p);
f = f * f * (3.0 - 2.0 * f);
return lerp(lerp(hash12(i), hash12(i + float2(1, 0)), f.x),
lerp(hash12(i + float2(0, 1)), hash12(i + float2(1, 1)), f.x), f.y);
}
// Value noise whose X axis is genuinely periodic, for anything wrapped around
// a circle.
//
// The version above is not, and the comment further down used to claim it was
// enough to use an integer number of cells around the turn. An integer count
// does make the INTERPOLATION parameter meet itself at the atan2 +-pi line -
// frac() lands on the same value from both sides - but hash12(i) and
// hash12(i + period) are unrelated numbers, so the VALUE still jumps.
//
// Measured before this existed, by reimplementing hash12 and noise2 exactly
// and evaluating across the seam: the iris fibre field jumped 0.18 to 0.20 of
// its 0..1 range across a single pixel boundary, against 0.004 to 0.008 for a
// typical neighbouring pixel. A 23x to 49x discontinuity - a hard radial tear
// running from the pupil to the limbus, in all ten appearances of the eye.
//
// The fix is to wrap the lattice INDEX too, so the cell after the last one is
// the first one again. period must be a whole number.
float noise2p(float2 p, float period)
{
float2 i = floor(p), f = frac(p);
f = f * f * (3.0 - 2.0 * f);
float x0 = i.x - period * floor(i.x / period);
x0 = (x0 >= period) ? 0.0 : x0; // guard the rounding case
float x1 = x0 + 1.0;
x1 = (x1 >= period) ? 0.0 : x1;
return lerp(lerp(hash12(float2(x0, i.y)),
hash12(float2(x1, i.y)), f.x),
lerp(hash12(float2(x0, i.y + 1.0)),
hash12(float2(x1, i.y + 1.0)), f.x), f.y);
}
#define TAU 6.28318531
#define ITAU 0.15915494
float4 main(VSOut i) : SV_Target
{
float2 p = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y flipped: the fullscreen triangle puts uv.y = 0 at the TOP, so
// without this the catch-light sat below centre and the lids
// closed the wrong way round.
p.x *= gTime.w;
float t = gTime.x;
// ---- which of the eleven is this? ------------------------------------
float k0 = frac(gTune.w * 10.00 + gTune.x * 14.20 + gTune.z * 2.60 + 0.143);
float k1 = frac(gTune.w * 9.50 + gTune.x * 7.10 + gTune.z * 2.80 + 0.083);
float k2 = frac(gTune.w * 12.50 + gTune.x * 13.10 + gTune.z * 6.10 + 0.587);
float k3 = frac(gTune.w * 13.60 + gTune.x * 9.40 + gTune.z * 12.20 + 0.959);
// three more, folded out of the first four rather than out of gTune, so
// they stay independent of the framing they decorate.
float k4 = frac(k0 * 3.6 + k2 * 3.2 + 0.415);
float k5 = frac(k1 * 5.6 + k3 * 1.4 + 0.258);
float k6 = frac(k0 * 3.5 + k3 * 2.6 + 0.346);
// ---- the crop --------------------------------------------------------
// This is the single biggest lever in the file. At mag 0.74 the whole
// eye sits in the frame with sclera and veins around it; at 1.52 we are
// inside the iris and the limbus only clips the corners. Eleven shots
// spread across that range stop being eleven of the same photograph.
float mag = 0.72 + 0.80 * k0;
float2 ctr = float2((k1 - 0.5) * 0.42, (k2 - 0.5) * 0.30);
// A slow drift, so the eye is alive without ever looking like it is
// being animated at you. Rate and throw are per appearance now.
ctr -= float2(sin(t * (0.19 + k4 * 0.17)) * (0.018 + k5 * 0.030),
cos(t * (0.13 + k5 * 0.16)) * (0.014 + k4 * 0.026));
// ---- the gaze --------------------------------------------------------
// A real eye never holds still: it darts and then sits. Step-and-hold,
// fast on the way out and long on the hold, with the targets hashed off
// this appearance's own seed so the pattern is reproducible per shot.
// This is what makes a CAM_HOLD shot not a freeze frame.
float sacR = 0.42 + k2 * 1.05; // darts per second
float sacA = 0.015 + k3 * 0.085; // and how far each one goes
float sp = t * sacR + k0 * 13.0;
float si = floor(sp);
float sf = smoothstep(0.0, 0.13, frac(sp));
float sd = k1 * 57.0;
float2 gA = float2(hash11(si * 2.13 + sd), hash11(si * 2.13 + sd + 19.7)) - 0.5;
float2 gB = float2(hash11(si * 2.13 + 2.13 + sd),
hash11(si * 2.13 + 2.13 + sd + 19.7)) - 0.5;
float2 gaze = lerp(gA, gB, sf) * sacA;
// Two frames, and the difference between them is the whole trick: the
// eyeball (sclera, veins, lids, the reflected world) does not move when
// the eye looks somewhere - only the iris and pupil do.
float2 eb = (p - ctr) / mag; // eyeball
float2 e = eb - gaze; // iris
float r = length(e);
float rb = length(eb);
float rs = length(p - ctr); // screen, for glow and vignette
// ---- iris ------------------------------------------------------------
float irisEdge = 0.86;
float spin = gTune.z + t * ((k3 - 0.45) * 0.16);
float a01 = (atan2(e.y, e.x) + spin) * ITAU; // turns, not radians
// Radial fibres, two scales, so it holds up at this magnification. The
// counts are INTEGERS in turns AND the noise is wrapped to them, which is
// what actually closes the seam at the +-pi line - the integer count on
// its own does not, see noise2p.
float sect = floor(7.0 + k4 * 13.0); // 7..19 coarse spokes
float fineN = floor(23.0 + k5 * 26.0); // 23..48 fine ones
float strc = 3.6 + k6 * 5.4; // how far they smear radially
float fib = noise2p(float2(a01 * sect, r * strc), sect) * 0.62
+ noise2p(float2(a01 * fineN, r * strc * 2.3), fineN) * 0.38;
// The collarette: the ruff where the iris changes character, and where
// the crypts live. Its radius moves per appearance, which redraws the
// whole interior structure rather than recolouring it.
float colR = 0.30 + k6 * 0.30;
float cb = (r - colR) * 5.5;
float band = exp(-cb * cb);
float cryN = floor(5.0 + k5 * 9.0);
float crypt = smoothstep(0.60, 0.88,
noise2p(float2(a01 * cryN, r * 3.0 + 11.0), cryN)) * band;
float iris = smoothstep(irisEdge + 0.055, irisEdge - 0.02, r);
// A cat pupil is a vertical slit that opens into an ellipse.
// The pupil breathes with the low band. 0.045 is a ceiling, not a
// starting point: it is 2.8% of the iris, and the band's 420 ms release
// against a 454 ms beat means it is always still falling when the next
// kick lands. It physically cannot pulse.
// On top of that it now DILATES OR CONTRACTS across the shot - direction
// from the seed - so the pupil is a movement and not a setting.
float dilDir = (k2 < 0.5) ? -1.0 : 1.0;
float dil = saturate(gTune.x + dilDir * (0.05 + 0.20 * gTune.x)
* smoothstep(0.15, 2.40, t));
float pw = max(0.052 + dil * 0.62 + gSync.x * 0.045 + gVoice.y * 0.012, 0.020);
float ph = 0.62 + k4 * 0.22; // how tall the slit is
float lean = (k1 - 0.5) * 0.22; // and how far it leans
float2 q = float2((e.x - e.y * lean) / pw, e.y / ph);
// A perfect ellipse reads as vector art, so the rim borrows the iris
// texture it is cut out of. Free: fib is already in hand.
// Bounded by the iris mask: a tall slit on a wide seed would otherwise
// run past the limbus and cut a hole in the sclera, which is an eye
// with a slot milled through it.
float pupil = smoothstep(1.04, 0.94, length(q) + (fib - 0.5) * 0.05) * iris;
float hueK = k2 * 0.55; // green cat to amber cat
float3 dark = lerp(float3(0.10, 0.30, 0.16), float3(0.27, 0.21, 0.07), hueK);
float3 lite = lerp(float3(0.55, 0.95, 0.40), float3(0.97, 0.82, 0.34), hueK);
// Contrast of the fibres rides the mid band. base + k*s: the floor is
// 1.20 and the music can only ever add to it.
float3 gold = lerp(dark, lite, saturate(fib * (1.20 + gSync.y * 0.18)));
gold = lerp(gold, lite * 1.15, pow(saturate(1.0 - r / irisEdge), 2.4) * 0.85);
gold *= 1.0 - 0.55 * crypt; // the lacunae, punched dark
// Flecks. Four of them, at hashed positions in the iris, and only some
// appearances get any at all - the reward for looking twice.
float fleckAmt = saturate((k5 - 0.35) / 0.40);
float fleck = 0.0;
[unroll] for (int fi = 0; fi < 4; fi++)
{
float fh = hash11(float(fi) * 3.7 + k0 * 91.0);
float fr = 0.26 + hash11(float(fi) * 5.1 + k2 * 77.0) * 0.50;
float da = a01 - fh;
da -= floor(da + 0.5); // shortest way round
float2 fd = float2(da * TAU * max(r, 0.12), r - fr);
fleck += exp(-dot(fd, fd) * 900.0);
}
gold += lite * fleck * fleckAmt * 0.55;
// The limbal ring: the dark edge that makes an iris read as an iris.
float ringW = 0.13 + k6 * 0.17;
gold *= 1.0 - (0.62 + 0.28 * k3) * smoothstep(irisEdge - ringW, irisEdge, r);
float3 col = gold * iris;
col *= 1.0 - pupil; // punch the pupil out
// ---- the sclera ------------------------------------------------------
// Only exists in the wider framings, and when it does it brings the veins
// with it. A whole extra half of the picture that six of the eleven shots
// have and the other five do not.
float scl = smoothstep(irisEdge - 0.01, irisEdge + 0.07, rb);
float3 sclera = float3(0.20, 0.215, 0.205) * (1.0 - 0.62 * smoothstep(0.95, 1.80, rb));
[branch] if (mag < 1.30)
{
float ab = atan2(eb.y, eb.x) * ITAU;
float vN = floor(13.0 + k5 * 17.0);
float vN2 = floor(vN * 2.4); // integer, so it can wrap
float vr = rb * 2.4 - t * 0.015;
float vv = noise2p(float2(ab * vN, vr), vN) * 0.68
+ noise2p(float2(ab * vN2, vr * 2.4 + 7.3), vN2) * 0.32;
vv = saturate(1.0 - abs(vv * 2.0 - 1.0));
vv *= vv; vv *= vv; vv *= vv; // ridged, ^8, no pow call
float vmask = smoothstep(irisEdge + 0.02, irisEdge + 0.50, rb);
sclera += float3(0.26, 0.09, 0.09) * vv * vmask
* (0.18 + 0.70 * k5) * (1.0 + gSync.x * 0.25);
}
col += sclera * scl;
// ---- what the cornea is reflecting -----------------------------------
// A cat's eye is a mirror before it is anything else, and the thing in
// the mirror is the only element that can be a different OBJECT without
// the shot stopping being an eye. Four of them, chosen by k1.
float2 rc = eb + gaze * 0.30; // the world does not turn with the eye
rc *= (1.4 + k3 * 1.5) / max(1.0 - 0.55 * dot(rc, rc), 0.30); // convex: the rim eats the horizon
float ref = 0.0;
int variant = min(3, (int)(k1 * 4.0));
if (variant == 0)
{
// a lit window, four panes, drifting
float2 wp = rc * float2(1.0, 1.30) - float2(sin(t * 0.09) * 0.20, 0.55);
float pane = smoothstep(1.00, 0.74, max(abs(wp.x), abs(wp.y)));
float mull = smoothstep(0.05, 0.11, abs(wp.x)) * smoothstep(0.05, 0.11, abs(wp.y));
ref = pane * (0.30 + 0.70 * mull);
}
else if (variant == 1)
{
// a low sun over a banded horizon: the demo's own synthwave shot,
// seen from the wrong side of the glass
float2 sn = rc - float2(0.0, -0.30 + sin(t * 0.07) * 0.06);
float sun = smoothstep(0.46, 0.20, length(sn * float2(1.0, 1.15)));
float band = 0.5 + 0.5 * sin(sn.y * 26.0 - t * 0.7);
float hz = smoothstep(0.06, 0.0, abs(rc.y + 0.64));
ref = sun * (0.45 + 0.55 * band) + hz * 0.55;
}
else if (variant == 2)
{
// a tube. scanlines and a roll bar, because of course it is a tube
float2 sn = rc * float2(0.92, 1.20);
float scr = smoothstep(1.05, 0.86, max(abs(sn.x), abs(sn.y)));
float lines = 0.55 + 0.45 * sin(sn.y * 52.0);
float roll = smoothstep(0.30, 0.0, abs(frac(sn.y * 0.4 - t * 0.13) - 0.5));
ref = scr * (lines * 0.75 + roll * 0.40);
}
else
{
// doorframes receding: the corridor, six deep, walking outward. The
// ratio is exactly 2 so the sequence at frac()==1 is the sequence at
// frac()==0 shifted by one frame, and the loop never pops.
float s = 1.05 * exp2(frac(t * 0.11));
[unroll] for (int ai = 0; ai < 6; ai++)
{
float dr = max(abs(rc.x) / s, abs(rc.y) / (s * 0.80));
ref += smoothstep(0.075, 0.0, abs(dr - 1.0));
s *= 0.5;
}
ref *= 0.55;
}
ref = saturate(ref);
// The pupil is not black: it is a hole with the world in it. Over the
// iris the same reflection sits far fainter, because there is already
// something under it.
float corn = smoothstep(irisEdge + 0.16, irisEdge - 0.04, rb);
col += pupil * float3(0.020, 0.028, 0.034);
col += ref * corn * float3(0.72, 0.92, 0.85)
* (pupil * (0.16 + 0.14 * k3) + (0.030 + 0.035 * k6));
// ---- the wet specular ------------------------------------------------
// The catchlight is a reflection of the KEY LIGHT, so it barely follows
// the gaze - which is exactly why it slides across the iris when the eye
// darts. Three shapes, and its position moves per appearance.
int cls = min(2, (int)(k2 * 3.0));
float2 cp = float2(lerp(-0.40, 0.34, k1), lerp(0.14, 0.46, k3))
+ gaze * 0.12 + float2(gSync.z * 0.010, 0.0);
float2 cd = eb - cp;
float csz = 0.13 + k6 * 0.17;
float spec;
if (cls == 0)
{
spec = smoothstep(csz * 2.1, 0.0, length(cd)); // one soft disc
}
else if (cls == 1)
{
spec = smoothstep(csz * 1.5, 0.0, length(cd)) // and a companion
+ smoothstep(csz * 0.85, 0.0, length(cd - float2(0.21, -0.14))) * 0.70;
}
else
{
float2 wd = cd / csz; // a window, four panes
float box = smoothstep(1.65, 1.15, max(abs(wd.x), abs(wd.y * 1.25)));
float mull = smoothstep(0.10, 0.24, abs(wd.x)) * smoothstep(0.10, 0.24, abs(wd.y));
spec = box * (0.35 + 0.65 * mull);
}
col += spec * float3(0.85, 0.95, 0.90) * (0.42 + 0.20 * k0) * (1.0 + gSync.z * 0.22);
// the bounce off the wet lower lid
col += smoothstep(0.28, 0.0, length(eb - float2(cp.x * 0.4, -0.54)))
* float3(0.30, 0.42, 0.38) * 0.11;
// ---- glow ------------------------------------------------------------
// The eye is its own light source. This is the reason the shot works in
// a black frame. It falls off in SCREEN radius, not eyeball radius, or a
// tight crop would flood the frame with it.
float glow = exp(-rs * 1.9) * gTune.w * (1.0 + gVoice.z * 0.10);
col += float3(0.28, 0.75, 0.34) * glow;
col += float3(0.10, 0.30, 0.14) * exp(-rs * 0.7) * gTune.w * 0.35;
// ---- the third eyelid ------------------------------------------------
// A cat has a nictitating membrane and it sweeps in from the inner
// corner. Four of the eleven get one, once, early in the shot. It is a
// film, not a shutter: it lifts the blacks under it and leaves a bright
// leading edge, and it takes 0.9 s to cross, so nothing about it snaps.
[branch] if (k6 > 0.62)
{
float sweep = sin(saturate((t - 0.55) / 0.90) * 3.14159265);
float xe = -2.10 + sweep * 2.55;
float memb = smoothstep(xe, xe - 0.14, p.x);
float lead = smoothstep(0.10, 0.0, abs(p.x - xe + 0.07)) * sweep;
col = lerp(col, col * 0.62 + float3(0.09, 0.13, 0.10) * (0.30 + 0.70 * sweep),
memb * 0.45);
col += float3(0.18, 0.26, 0.21) * lead * 0.35;
}
// ---- the lid ---------------------------------------------------------
// Two arcs closing on the eye. A blink is a shape, not a fade - and it
// is a movement, so the shader plays it from the shot's own clock.
// gTune.y only arms it; holding the lid shut for a whole shot would just
// be a shot of black, which is what the first version of this was.
//
// The APERTURE is now per appearance, and it is the second biggest lever
// after the crop: 0.68 is a half lidded stare and 1.37 is wide open, and
// an eye is a different shape at each end of that. The curve and the
// slant move with it, so some of the eleven are almonds and some are
// rounds.
float apert = (1.38 - 0.70 * k3) + sin(t * 0.7 + k0 * 6.0) * 0.015;
float cvx = 0.16 + k6 * 0.30;
float tilt = (k4 - 0.5) * 0.30;
float lid = 0.0;
if (gTune.y > 0.5) {
float u = saturate(t / 0.18); // 180 ms, shut then open
lid = u < 0.38 ? (u / 0.38) : saturate(1.0 - (u - 0.38) / 0.62);
}
// and a settle, on every shot: the lids come the last few percent of the
// way open over the first second, so frame one is never where we stay.
lid = saturate(lid + (1.0 - smoothstep(0.0, 1.10, t)) * 0.10 * (0.40 + k5));
// The lid edge carries fur. Smoothed value noise along x, so the
// silhouette is a different ragged line in every appearance.
float2 d = p - ctr * 0.7;
float lx = d.x * (30.0 + k5 * 34.0);
float lf = frac(lx); lf = lf * lf * (3.0 - 2.0 * lf);
float ls = 5.0 + k0 * 9.0;
float fur = (lerp(hash12(float2(floor(lx), ls)),
hash12(float2(floor(lx) + 1.0, ls)), lf) - 0.5) * 0.034;
float lo = -apert + lid * (apert + 0.30) + cvx * d.x * d.x + tilt * d.x + fur;
float hi = apert - lid * (apert + 0.30) - cvx * d.x * d.x + tilt * d.x - fur;
float open = smoothstep(lo, lo + 0.045, d.y) * smoothstep(hi, hi - 0.045, d.y);
// the shadow the lid casts on the globe under it
float inner = smoothstep(lo + 0.02, lo + 0.17, d.y) * smoothstep(hi - 0.02, hi - 0.17, d.y);
col *= open * (0.30 + 0.70 * inner);
// Vignette down to nothing, so the eye floats in the dark.
col *= 1.0 - 0.55 * smoothstep(0.72, 1.75, rs);
return float4(col * gTime.z, 1.0);
}

18
fx/fullscreen.hlsl Normal file
View file

@ -0,0 +1,18 @@
// One triangle that covers the screen, built from the vertex id alone.
// Nothing is bound: no vertex buffer, no input layout, no index buffer.
// Draw(3, 0) with topology TRIANGLELIST is the whole call.
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
VSOut main(uint id : SV_VertexID)
{
VSOut o;
o.uv = float2((id << 1) & 2, id & 2); // (0,0) (2,0) (0,2)
o.pos = float4(o.uv.x * 2.0 - 1.0,
1.0 - o.uv.y * 2.0, 0.0, 1.0);
return o;
}

1254
fx/horizon.hlsl Normal file

File diff suppressed because it is too large Load diff

68
fx/inscriptions.hlsli Normal file
View file

@ -0,0 +1,68 @@
#ifndef INSCRIPTIONS_HLSLI
#define INSCRIPTIONS_HLSLI
uint2 inscriptionGlyph(uint c)
{
switch (c) {
case 97u: return uint2(0x83800u, 0x7a3eu);
case 98u: return uint2(0x8bc21u, 0x3e31u);
case 100u: return uint2(0x8fa10u, 0x7a31u);
case 101u: return uint2(0x8b800u, 0x383fu);
case 102u: return uint2(0x38a4cu, 0x842u);
case 103u: return uint2(0x8c7c0u, 0x3a1eu);
case 105u: return uint2(0x21804u, 0x3884u);
case 108u: return uint2(0x21086u, 0x3884u);
case 109u: return uint2(0xaac00u, 0x56b5u);
case 110u: return uint2(0x8bc00u, 0x4631u);
case 111u: return uint2(0x8b800u, 0x3a31u);
case 114u: return uint2(0x9b400u, 0x421u);
case 115u: return uint2(0xf800u, 0x3e0eu);
case 116u: return uint2(0x11c42u, 0x3242u);
case 117u: return uint2(0x8c400u, 0x5b31u);
case 121u: return uint2(0x8c620u, 0x3a1eu);
case 46u: return uint2(0x0u, 0x1080u);
default: return uint2(0u, 0u);
}
}
static const uint inscriptionRemember[12] = {114,101,109,101,109,98,101,114,46,46,46,32};
static const uint inscriptionSignal[12] = {115,105,103,110,97,108,32,102,111,117,110,100};
static const uint inscriptionStrange[12] = {115,116,97,121,32,115,116,114,97,110,103,101};
float inscriptionPixel(int2 p, uint label)
{
uint count = label == 1u ? 11u : 12u;
if (p.x < 0 || p.y < 0 || p.x >= int(count * 6u - 1u) || p.y >= 7) return 0.0;
uint slot = uint(p.x) / 6u;
uint x = uint(p.x) % 6u;
if (x == 5u) return 0.0;
uint c = label == 1u ? inscriptionRemember[slot]
: label == 2u ? inscriptionSignal[slot] : inscriptionStrange[slot];
uint2 bits = inscriptionGlyph(c);
uint row = uint(p.y);
return float(((row < 4u ? bits.x : bits.y) >> ((row % 4u) * 5u + x)) & 1u);
}
float inscriptionMask(float2 uv, float2 footprint, float selector)
{
if (selector < 0.5 || selector >= 3.5 || any(uv < 0.0) || any(uv > 1.0)) return 0.0;
uint label = uint(selector + 0.5);
float2 size = float2(label == 1u ? 65.0 : 71.0, 7.0);
float2 p = uv * size;
float2 fw = max(footprint * size, 0.001);
float resolved = 1.0 - smoothstep(1.0, 1.8, max(fw.x, fw.y));
if (resolved <= 0.0) return 0.0;
int2 base = int2(floor(p));
float value = 0.0;
[loop] for (int y = -1; y <= 1; ++y) {
[loop] for (int x = -1; x <= 1; ++x) {
int2 cell = base + int2(x, y);
float2 overlap = max(0.0, min(p + fw * 0.5, float2(cell) + 1.0)
- max(p - fw * 0.5, float2(cell)));
value += inscriptionPixel(cell, label) * overlap.x * overlap.y;
}
}
return saturate(value / (fw.x * fw.y)) * resolved;
}
#endif

722
fx/kaleido.hlsl Normal file
View file

@ -0,0 +1,722 @@
// KALEIDOSCOPIC IFS TUNNEL.
//
// You are falling down a folded throat: a lattice mirrored around the axis
// and repeated down it, streaming past close enough to blur and converging on
// a light you never reach. It belongs under a solo, and it is built so that
// the same shader is several different rooms - a tight four-sided pipe you
// can barely fit through, a twelve-fold cathedral of glass with irises you
// fly through - on the shot knobs alone.
//
// The composition, which is what everything below is in service of: the light
// is a lamp ON THE AXIS, a fixed distance AHEAD of the camera, travelling
// with it. So the far end of the tunnel is blown out, the walls rushing past
// your ear are nearly black, and the relief between the two is raked by a
// light that is always at the vanishing point. That is the entire value
// structure - white core, amber-to-green relief, black near walls - and it
// is the structure that survives a 4x4 Bayer dither at 640x360, where
// anything subtler would not.
//
// ---- WHY THIS FILE IS SHAPED THE WAY IT IS -------------------------------
//
// Eight shots in the edit draw this scene. Measured as thumbnails they were
// too close to each other: the knobs only ever changed the fold ANGLE, the
// IFS scale and the pipe diameter, and at 360 lines through a four-stop ramp
// those three read as the same picture with the contrast nudged. What the
// eye actually sorts a frame by, in the half second a two-bar shot gets, is
// SYMMETRY ORDER and SILHOUETTE - how many arms the star at the vanishing
// point has, and whether the tunnel is a bare pipe or has rings coming at
// you. So the knobs now quantise into a small set of discrete layouts and
// the continuous values ride on top of those.
//
// gTune.x fold amount - 0..1. Two jobs. Quantised into five bands it picks
// the SYMMETRY ORDER: 4, 6, 8, 10 or 12 sectors
// around the axis, and the parity of that band sets
// which way the whole thing spins. Continuously it
// still drives the IFS rotation between iterations
// (blocky and architectural at 0, sheared into
// spines at 1), the spin rate, the rate the throat
// breathes at, and the colour band spacing.
// gTune.y IFS scale - space expansion per iteration, clamped 1.15..2.30.
// Low is a dense fine weave, high is a few big
// slabs. Its FRACTIONAL part is a second, unrelated
// knob: the coarseness floor, which caps how fine
// the lattice is allowed to get regardless of how
// close it is. A coarse shot is carved out of
// slabs, a fine one is filigree.
// gTune.z openness - 0 is a tight bore threaded onto the camera, 1
// blows the pipe out into a hall and turns on the
// glass rim light. Quantised into four bands it also
// decides whether the tunnel carries IRIS PLATES -
// annular bulkheads rushing past with a hole in the
// middle - and how close together they sit.
// Continuously it sets cell length down the axis,
// rail thickness, twist pitch and fog density.
// gTune.w hurtle - EXTRA units per second the structure flows toward
// you, on top of a baseline the shot always gets.
// The baseline exists because half these shots are
// held or whip-panned cameras: with a still camera
// and no flow the shot is a photograph, and this is
// the scene under the solo.
//
// The eight rows in the table land on eight different (symmetry, structure)
// pairs, which is the point: no two appearances are the same room.
//
// ---- OFF-AXIS SAFETY -----------------------------------------------------
//
// The tunnel used to be nailed to the world axis, so any shot that walked the
// camera sideways buried the lens in solid lattice and the frame went black.
// The axis now follows the camera once the camera has used up its clearance
// inside the bore - free parallax within the throat, and a tow after that.
// It is a translation that depends only on the constant buffer, so it costs
// nothing per step and every argument below about toTube being a pure
// translation still holds.
//
// ---- THE THING THAT MAKES THIS SHADER WORK AT 360 LINES ------------------
//
// A five level IFS with a scale of 2.3 puts its finest strut at th/2.3^5, a
// hair over seven thousandths of a unit. At the demo's fixed 360 virtual
// lines that is sub-pixel from about four units out - which is to say, over
// essentially the whole frame. Rendered flat, that detail does not read as
// detail. It reads as a boiling stipple that the post pass's ordered dither
// then latches onto and amplifies, and in a dark cinema it is the only thing
// anybody sees.
//
// So the field is CONE AWARE. The march carries the radius of the pixel
// footprint at the current depth, and the IFS uses it twice: any level whose
// struts are thinner than one pixel is fattened out to a pixel, and once a
// level falls below that it stops iterating entirely. Fattening keeps the
// strut visible instead of stippling; stopping keeps the compiler from
// spending five iterations resolving something that lands inside one sample.
// The normal and the occlusion are handed the same radius, so all three agree
// on which surface they are looking at. The per-shot coarseness floor rides
// in through exactly the same door - it is a minimum footprint - so it costs
// nothing and it saves iterations on the shots that use it hardest.
//
// Cost: up to 56 march steps, a four tap normal and a five tap occlusion at
// the hit, so 65 distance field evaluations for a pixel that hits and fewer
// for one that does not. Each evaluation is two to five IFS iterations after
// the cone cutoff, plus a rail, plus - on the shots that turn them on - one
// iris plate. No shadow rays: the only real light sits on the axis at the
// vanishing point, so a shadow ray from any visible surface would trace back
// along the camera's own sightline and buy almost nothing off the most
// expensive map in the demo. Occlusion does that job instead, and in a folded
// lattice it is doing most of the shaping.
//
// In wall clock, at the 640x360 the scene target actually runs at: order of
// a millisecond on a mid-range discrete part, a few tenths on a fast one,
// and several milliseconds on integrated graphics.
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect (w/h)
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look direction, w roll
float4 gTune; // per shot knobs
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// ---- distance field ------------------------------------------------------
#define LAMP 13.0 // how far ahead of the camera the light sits
#define TAU 6.28318531
// Half the vertical field, in tangent units, divided by half the virtual
// height: the scene target is a fixed 360 lines (gfx.c, VH), so this is the
// tangent subtended by one virtual pixel. Multiplied by depth it is the
// radius of the pixel's footprint out there, which is the only number the
// level-of-detail cutoff needs. It is deliberately biased a little coarse -
// the output is dithered into a narrow ramp, and half a pixel of detail is
// not detail there, it is noise.
#define PIXTAN (1.25 / 180.0)
float2 rot2(float2 v, float a)
{
float c = cos(a), s = sin(a);
return float2(v.x * c - v.y * s, v.x * s + v.y * c);
}
// The two radii the tunnel lives between. Shots need the inner one as well -
// it is the safety margin that stops a camera ending up buried in a solid -
// so it is worth having in one place.
float boreRadius(float op) { return 0.80 + 1.70 * op; }
float wallRadius(float op) { return 3.20 + 2.60 * op; }
// ---- the per shot layout -------------------------------------------------
//
// Everything in here reads the constant buffer and nothing else, so it is
// uniform over the whole frame and fxc hoists the lot out of the march. It
// is written as one struct rather than sprinkled through mapT so that the
// eight rows in the table can be read off against it in one place.
struct Cfg
{
float folds, sec, isec; // symmetry order and the wedge it implies
float spin, zTwist; // rotation in time, and pitch of the spiral
float cell, coarse; // axial repeat, and the detail floor
float boreAmp, boreFrq; // the throat breathing as it comes at you
float railGap, railW; // the spars that ride the lip of the throat
float ringOn, ringSp, ringISp, ringTh, ringGap; // the iris plates
float bandFrq, fogK, flow;
};
Cfg cfg()
{
Cfg c;
float fx = saturate(gTune.x);
float fz = saturate(gTune.z);
float fy = clamp(gTune.y, 1.15, 2.30);
// The two discrete axes. Five symmetry bands against four structure
// bands is twenty layouts for eight shots, and the table's values land
// on eight distinct pairs - which is the whole reason the appearances
// stop looking like each other.
float vi = min(floor(fx * 5.0), 4.0); // 0..4
float ri = min(floor(fz * 4.0), 3.0); // 0..3
// Spin direction off the parity of the symmetry band. Two shots that
// happen to share a fold count will at least be turning opposite ways.
float par = (frac(vi * 0.5) < 0.25) ? 1.0 : -1.0;
// Four sectors reads as a square shaft, six as the snowflake everybody
// already knows as "kaleidoscope", twelve as a rose window. Nothing else
// in this file changes the frame as hard as this one number.
c.folds = 4.0 + 2.0 * vi;
c.sec = TAU / c.folds;
c.isec = c.folds * (1.0 / TAU);
c.spin = par * (0.22 + 0.50 * fx);
c.zTwist = par * (0.018 + 0.045 * fz);
c.cell = 2.30 + 2.60 * fz;
// The coarseness floor. gTune.y's integer part is the IFS scale, which
// the table sweeps monotonically; its fraction is free, and it is worth
// more here than anywhere else because it decides whether the wall is a
// filigree or a set of slabs.
c.coarse = 0.004 + 0.030 * frac(fy);
// The throat is not a constant diameter. A long wave travelling with the
// structure opens and closes the aperture as it comes at you, which is
// motion the camera cannot supply and which reads even on a shot held
// dead still. The gSync term pumps it with the kick; it is an addition
// to a base, never a multiply of the picture.
c.boreAmp = 0.08 + 0.16 * fz + 0.05 * saturate(gSync.x);
c.boreFrq = 0.055 + 0.075 * fx;
// Spars riding the lip of the throat, one per sector, silhouetted
// against the bright core and converging on it. They are what makes the
// symmetry order legible at a glance instead of something you have to
// work out from the relief.
c.railGap = 0.10 + 0.28 * fz;
c.railW = 0.045 + 0.055 * fz;
// Iris plates: annular bulkheads with a hole in the middle, rushing past.
// Off for the tightest shots, where the pipe wants to be bare, and
// getting denser as the room opens up.
c.ringOn = (ri >= 1.0) ? 1.0 : 0.0;
c.ringSp = 11.0 - 2.2 * ri;
c.ringISp = 1.0 / c.ringSp;
c.ringTh = 0.06 + 0.12 * fz;
// The hole is only a little wider than the throat, so these read as
// apertures you fall through rather than as ribs on a distant wall. Any
// wider and the eye files them as wall detail; the whole reason they are
// here is to put something between the camera and the vanishing point.
c.ringGap = 0.06 + 0.26 * fz;
c.bandFrq = 0.16 + 0.16 * fx;
// Fog is a composition control, not an atmosphere: it sets how deep the
// tunnel reads. A tight bore wants to close in a few units, a cathedral
// wants to run away from you.
c.fogK = 0.020 + 0.022 * (1.0 - fz);
// Baseline flow, so a held or whip-panned camera is not a photograph.
// It is a RATE multiplied by absolute shot time, so nothing audio driven
// is allowed in it - a rate that changed would jump the phase.
c.flow = gTune.w + 2.0 + 7.0 * fz;
return c;
}
// World space into tube space, where the axis of the tunnel is exactly
// x = y = 0. This is a pure translation at every depth - never a rotation -
// so length(q.xy) is a true world distance to the axis and a direction built
// out of q.xy is a true world direction. The lighting leans on both of those,
// which is why the twist lives in mapT and not in here.
float3 toTube(float3 p)
{
// The structure comes at the camera rather than the other way round, so
// a shot can hold the camera dead still and still be moving at speed.
p.z += gTime.x * cfg().flow;
float op = saturate(gTune.z);
// The bore is not a straight pipe. A long shallow serpentine drifts the
// vanishing point off centre and back, which is the whole difference
// between falling down a hole and riding something.
//
// The amplitude is a FRACTION OF THE BORE and not a constant. It used to
// be a constant 0.60 and 0.48, whose combined swing is 0.77 units - wider
// than the tightest bore, so a shot that put the camera on the world axis
// with tune.z at 0 had the tunnel walk over the top of it and bury the
// lens in solid lattice, on a schedule, some seconds into the shot. At
// 0.42 of the bore the worst case swing is a little over half the
// clearance, and it gets grander as the room does, which is also the
// better look.
float amp = boreRadius(op) * 0.42;
p.x -= sin(p.z * 0.021) * amp;
p.y -= cos(p.z * 0.017) * amp * 0.80;
// ...and the tunnel is threaded onto the CAMERA, not onto the world
// origin. A crane or a lateral track used to walk the lens straight into
// the solid outside the wall and the frame went black; now the camera
// gets free parallax for the first half of its clearance and tows the
// axis after that. Depends on gCam alone, so it is a constant offset for
// the whole frame and the pure-translation argument above survives.
float2 co = gCam.xy;
float cl = length(co);
float free = boreRadius(op) * 0.50;
p.xy -= co * (max(cl - free, 0.0) / max(cl, 1e-4));
return p;
}
// `lod` is the radius of the pixel footprint at the point being sampled.
// Pass 0 for the exact field; the march, the normal and the occlusion all
// pass the real thing, and all three must pass the SAME thing at a given
// point or the normal ends up being the gradient of a discontinuity.
float mapT(float3 q, float lod)
{
Cfg c = cfg();
float op = saturate(gTune.z);
float bore = boreRadius(op);
float wall = wallRadius(op);
float mid = (bore + wall) * 0.5;
float r = length(q.xy);
// The breathing throat. Only the CUT is modulated, never `mid` - the
// lattice stays exactly where it was and the aperture opens over it and
// closes back, so the wave reveals and hides relief instead of dragging
// the whole wall around. Amplitude times frequency is under a tenth, so
// the field stays comfortably Lipschitz and the march does not overstep.
float bth = bore * (1.0 + c.boreAmp * sin(q.z * c.boreFrq));
// Twist about the axis. Being a rotation about that axis it leaves r
// alone, so it is free to happen after the radius has been taken. Rate
// and sign are both per shot: a spiral climbing left at one pitch and a
// spiral climbing right at three times that are different rooms.
float2 tw = rot2(q.xy, q.z * c.zTwist + gTime.x * c.spin);
// The kaleidoscope. Fold the plane down to one sector, then mirror that
// wedge about its own centre line. The mirror is the part that matters:
// it makes the two edges of the wedge identical, so the copies meet with
// no visible seam no matter what the IFS then does inside.
//
// The usual failure of a polar fold is the pinch at the axis, where the
// sectors converge and the arc length metric collapses to nothing. It
// cannot happen here: the bore hollows out everything inside the throat,
// so the pinch is never rendered.
float a = atan2(tw.y, tw.x);
a -= c.sec * floor(a * c.isec);
a = abs(a - c.sec * 0.5);
// Arc length around the tunnel. A true world length, which is what makes
// a box built on it a valid distance estimate.
float arc = a * r;
// Unroll the wedge into a flat slab: x is arc length around the tunnel,
// y is how far out from the middle of the annulus, z is depth, repeated
// so the tunnel has no end.
//
// This unrolling is the fix for the thing that makes a naive version of
// this shader fail. The attractor of a contracting IFS is COMPACT - a
// blob a couple of units across - so running one on raw world space
// gives a small clump of struts floating in an otherwise empty frame.
// Run it in the slab instead and the fold and the repeat tile that one
// blob into a relief that covers the whole wall.
float3 p;
p.x = arc;
p.y = r - mid;
p.z = frac(q.z * (1.0 / c.cell)) * c.cell - c.cell * 0.5;
// The iterated function system. Fold into the positive octant, rotate,
// then scale about an offset point - five times. Everything but the
// scale is an isometry, so working in units of 1/scale is a correct
// distance estimate for the original point.
//
// A shot row that left tune.y at zero would otherwise divide by zero and
// paint the frame with NaN, so the scale is clamped rather than trusted.
float s = clamp(gTune.y, 1.15, 2.30);
float is = 1.0 / s;
// The fold angle is taken as a 0..1 amount and remapped onto the band
// where the lattice actually exists. Past about 1.5 radians the two
// rotations between them walk the whole structure out of the slab and
// the shot becomes an empty pipe - a silent, total failure that looks
// like a bug in the engine rather than a bad number in a row. Rather
// than leave that trap in the table, the knob only reaches the good band.
float ang = 0.18 + 1.30 * saturate(gTune.x);
float ca = cos(ang), sa = sin(ang);
// Opening the tunnel up moves the IFS fixed point outward with the wall,
// so the relief keeps hugging the surface instead of being left behind
// floating in the middle of the new, larger hall.
float3 off = float3(0.62 + 0.55 * op, 0.48 + 0.75 * op, 0.40);
// A square tube down the current z at every level of the iteration, all
// unioned together. Measuring only the LAST iterate is the obvious way to
// write this and it is a trap: past about a radian of fold angle the
// rotations walk the attractor clean out of the slab we sample, the
// union collapses to nothing, and the shot becomes an empty pipe. Taking
// a primitive at each level instead guarantees material at every scale,
// so the fold angle is free to sweep its whole range without the
// structure ever disappearing. Each term is a valid estimate at its own
// scale, so the minimum of them is still a valid estimate.
//
// Square rather than round because at 640x360 a flat face that catches
// the light in one value beats a cylinder that ramps across four pixels.
//
// The strut swells with the solo. It is base * (1 + k * envelope), so the
// lattice thickens on a peak and never thins away to nothing.
float th = (0.45 + 0.25 * op) * (1.0 + 0.20 * saturate(gVoice.y));
float d = 1e9;
float isc = 1.0; // 1 / (total scale so far)
// The footprint the iteration is actually allowed to resolve: the pixel,
// or the shot's coarseness floor, whichever is blunter.
float lodI = max(lod, c.coarse);
[loop] for (int i = 0; i < 5; i++) {
p = abs(p);
p.xy = float2(p.x * ca - p.y * sa, p.x * sa + p.y * ca);
p = p * s - off * (s - 1.0);
p.yz = float2(p.y * ca - p.z * sa, p.y * sa + p.z * ca);
isc *= is;
// This level's strut half-width, back in world units.
float w = th * isc;
// Never let a strut be thinner than the pixel it lands in. Below that
// width it stops being geometry and starts being a coin flip per
// frame, and the dither in the post pass turns a coin flip into
// crawling salt. Fattening it costs nothing - the max() was already
// there - and it is exactly the original expression when the strut is
// wider than a pixel, so near geometry is untouched.
float wf = max(w, lodI);
d = min(d, max(abs(p.x) * isc - wf, abs(p.y) * isc - wf));
// ...and once a level is finer than a pixel, nothing below it can be
// resolved either, because every subsequent level is smaller again.
// Stop. This is where the cost saving lives: at the far wall this
// runs twice, not five times.
if (w < lodI) break;
}
// The rails. One square spar per sector, sitting a fixed gap outside the
// CURRENT throat radius - so they ride the breathing aperture rather than
// being swallowed by it at the wide phase - and running the length of the
// tunnel. Because the fold that produced `arc` is taken from the twisted
// coordinates, they are helices, and their pitch is the shot's.
//
// They cost five instructions and they do three jobs: they draw the
// symmetry order in one unmistakable read, they give the eye something
// with real speed on it near the camera where the lattice is just a blur,
// and they guarantee material in the frame for any combination of fold
// angle and scale.
float railR = bth + c.railGap;
float rw = max(c.railW, lod);
d = min(d, max(arc - rw, abs(r - railR) - rw));
// The iris plates. A bulkhead every few units with a hole punched in it
// just outside the rails, so the shot is a series of apertures you fall
// through rather than a smooth pipe. Their inner rims face the lamp and
// catch it, which puts a stack of concentric bright rings down the
// tunnel - a completely different silhouette from the bare configuration
// for eight instructions, on the shots that ask for it.
if (c.ringOn > 0.5) {
float zr = frac(q.z * c.ringISp + 0.5) * c.ringSp - c.ringSp * 0.5;
d = min(d, max(abs(zr) - max(c.ringTh, lod),
(railR + c.ringGap) - r));
}
// The pipe the relief is carved into. Anything past `wall` is solid, so
// the frame is never black holes with a few struts in them, and rays
// that would otherwise fly off into nothing terminate - which makes the
// march cheaper, not more expensive.
d = min(d, wall - r);
// Hollow out the throat we fly down. Parts of the lattice that reach too
// far inward are simply cut off here, so the fold angle and the scale
// can be pushed hard without ever walling the camera in.
d = max(d, bth - r);
return d;
}
float map(float3 p, float lod) { return mapT(toTube(p), lod); }
// Tetrahedron sampling: four map evaluations rather than the usual six. This
// is the most expensive map in the demo, and at 640x360 through a dithered
// ramp the slightly noisier normal is invisible while the two evaluations it
// saves are not.
//
// The offset grows with the pixel footprint. A fixed 0.0018 is right at two
// units and wrong at forty, where it samples inside one strut of a lattice
// finer than the pixel and returns a normal that changes completely between
// one frame and the next - which is a shimmer no amount of fogging hides.
// Sampling at the scale you can actually see is the whole trick.
float3 mapNormal(float3 p, float lod)
{
float2 e = float2(1.0, -1.0) * max(0.0018, lod * 0.60);
float3 g = e.xyy * map(p + e.xyy, lod) + e.yyx * map(p + e.yyx, lod) +
e.yxy * map(p + e.yxy, lod) + e.xxx * map(p + e.xxx, lod);
// Safe normalize: four taps of a folded field can in principle cancel,
// and one NaN pixel here is a NaN the CRT pass then smears across a
// neighbourhood. Three instructions to never find out.
return g * rsqrt(max(dot(g, g), 1e-12));
}
// Cheap ambient occlusion: how much of the field crowds in along the normal.
// With one distant lamp doing all the lighting, this is what actually carves
// the relief - without it the wall reads as a smooth painted cylinder.
//
// The probe distances stretch with the footprint for the same reason the
// normal offset does: probing 5 cm into a field that has been coarsened to
// 20 cm measures nothing. The final scale divides the stretch back out so
// the amount of occlusion is the same at every depth.
float occlusion(float3 p, float3 n, float lod)
{
float sca = 1.0 + lod * 6.0;
float o = 0.0, s = 1.0;
[loop] for (int i = 0; i < 5; i++) {
float d = (0.05 + 0.15 * float(i)) * sca;
o += (d - map(p + n * d, lod)) * s;
s *= 0.62;
}
return saturate(1.0 - (1.35 / sca) * o);
}
// ---- shading -------------------------------------------------------------
float4 main(VSOut i) : SV_Target
{
Cfg c = cfg();
float2 uv = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y is FLIPPED here on purpose. The fullscreen triangle emits
// uv.y = 0 at the top of the screen, so i.uv*2-1 gives -1 up
// there and the top of the frame ended up looking DOWNWARD -
// the cathedral vault springs at y=+12 and was rendering in the
// lower half, the monolith hung from the ceiling.
uv.x *= gTime.w;
float3 fw = normalize(gDir.xyz);
float3 rt = normalize(cross(float3(0.0, 1.0, 0.0), fw));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 ro = gCam.xyz;
float3 rd = normalize(fw + (uv.x * (rt * cr + up * sr) +
uv.y * (up * cr - rt * sr)) * gCam.w);
float op = saturate(gTune.z);
// Radius of this pixel's footprint per unit of depth. Uniform across the
// frame, so it costs one multiply and never a derivative.
float lodRate = gCam.w * PIXTAN;
// The lamp, in tube space: on the axis, down the tunnel from wherever the
// camera is. It travels with the shot, so the bright core stays pinned to
// the vanishing point however the camera moves.
//
// Its distance grows as the tunnel opens up. A fixed distance is right for
// a tight bore and washes a wide one out to flat amber, because an open
// tunnel puts far more wall within a few units of the lamp; scaling it
// with the room keeps the lit core about the same size on screen whatever
// the shot does with tune.z.
float lampD = LAMP * (1.0 + 0.45 * op);
float3 tube0 = toTube(ro);
float3 lamp = float3(0.0, 0.0, tube0.z + lampD);
// The ray, in tube space, as the secant across exactly the distance the
// lamp sits at. toTube is a translation that varies slowly with depth, so
// the tube-space ray is not quite the world ray, and over thirteen units
// the difference is enough to slide the bright core visibly off the hole
// it is supposed to be sitting in.
float3 trd = normalize(toTube(ro + rd * lampD) - tube0);
float t = 0.05;
float glow = 0.0;
float3 q = tube0;
bool hit = false;
// The march. 0.62 of a step rather than a full one, because a polar fold,
// a domain repeat and an IFS all overestimate distance near their fold
// planes, and at a full step they all show up as the same artifact: a
// hard bitten edge where a strut should be.
[loop] for (int k = 0; k < 56; k++) {
q = toTube(ro + rd * t);
float lod = lodRate * t;
float h = mapT(q, lod);
// Haze around the lamp, accumulated along the ray. This is what fills
// the throat with air, and it costs no extra map evaluations because
// the march is already here. It is the AIR, though, not the core -
// see the core term below for why that distinction is worth the
// handful of instructions it costs.
float dl = length(q - lamp);
glow += min(h, 0.7) * exp(-t * c.fogK) / (1.0 + dl * dl * 0.09);
// Stop when the remaining distance is under half a pixel. Tying the
// threshold to the footprint rather than to a hand-tuned slope means
// it tracks the field of view: a wide shot spends fewer steps
// resolving something it is going to draw coarsely anyway.
if (h < lod * 0.45 + 0.0008) { hit = true; break; }
t += h * 0.62;
if (t > 80.0) break;
}
float lodHit = lodRate * t;
// Bands of colour sweeping up the tunnel toward the camera. This is the
// psychedelic half of the brief, and it is deliberately only two hues -
// the demo's warm amber and its phosphor green - because a full rainbow
// would fight both the palette and the narrow ramp the post pass dithers
// into. Banding it along z rather than by time means the colour is
// attached to the structure and arrives with it.
//
// The period is per shot, twenty to thirty-six units, which is one to
// three bands across the depth the fog leaves visible. At the 0.085 it
// used to be, the period was seventy-four units - longer than you can
// see - so there were never any bands, only one slowly changing wash,
// and the one thing the shot promised the eye it never delivered.
float band = sin(q.z * c.bandFrq + gTime.x * 0.7) * 0.5 + 0.5;
float3 hot = lerp(float3(1.00, 0.63, 0.26),
float3(0.36, 1.00, 0.56),
smoothstep(0.28, 0.80, band));
float3 deep = float3(0.021, 0.027, 0.046); // near black, slightly blue
// The air gets its hue from the lamp's depth, not from wherever this
// pixel's march happened to stop. Sampling the band at the end of the
// ray means two neighbouring pixels that terminated a step apart pick up
// different hues, and the throat - which is nothing BUT air - fills with
// colour noise that the dither then locks into a crawling pattern. One
// hue for the whole haze, drifting as the structure passes.
float bandA = sin(lamp.z * c.bandFrq + gTime.x * 0.7) * 0.5 + 0.5;
float3 hotA = lerp(float3(1.00, 0.63, 0.26),
float3(0.36, 1.00, 0.56),
smoothstep(0.28, 0.80, bandA));
float3 col = deep;
if (hit) {
float3 p = ro + rd * t;
float3 n = mapNormal(p, lodHit);
// Toward the lamp. Legal as a world direction only because toTube is
// a translation at every depth - see the note on it.
float3 lv = lamp - q;
float dl = length(lv);
float3 ld = lv / max(dl, 0.001);
// The key. Falloff is gentler than inverse square on purpose: true
// inverse square over a 60 unit tunnel puts everything past the first
// few metres into the black, and then there is no relief left to look
// at, only a bright hole. The master peak lifts it - base * (1 + k),
// so the floor never drops out from under the picture.
float key = saturate(dot(n, ld)) * (8.5 / (1.0 + dl * dl * 0.032))
* (1.0 + 0.30 * saturate(gSync.w));
// A dim fill from the axis itself, so the walls sliding past the
// camera are dark rather than absent. Without it the near field is a
// black frame around a bright hole and the sense of speed goes.
// At 0.40 over a 0.30 falloff it was worth about one extra unit of
// `deep` on the near wall, which is to say it was not doing its job;
// this reaches the far side of the open configuration as well.
float ra = length(q.xy);
float fil = saturate(dot(n, normalize(float3(-q.x, -q.y, 0.25))))
* (0.55 / (1.0 + ra * ra * 0.22));
float ao = occlusion(p, n, lodHit);
float fre = pow(1.0 - saturate(dot(n, -rd)), 3.0);
// The key is the warm-to-green lamp light; the fill is deliberately
// COLD. Lighting both with the same hue washes the entire frame one
// colour and the palette collapses - the walls have to fall back to
// the demo's blue-black for the amber core to read as warm at all.
col = hot * key * ao;
col += float3(0.30, 0.42, 0.68) * fil * ao;
col += deep * 1.6 * ao;
// The glass. Grazing angles pick up the light, which is what turns
// the open configuration from a dark lattice into something lit from
// inside. Mostly off when the tunnel is tight, because a tight tunnel
// wants to be a silhouette.
col += hot * fre * (0.18 + 1.15 * op) * (1.0 + 0.45 * saturate(gVoice.y)) * ao;
// A hard specular, off the same lamp. The lattice is glass in the
// open configuration and stone in the tight one, and one exponent
// scaled by openness is the whole difference between those two
// materials. It lands on the flat faces the IFS is built out of, so
// it reads as facets catching the light rather than as a sheen.
float3 hv = normalize(ld - rd);
float spe = pow(saturate(dot(n, hv)), 26.0) * (0.20 + 1.30 * op);
col += hot * spe * (0.40 + 0.60 * ao);
}
// Fog the surfaces back into the dark, then add the air on top: the glow
// IS the depth cue, so it must not be faded by the thing it is cueing.
float f = exp(-t * c.fogK);
col = col * f + deep * (1.0 - f);
col += hotA * glow * 0.13;
// The lamp itself. The accumulated haze above cannot do this on its own:
// it is a sum over march steps, so its brightness depends on how many
// steps a pixel happened to take, and down the middle of a hollow bore
// that count changes by one between neighbouring pixels. The result is a
// core that is grey rather than blown out AND that flickers a step at a
// time. This term is closed form - the perpendicular distance from the
// ray to the lamp - so it is smooth across the frame and dead steady in
// time, and it is the white in "white core, amber relief, black walls".
// Same construction as the source down the nave in scene.hlsl.
{
float3 lw = lamp - tube0;
float tc = max(dot(lw, trd), 0.0);
float3 pv = lw - trd * tc;
float perp = length(pv);
float core = 1.0 / (1.0 + perp * perp * 2.2);
// ...and it wears the tunnel's own symmetry. The core is the single
// brightest thing in the frame and it was a featureless dot in every
// one of the eight appearances; giving it the shot's fold count turns
// it into a four, six, eight, ten or twelve armed star that turns
// with the structure. It is a modulation of a small bright region
// about its own mean, not a gate on it, so nothing here flashes.
// The 1e-6 is not decoration. pv.xy is exactly zero for the pixel
// whose ray points straight down the barrel at the lamp, atan2 of
// (0,0) is not defined, and one NaN in the brightest pixel in the
// frame is a NaN the CRT pass then smears over a neighbourhood.
float pa = atan2(pv.y + 1e-6, pv.x + 1e-6) + gTime.x * c.spin;
float star = 1.0 + 0.45 * cos(pa * c.folds);
// Squared so it is a small hard core rather than a broad grey wash,
// and scaled past 1.0 so the middle of it clips to the top of the
// post pass ramp instead of dithering somewhere in the mid greys.
col += hotA * core * core * 3.2 * star * (tc < t ? 1.0 : 0.30);
}
return float4(col * gTime.z, 1.0);
}

310
fx/logo.hlsl Normal file
View file

@ -0,0 +1,310 @@
// SC_LOGO: one solid CRTKAFA sculpture, then a flight into its conduit.
// Scene layout: word centred at (0,0,0), width 11.6, height 2.2,
// depth 1.1. Tunnel axis +Z, inner radius approximately 8.
// gTime.x is absolute intro seconds, 0..7.25; no modulo / logo repeats.
// gTune = (twist adjustment, metal warmth, emission adjustment, camera mode).
// Recommended (0,0,0,0). w < .5 uses introCamera below; w >= .5 uses
// gCam.xyz/gDir verbatim. gCam.w remains tan(vertical FOV/2) in BOTH modes;
// recommend .48, with .48 fallback for an unset value. gTime.w = aspect.
// For CPU meshes/depth compositing, mirror introCamera on CPU or use w=1.
// All other Scene fields have the same layout as scene.hlsl.
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
float segment(float2 p, float2 a, float2 b)
{
float2 v = b - a;
return length(p - a - v * saturate(dot(p - a, v) / dot(v, v)));
}
// Stroke centre lines, NOT a bitmap: closed contours have real open counters.
// Each glyph is subsequently extruded, including the counter walls.
float glyph(float2 p, int id)
{
float d = 100.0;
if (id == 0) // C: chamfered bowl, right side visibly open.
{
d = segment(p, float2(.52,.84), float2(.25,1.0));
d = min(d, segment(p, float2(.25,1), float2(-.35,1)));
d = min(d, segment(p, float2(-.35,1), float2(-.58,.72)));
d = min(d, segment(p, float2(-.58,.72), float2(-.58,-.72)));
d = min(d, segment(p, float2(-.58,-.72), float2(-.35,-1)));
d = min(d, segment(p, float2(-.35,-1), float2(.25,-1)));
d = min(d, segment(p, float2(.25,-1), float2(.52,-.84)));
}
else if (id == 1) // R: closed upper bowl AND a diagonal lower leg.
{
d = segment(p, float2(-.55,-1), float2(-.55,1));
d = min(d, segment(p, float2(-.55,1), float2(.28,1)));
d = min(d, segment(p, float2(.28,1), float2(.55,.76)));
d = min(d, segment(p, float2(.55,.76), float2(.55,.30)));
d = min(d, segment(p, float2(.55,.30), float2(.28,.08)));
d = min(d, segment(p, float2(.28,.08), float2(-.55,.08)));
d = min(d, segment(p, float2(-.08,.08), float2(.60,-1)));
}
else if (id == 2) // T
{
d = segment(p, float2(-.60,1), float2(.60,1));
d = min(d, segment(p, float2(0,1), float2(0,-1)));
}
else if (id == 3) // K: two diagonals meet the upright at its middle.
{
d = segment(p, float2(-.55,-1), float2(-.55,1));
d = min(d, segment(p, float2(-.55,-.08), float2(.55,1)));
d = min(d, segment(p, float2(-.25,.23), float2(.60,-1)));
}
else if (id == 5) // F: no lower arm, unlike the R bowl.
{
d = segment(p, float2(-.55,-1), float2(-.55,1));
d = min(d, segment(p, float2(-.55,1), float2(.58,1)));
d = min(d, segment(p, float2(-.55,.12), float2(.35,.12)));
}
else // A, at indices 4 and 6; triangular open counter.
{
d = segment(p, float2(-.62,-1), float2(0,1));
d = min(d, segment(p, float2(0,1), float2(.62,-1)));
d = min(d, segment(p, float2(-.38,-.24), float2(.38,-.24)));
}
return d - .125;
}
float box3(float3 p, float3 b)
{
float3 q = abs(p) - b;
return length(max(q,0.0)) + min(max(q.x,max(q.y,q.z)),0.0);
}
float word(float3 p)
{
// Bounding box is a conservative step outside the glyph neighbourhood.
float bound = box3(p, float3(5.91,1.19,.57));
if (bound > .65) return bound;
// Evaluate adjacent cells too: nearest-centre alone can skip a thinner
// glyph at cell boundaries. There is NO repetition in world Z.
int cell = (int)clamp(floor(p.x / 1.70 + 3.5),0.0,6.0);
float d = 100.0;
[loop] for (int j = -1; j <= 1; ++j)
{
int id = cell + j;
if (id < 0 || id > 6) continue;
float2 q = p.xy - float2((id - 3) * 1.70,0);
float2 e = float2(glyph(q,id),abs(p.z) - .49);
// Minkowski bevel gives lit edge curvature and .55 half thickness.
float solid = min(max(e.x,e.y),0.0) + length(max(e,0.0)) - .06;
d = min(d,solid);
}
return d;
}
float2 conduit(float3 p)
{
float radius = length(p.xy);
float twist = .115 + .035 * clamp(gTune.x,-1.0,1.0);
float a = twist * p.z + .10 * sin(gTime.x * .40);
float2 q = float2(cos(a)*p.x-sin(a)*p.y,
sin(a)*p.x+cos(a)*p.y);
// Four solid helical rails inside a continuous enclosing wall.
float rail = length(float2(abs(q.x)-7.65,q.y)) - .24;
rail = min(rail,length(float2(q.x,abs(q.y)-7.65))-.24);
// Twist metric bound for r <= 9; wall dominates outside that radius.
rail *= .57;
float wall = 8.55 - radius;
float ringZ = (frac((p.z-2.5)/5.0+.5)-.5)*5.0;
float ring = length(float2(radius-8.08,ringZ))-.30;
float d = min(wall,ring);
float material = 2.0;
if (rail < d) { d = rail; material = 3.0; }
return float2(d,material);
}
/* Small, diegetic title stamped into the lower lip of the conduit. This is
intentionally a bitmap-sized mark rather than another giant overlay: the
opening names itself once, then the journey owns the frame. */
static const uint titleRows[56] = {
14,17,16,16,16,17,14, 30,17,17,30,20,18,17,
4,10,17,17,31,17,17, 17,18,20,24,20,18,17,
31,4,4,4,4,4,4, 14,17,17,17,17,17,14,
10,10,31,10,31,10,10, 4,12,4,4,4,4,14
};
uint tinyRow(int id, int y) { return titleRows[clamp(id,0,7)*7+clamp(y,0,6)]; }
float tinyTitle(float2 p)
{
// A finite luminous label on the z=-.65 face. Rows go DOWN the page.
float2 q = float2(p.x + 3.465, -1.55-p.y) / .105;
if (q.x < 0 || q.y < 0 || q.x >= 66 || q.y >= 7) return 0;
int ci = (int)floor(q.x / 6);
int co = (int)floor(q.x) - ci*6;
int ro = clamp((int)floor(q.y),0,6);
if (ci == 8 || co >= 5) return 0;
int id = ci == 0 ? 0 : ci == 1 ? 1 : ci == 2 ? 2 :
ci == 3 ? 0 : ci == 4 ? 3 : ci == 5 ? 4 :
ci == 6 ? 1 : ci == 7 ? 5 : ci == 9 ? 6 : 7;
uint bits = tinyRow(id,ro);
return float((bits >> (4-co)) & 1u);
}
float2 scene(float3 p)
{
float2 h = conduit(p);
float w = word(p);
if (w < h.x) h = float2(w,1.0);
return h;
}
float3 normalAt(float3 p, float eps)
{
float2 e = float2(1,-1)*eps;
float3 n = e.xyy*scene(p+e.xyy).x + e.yyx*scene(p+e.yyx).x
+ e.yxy*scene(p+e.yxy).x + e.xxx*scene(p+e.xxx).x;
return n * rsqrt(max(dot(n,n),1e-12));
}
float ambientOcclusion(float3 p, float3 n)
{
float occ = 0.0;
float weight = 1.0;
[loop] for (int k=0; k<4; ++k)
{
float r = .09 + .18*k;
occ += max(r-scene(p+n*r).x,0.0)*weight;
weight *= .55;
}
return saturate(1.0-1.5*occ);
}
float shadow(float3 p, float3 l)
{
float visibility = 1.0;
float t = .035;
[loop] for (int k=0; k<16; ++k)
{
float h = scene(p+l*t).x;
visibility = min(visibility,12.0*max(h,0.0)/t);
if (h < .002 || t > 7.0) break;
t += clamp(h,.025,.85);
}
return saturate(visibility);
}
void introCamera(out float3 ro, out float3 fw, out float roll)
{
// Read for 1.5 seconds, then pass the word before the 3.63s cut.
float t = min(gTime.x,1.5)*.60 + max(gTime.x-1.5,0.0)*3.0;
float rush = max(t-2.0,0.0);
float lift = smoothstep(1.9,3.35,t);
float settle = smoothstep(4.3,6.4,t);
ro = float3(1.5*cos(t*.60)*(1.0-settle),
.35 + 2.45*lift*(1.0-settle),
-14.0+1.1*t+2.4*rush*rush);
// Aim at word first, then turn forward BEFORE crossing its plane.
float3 aim = float3(0,0,0)-ro;
float3 readDir = normalize(float3(aim.xy,max(aim.z,3.0)));
fw = normalize(lerp(readDir,float3(0,0,1),smoothstep(2.4,3.65,t)));
roll = .025*sin(t*.9) + .12*settle;
}
float4 main(VSOut input, out float depth : SV_Depth) : SV_Target
{
float3 ro, fw;
float roll;
introCamera(ro,fw,roll);
if (gTune.w >= .5)
{
ro = gCam.xyz;
fw = gDir.xyz * rsqrt(max(dot(gDir.xyz,gDir.xyz),1e-10));
if (dot(fw,fw) < .5) fw = float3(0,0,1);
roll = gDir.w;
}
float3 upHint = abs(fw.y) > .98 ? float3(0,0,1) : float3(0,1,0);
float3 rt = normalize(cross(upHint,fw));
float3 up = cross(fw,rt);
float2 uv = float2(input.uv.x*2-1,1-input.uv.y*2);
uv.x *= max(gTime.w,.1);
float fov = max(gCam.w > .01 ? gCam.w : .48, .55/max(gTime.w,.25));
float3 rd = normalize(fw + fov*(uv.x*(rt*cos(roll)+up*sin(roll))
+uv.y*(up*cos(roll)-rt*sin(roll))));
float t = .05;
float material = 0.0;
bool hit = false;
depth = 0.0;
[loop] for (int k=0; k<112; ++k)
{
float2 h = scene(ro+rd*t);
if (h.x < max(.0015,t*.00055))
{
hit = true;
material = h.y;
break;
}
t += max(h.x*.82,.001);
if (t > 145.0) break;
}
float3 deep = float3(.009,.017,.026);
float3 col = deep;
if (hit)
{
float3 p = ro+rd*t;
depth = saturate(.05/max(t*dot(rd,fw),.001));
float3 n = normalAt(p,max(.002,t*.00022));
float ao = ambientOcclusion(p,n);
float3 key = normalize(float3(-.45,.65,-.75));
float diffuse = saturate(dot(n,key));
float shade = shadow(p+n*.018,key);
float fresnel = pow(1.0-saturate(dot(n,-rd)),3.0);
float spec = pow(saturate(dot(n,normalize(key-rd))),48.0);
float3 phosphor = lerp(float3(.35,.95,.69),float3(1,.65,.29),
saturate(.20+gTune.y));
float pulse = 1.0+.12*saturate(gSync.x)+.07*saturate(gVoice.z);
if (material < 1.5)
{
// Front and side are different alloys; bevel joins them visibly.
float front = smoothstep(.65,.97,abs(n.z));
float3 metal = lerp(float3(.12,.23,.26),float3(.65,.77,.71),front);
col = metal*(.15*ao+1.05*diffuse*shade);
col += float3(.65,.79,1)*spec*.75*shade;
col += phosphor*fresnel*.38*ao;
col += phosphor*front*(.08+.09*saturate(gTune.z))*pulse;
col += float3(.16,.28,.42)*saturate(dot(n,normalize(float3(1,-.1,.5))))*.32*ao;
}
else
{
float3 lamp = float3(0,0,ro.z+16.0)-p;
float lampDist = length(lamp);
float lit = saturate(dot(n,lamp/max(lampDist,.001)));
float band = .5+.5*sin(p.z*.19);
float3 tint = lerp(float3(.21,.57,.48),float3(.61,.36,.16),band);
col = tint*(.12+lit*2.2/(1.0+lampDist*lampDist*.008))*ao;
col += float3(.20,.30,.42)*diffuse*.18;
col += tint*fresnel*.18*ao;
if (material > 2.5)
col += phosphor*(.36+.18*saturate(gTune.z))*pulse;
}
col = lerp(deep,col,exp(-t*.010));
}
// Ray/plane hit is bounded in X, Y AND depth. No infinite extrusion.
if (rd.z > .001 && ro.z < -.65) {
float labelT = (-.65-ro.z)/rd.z;
float2 xy = (ro+rd*labelT).xy;
if (labelT > .05 && (!hit || labelT < t) &&
abs(xy.x) < 3.7 && xy.y < -1.37 && xy.y > -2.48) {
float ink = tinyTitle(xy);
col = lerp(float3(.018,.038,.047),float3(.48,.91,.79),ink);
depth = saturate(.05/(labelT*dot(rd,fw)));
}
}
return float4(max(col,0.0)*saturate(gTime.z),1.0);
}

294
fx/mesh.hlsl Normal file
View file

@ -0,0 +1,294 @@
// Meshes, pulled rather than fed.
//
// Nothing is bound to the input assembler - no vertex buffer, no index
// buffer, no input layout. The vertex shader reads straight out of two typed
// buffers laid over the `const short` arrays in cats_mesh.h, and the draw is
// Draw(NT*3, 0) with the index fetched here.
//
// That is not stylistic. Three things fall out of it:
//
// There is no DXGI_FORMAT_R16G16B16_SINT, so an input layout would have to
// pad the 6-byte vertices to 8 - about 19 KB on the run cat alone, in an
// executable where the shader blobs are already the biggest thing.
//
// A typed R16_SINT buffer has a 2-byte stride, so the baked arrays upload
// verbatim. pSysMem points at the header array: no copy, no allocation,
// nothing a C runtime would have to be present for.
//
// Drawing non-indexed means the triangle id is just vid/3, so a per-triangle
// flat colour needs no vertex duplication, and the barycentric is
// float3(vid%3 == 0, 1, 2) - which is a wireframe-to-solid morph for free.
//
// The cost is one dependent load per vertex on a 790-triangle mesh.
//
// ---------------------------------------------------------------------------
// W H Y T H E R E I S A R I G D O W N T H E R E
//
// The 24 baked frames are the whole of the cat's motion, and the rate they
// play at is not free: actRate in the shot table is tuned so a stride covers
// about two body lengths of the from -> to travel, because anything else makes
// the feet skate. Run the numbers on bar 35 - 10.33 units of travel over 32
// rows at 0.63 frames a row - and the cat gets through FOUR FIFTHS of one
// stride in the entire shot. Bar 59 gets through half of one. That is the
// honest reason the cat reads as furniture: not that the animation is bad, but
// that at a skate-free rate there is barely any of it inside a two-bar shot.
//
// The rate cannot go up without the feet sliding. So everything below is
// SECONDARY motion - the parts of an animal that are not carrying its weight
// and are therefore free to move as fast as they like. A tail that lashes, a
// head that turns, ears that flick, a spine that flexes, a ribcage that
// breathes, and a body that sinks into its knees when the kick lands. The legs
// are deliberately left alone: they are doing the one job the baked frames
// already do well, and anything added to a planted paw is a skate.
//
// The rig weights are plain thresholds in the mesh's own baked integer space,
// which is why fetchVert no longer applies gAnim.z - the quantiser scale is
// applied once, at the end, and until then a number in this file can be read
// straight against cats_mesh.h. Measured off the array: the cat faces +X, the
// animation is entirely in XY (z is constant per vertex to within a unit or
// two, which is what a sagittal run cycle looks like), the tail runs from
// x=-9800 out to x=-15200, the paws bottom out around y=-6400, and the head is
// everything past x=+6600.
//
// THE THRESHOLDS CANNOT BE TAKEN OFF THE ANIMATED POSE. A paw swings 8500
// units of x during a stride - a front paw reaches x=+8800, which is deeper
// into head territory than the head is, and a rear paw reaches x=-11600, which
// is halfway down the tail. Segment on that and the rig grabs a foot. So the
// weights are read off `rf`: the midpoint of the current frame and the one
// half a cycle away. A pair of legs is in antiphase, so the midpoint very
// nearly cancels the swing - it drops the worst per-vertex x wander over the
// cycle from 15387 units to 3169, and the median from 2643 to 599 - and what
// is left is a bind pose in all but name. Three extra loads, and after it the
// paws never once cross a threshold: they stay inside x = [-9740, +6515] while
// the tail sits below -9770 and the head above +6680.
//
// Four appearances, all ACT_CAT_RUN in the corridor, and gTune.z happens to
// track the energy of each one exactly: 0.20 at bar 59 (the sparse solo
// entry, the slowest gait in the demo), 0.30 at bar 35, 0.50 at bar 43, 0.60
// at bar 77 (the tension phase, the fastest). So gTune.z is read here as
// AGITATION and it drives every amplitude in the rig. The bar 59 cat prowls;
// the bar 77 cat is coming apart. That is one animal with four moods rather
// than the same silhouette pasted in four times.
// ---------------------------------------------------------------------------
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look direction, w roll
float4 gTune;
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
cbuffer Mesh : register(b1)
{
float4 gModel; // xyz world position, w uniform scale
float4 gAnim; // x fractional frame, y frame count (1 = rigid), z quant scale, w yaw
float4 gMisc; // x vertices per frame, y wireframe 0..1, z shatter, w tint
};
Buffer<int> gPos : register(t0);
Buffer<uint> gIdx : register(t1);
struct VSOut
{
float4 pos : SV_Position;
float3 wp : TEXCOORD0; // world position, for the face normal
float3 bary : TEXCOORD1;
float vz : TEXCOORD2; // view depth, for the fog
};
// Raw baked units. gAnim.z is deliberately NOT applied here - see above.
float3 fetchVert(uint vtx, uint frame)
{
uint o = (frame * (uint)gMisc.x + vtx) * 3u;
return float3(gPos.Load((int)o), gPos.Load((int)(o + 1u)),
gPos.Load((int)(o + 2u)));
}
VSOut main(uint vid : SV_VertexID)
{
VSOut o;
uint vtx = gIdx.Load((int)vid);
// The baked run cycle is 24 frames of plain vertex positions, and the
// frame index is FRACTIONAL because it comes from the song's row clock
// rather than a wall clock - the old demo stepped them against wall-clock
// time and the cat never once landed on the beat.
//
// It used to lerp two frames. At the skate-free rate the cat is only
// getting about 5.6 frames a second, so a straight line between them holds
// each limb at a constant velocity for 180 ms and then turns a corner, and
// the corner is visible - the legs tick. Catmull-Rom over four frames
// costs six more loads on a 396-vertex mesh and makes the velocity
// continuous, which is the difference between a flipbook and an arc. The
// cycle loops, so the neighbours wrap; at frac == 0 it returns frame f1
// exactly, which is what ACT_CAT_STILL depends on.
uint nf = max((uint)gAnim.y, 1u);
float3 p;
if (nf == 1u)
{
// Static props have their own proportions: no cat rig or interpolation.
p = fetchVert(vtx, 0u) * gAnim.z;
}
else
{
uint f1 = (uint)gAnim.x % nf;
uint f0 = (f1 + nf - 1u) % nf;
uint f2 = (f1 + 1u) % nf;
uint f3 = (f1 + 2u) % nf;
float t = frac(gAnim.x);
float3 P0 = fetchVert(vtx, f0), P1 = fetchVert(vtx, f1);
float3 P2 = fetchVert(vtx, f2), P3 = fetchVert(vtx, f3);
float3 g = 0.5 * (2.0 * P1
+ (P2 - P0) * t
+ (2.0 * P0 - 5.0 * P1 + 4.0 * P2 - P3) * t * t
+ (3.0 * (P1 - P2) + P3 - P0) * t * t * t);
// The stand-in bind pose: this frame averaged with its opposite. Nothing
// below reads a threshold off `g`, only off `rf`. nf>>1 is 0 for a
// single-frame mesh, which degenerates to the frame itself, correctly.
float3 rf = 0.5 * (P1 + fetchVert(vtx, (f1 + (nf >> 1)) % nf));
// ---- the rig -------------------------------------------------------
// ag agitation, the one number that separates the four appearances
// sd a phase seed, so two cats never start a sway on the same beat
// st seconds into THIS shot, for the drifts that must not be periodic
// gp gait phase, 2*pi per stride, off the row clock and so beat-locked
// dr whichever of the two loud voices is actually playing
float ag = saturate(gTune.z * 1.6);
float sd = gTune.x * 31.0 + gTune.y * 17.0 + gTune.z * 57.0;
float st = gTime.x;
float gp = 6.2831853 * gAnim.x / (float)nf;
float dr = gVoice.x * 0.45 + gVoice.y * 0.55;
// The three weights the whole rig is built out of, all in bind space.
// tail past the root of it, and thin with it - a tail stays inside
// |z| = 788 where a hind leg reaches 1578, so the second gate
// holds even where the first one is tight
// head starts at 6550, which is 35 units clear of the furthest a paw
// ever reaches, so the head rotation can never catch a foot
// torso how far above the feet: 0 at every paw (they top out at -1510),
// 1 through the spine. This is what keeps the legs out of the
// weave and turns the body's sink into knee compression.
float tail = (1.0 - smoothstep(-14800.0, -9755.0, rf.x))
* (1.0 - smoothstep(900.0, 1400.0, abs(rf.z)));
float head = smoothstep(6550.0, 9200.0, rf.x);
float torso = smoothstep(-1400.0, 900.0, rf.y);
float3 d = float3(0.0, 0.0, 0.0);
// TAIL. A travelling wave with the phase lagging further the further out
// along it you go, which is what makes a tail read as a whip rather than a
// rod, and the lag itself opens up with agitation. Amplitude is
// base + k*voice, never base*voice: a silent bar still has a moving tail.
float lag = tail * (2.2 + 1.7 * ag);
float tp = gp * 2.0 + sd - lag;
float ta = 320.0 + 820.0 * ag + 420.0 * dr;
d.z += tail * ta * sin(tp);
d.y += tail * ta * 0.40 * sin(tp * 0.5 + 1.1);
d.y += tail * (200.0 + 450.0 * ag) * sin(st * 0.55 + sd);
// SPINE. A lateral S about one wavelength along the body, plus an arch
// that peaks between the two leg pairs at x = -1750 - the mid-back is the
// part of a running cat that actually bends.
d.z += torso * (110.0 + 320.0 * ag) * sin(rf.x * 0.00022 + gp * 2.0 + sd);
float mid = 1.0 - saturate(abs(rf.x + 1750.0) / 9000.0);
d.y += torso * mid * (150.0 + 470.0 * ag) * sin(gp * 2.0 + 0.7);
// The kick lands in the knees. The body sinks and the paws do not, because
// `torso` is zero down there, so the legs compress instead of the cat
// teleporting. base + k*s, so muting the drums leaves a deliberate stance.
d.y -= torso * (0.35 + 0.65 * ag) * (90.0 + 520.0 * gSync.x);
// BREATHING. Ribcage only - not the head, not the tail, not the legs. It
// is small on purpose: this is the thing that stops a held frame from
// being a still, and it should reward a second look rather than announce
// itself. Proportional to the vertex's own offset, so it is a scale.
float rib = torso * (1.0 - head) * (1.0 - tail)
* saturate(1.0 - abs(rf.x + 1000.0) / 8000.0);
float br = sin(st * 1.7 + sd * 0.3);
d.z += rib * g.z * (0.030 + 0.045 * gVoice.z) * br;
d.y += rib * g.y * (0.020 + 0.030 * gVoice.z) * br;
// HEAD. Yawed and pitched about the base of the neck, on two slow
// incommensurable periods so it never repeats inside a shot, and lifted by
// the guitar. The rotation is applied to the live pose but blended in by a
// bind-space weight, so the shoulders carry the shear and nothing else in
// the mesh can wander into it.
float hyaw = (0.05 + 0.15 * ag) * sin(st * 0.83 + sd)
+ 0.04 * sin(st * 2.70 + sd * 1.7);
float hpit = (0.04 + 0.10 * ag) * sin(st * 0.61 + sd * 0.5)
+ 0.07 * gVoice.x;
float3 hv = g - float3(6550.0, 500.0, 0.0);
float cy = cos(hyaw), sy = sin(hyaw);
float3 hr = float3(hv.x * cy - hv.z * sy, hv.y, hv.x * sy + hv.z * cy);
float cp = cos(hpit), sp = sin(hpit);
hr = float3(hr.x * cp - hr.y * sp, hr.x * sp + hr.y * cp, hr.z);
d += (hr - hv) * head;
// EARS. The top of the head only, each one on its own phase, flicking on
// the hat. Tiny in world units - the ears are tiny - but they are the
// outermost points of the silhouette and the rim light finds them.
float ear = head * smoothstep(1900.0, 3100.0, rf.y);
float side = rf.z >= 0.0 ? 1.0 : -1.0;
float fk = sin(gp * 6.0 + sd + side * 1.9);
d.z += ear * side * (60.0 + 400.0 * gVoice.w) * fk;
d.y -= ear * (30.0 + 180.0 * gVoice.w) * (0.5 + 0.5 * fk);
// WEAVE. The whole body yaws a few degrees as it runs, pinned at the
// paws again, so head and tail swing opposite ways. This is the one that
// makes it look like it has mass.
float wv = (0.015 + 0.045 * ag) * sin(gp + sd * 0.7)
+ 0.020 * sin(st * 0.47 + sd);
float cw = cos(wv), sw = sin(wv);
d += (float3(g.x * cw - g.z * sw, g.y, g.x * sw + g.z * cw) - g) * torso;
// Out of the baked integer space, once.
p = (g + d) * gAnim.z;
}
// Shatter: push each triangle out along its own pseudo-random axis. The
// seed is the triangle id, so a face stays whole while it flies.
if (nf > 1u && gMisc.z > 0.001)
{
uint tri = vid / 3u;
float s = frac(sin(float(tri) * 12.9898) * 43758.5453);
float s2 = frac(sin(float(tri) * 78.2330) * 24634.6345);
float s3 = frac(sin(float(tri) * 39.4260) * 13875.9284);
p += (float3(s, s2, s3) - 0.5) * gMisc.z * gMisc.z * 14.0;
}
float ca = cos(gAnim.w), sa = sin(gAnim.w);
p = float3(p.x * ca - p.z * sa, p.y, p.x * sa + p.z * ca);
float3 wp = p * gModel.w + gModel.xyz;
// The camera basis, built the same way every scene shader builds it, so
// a mesh and the distance field behind it agree about where things are.
float3 fw = normalize(gDir.xyz);
float3 rt = normalize(cross(float3(0.0, 1.0, 0.0), fw));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 r2 = rt * cr + up * sr;
float3 u2 = up * cr - rt * sr;
float3 dv = wp - gCam.xyz;
float z = dot(dv, fw);
// Clip space by hand. The scene shaders cast normalize(fw + (uv.x*r2 +
// uv.y*u2) * gCam.w), so a point lands at uv = (x, y) / (z * gCam.w) -
// and w = z with 0.05 in the z slot reproduces the SDF passes' own
// saturate(0.05 / vz), which is what puts them on the same depth scale.
// Keep signed w: hardware clips at z = 0.05 and rejects geometry behind
// the eye instead of projecting it onto a tiny positive denominator.
o.pos = float4(dot(dv, r2) / (gCam.w * gTime.w),
dot(dv, u2) / gCam.w,
0.05, z);
o.wp = wp;
o.vz = z;
uint c = vid % 3u;
o.bary = float3(c == 0u ? 1.0 : 0.0, c == 1u ? 1.0 : 0.0, c == 2u ? 1.0 : 0.0);
return o;
}

283
fx/meshps.hlsl Normal file
View file

@ -0,0 +1,283 @@
// The pixel half of the mesh path.
//
// No baked normals are read. The face normal comes from the screen-space
// derivatives of the world position, which is exact for a flat triangle and
// costs two instructions - and it means the 900-odd bytes of baked normals in
// the mesh headers never have to be uploaded at all.
//
// The lighting deliberately matches what the distance-field scenes do: one
// warm key, a cool fill from above, and the same exponential fog. A mesh that
// is lit by different rules than the space it is standing in reads as a
// sticker on the frame, however good it looks on its own.
//
// ---------------------------------------------------------------------------
// W H Y T H I S F I L E S H A D E S I N B O D Y S P A C E
//
// Every appearance of the cat is a broadside pass across a corridor. Yaw is 0
// in all four shots, the mesh's long axis is world X, and the camera sits near
// the middle of the corridor looking down Z - so what reaches the screen is
// the animal's FLANK, nearly face on. A flat-shaded flank is one continuous
// surface whose face normal barely moves across it, so ANYTHING BUILT OUT OF N
// IS VERY NEARLY A CONSTANT over the two thousand-odd pixels that matter. That
// is the exact mechanism by which a cat becomes a black lozenge with a green
// edge on it, and no amount of relighting fixes it.
//
// It is also physically true rather than a rendering accident: the only lights
// in a corridor are the ceiling tubes and the two side walls, and all three
// are edge-on to a vertical flank. A real cat crossing a real corridor really
// is nearly unlit on the side we can see. So the form cannot be lit into
// existence - it has to be DRAWN, out of where a point sits in the animal.
//
// Which meant measuring the animal. The 24 baked frames were dumped and
// rasterised offline; the cycle turned out to be in place (mean X moves 0.118
// over the whole cycle), so a body-space constant stays put on the body. The
// landmarks below are the same ones the rig in mesh.hlsl weights against -
// same numbers, converted out of baked integer space - so the two halves of
// the mesh path cannot drift apart about where the cat's parts are:
//
// x -0.96 ....................................... +0.77 (mesh units)
// |<-- tail, -0.89 to -0.56 -->|
// haunch -0.44 waist -0.12 shoulder +0.30
// head, +0.39 to +0.59 and beyond
// y -0.41 paws/floor ... 0 spine ... +0.24 ear roots ... +0.33 arch
// z +-0.15 flanks
//
// P E R A P P E A R A N C E. The cat runs four times, always inside
// SC_CORRIDOR, so gTune is the corridor's own knob set and the honest thing is
// to obey it rather than invent a second, disagreeing one:
//
// gTune.x corridor width -> how much the two side walls bounce back on it
// gTune.y ceiling height -> how high the fitting that lights it hangs
// gTune.z bend -> the coat: band count, contrast, edge width
//
// gTune.z is 0.30 / 0.50 / 0.20 / 0.60 across the four, which is the widest
// spread on offer, and mesh.hlsl already reads it as the animal's AGITATION.
// This file reads the same axis as how GRAPHIC the animal is: four wide soft
// bands and a thin hard edge at the calm end, ten fine bands and a fat edge at
// the frantic one. One quantity, two halves of the same idea, so the bar 59
// cat prowls and looks plain and the bar 77 cat is coming apart and looks it.
//
// Legibility is NOT keyed off gModel.w. It is keyed off fwidth of the body
// coordinate - how many mesh units one pixel is worth on this draw - so a cat
// that is small because it is far away reads the same as one that is small
// because it was scaled down, and neither can be got wrong by the shot table.
//
// Measured against the shader this replaces, on the bar 35 pass at 1080p:
// mean level 0.172 -> 0.182 (the exposure is meant to be unchanged), but the
// standard deviation across the animal 0.087 -> 0.118, and the mean pairwise
// gap between the four appearances 17.97 -> 21.90. Wider tonal range on one
// cat, and four cats that no longer look like the same picture.
// ---------------------------------------------------------------------------
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
cbuffer Mesh : register(b1)
{
float4 gModel;
float4 gAnim;
float4 gMisc; // x verts/frame, y wireframe 0..1, z shatter, w tint
};
struct VSOut
{
float4 pos : SV_Position;
float3 wp : TEXCOORD0;
float3 bary : TEXCOORD1;
float vz : TEXCOORD2;
};
// Original per-triangle RGB, expanded to RGBA8_UNORM once at upload.
// Only single-frame models use this resource; the run cat keeps its coat.
Buffer<float4> gFaceColor : register(t2);
// One fitting every four metres, the same spacing corridor.hlsl uses. The two
// files have to agree about this or the cat lights up in the dark half of a
// bay and stops belonging to the room it is running through.
#define FIX_PERIOD 4.0
float bump(float x, float c, float k) { float d = (x - c) * k; return exp(-d * d); }
float4 main(VSOut i, uint tri : SV_PrimitiveID) : SV_Target
{
float3 n = normalize(cross(ddx(i.wp), ddy(i.wp)));
// Face the light rather than the camera: a flat-shaded mesh whose normals
// point away just goes black, and a demo prop is never seen from behind.
float3 vdir = normalize(gCam.xyz - i.wp);
if (dot(n, vdir) < 0.0) n = -n;
if (gAnim.y == 1.0)
{
float3 base = gFaceColor.Load((int)tri).rgb;
float key = saturate(dot(n, normalize(float3(-0.35, 0.80, -0.45))));
float fill = saturate(dot(n, normalize(float3(0.65, 0.30, 0.55))));
// Neutral light preserves the blue paint, pale windows and dark trim.
// Ambient keeps a distant face readable even when the key is behind it.
float3 col = base * (0.60 + 0.55 * key + 0.15 * fill);
float fog = exp(-max(i.vz, 0.0) * 0.0075);
col = col * fog + float3(0.055, 0.050, 0.062) * (1.0 - fog);
return float4(col * gTime.z, 1.0);
}
// ---- body space ------------------------------------------------------
// Undo the vertex shader exactly: translate, uniform scale, yaw. The yaw
// is 0 in every shot the cat appears in, but doing it properly costs one
// sine pair on two thousand pixels and means none of the landmarks below
// can come adrift if the C side ever turns the animal.
float iw = 1.0 / max(gModel.w, 1e-4);
float3 rp = (i.wp - gModel.xyz) * iw;
float cy = cos(gAnim.w), sy = sin(gAnim.w);
float3 op = float3(rp.x * cy + rp.z * sy, rp.y, rp.z * cy - rp.x * sy);
float3 on = float3( n.x * cy + n.z * sy, n.y, n.z * cy - n.x * sy);
// One pixel, measured in mesh units. Every fine feature below is floored
// at this, so nothing crawls on the near cat or vanishes on the far one.
float pw = max(max(fwidth(op.x), fwidth(op.y)), fwidth(op.z));
// The same three weights the rig in mesh.hlsl deforms by, so the shading
// and the animation agree about which end of the cat is which.
float head = smoothstep( 0.3875, 0.5875, op.x); // 0 shoulders .. 1 head
float tail = 1.0 - smoothstep(-0.89, -0.56, op.x);// 0 hip .. 1 tail tip
float hgt = saturate((op.y + 0.41) * 1.35); // 0 paws .. 1 crown
// ---- the light the corridor actually has -----------------------------
float ceilH = lerp(2.30, 4.60, saturate(gTune.y));
float cn = floor(i.wp.z / FIX_PERIOD + 0.5);
float cz = cn * FIX_PERIOD;
float dz = max(abs(i.wp.z - cz) - 0.60, 0.0); // metres to the tube
float3 lp = float3(0.0, ceilH - 0.07,
clamp(i.wp.z, cz - 0.60, cz + 0.60));
float3 ld = normalize(lp - i.wp);
// Two metres is the darkest a bay gets, and a quarter is as far as the
// level is allowed to move: base + k*s and never base*s, so the animal
// dims between fittings instead of blinking out.
float bay = 1.0 - 0.24 * saturate(dz * dz * 0.52);
// The demo's standing key, tilted toward whichever fitting is currently
// overhead. The tilt is most of the animation of a held shot: as the cat
// crosses a bay the highlight walks along it and the head turns into and
// out of the light, so two bars on one camera stop being a still.
float3 kd = normalize(lerp(normalize(float3(-0.35, 0.80, -0.45)), ld, 0.24));
float dif = saturate(dot(n, kd));
// Both walls, not the nearer one: picking the nearer one puts a seam down
// the middle of the corridor that the cat pops across at x = 0. A narrow
// corridor throws a great deal back onto the flanks, a wide one almost
// nothing, which is one more thing that separates the four passes.
float hw = lerp(1.15, 3.80, saturate(gTune.x));
float3 wl = float3(-hw, 1.10, i.wp.z) - i.wp;
float3 wr = float3( hw, 1.10, i.wp.z) - i.wp;
float wl2 = max(dot(wl, wl), 0.30), wr2 = max(dot(wr, wr), 0.30);
// Capped, not for the corridor - the widest it gets there is 0.83 - but
// for the mesh-dump path in gfx.c, which draws the cat at the origin with
// gTune all zeroes and would otherwise stand it inside both walls at once.
float bnc = min(saturate(dot(n, wl * rsqrt(wl2))) * (2.4 / (1.4 + wl2))
+ saturate(dot(n, wr * rsqrt(wr2))) * (2.4 / (1.4 + wr2)), 1.0);
// ---- the shape, drawn rather than lit --------------------------------
// Three masses and the gaps between them, on the landmarks measured off
// the mesh: the shoulder over the front legs, the haunch over the rear
// ones, the waist that makes those two read as two, and the head - so the
// front of the animal is brighter than the back and the silhouette has a
// direction even when it is sixty pixels long.
float mass = 1.0
+ 0.28 * bump(op.x, 0.30, 4.0) // shoulder, over the forelegs
+ 0.24 * bump(op.x, -0.44, 3.6) // haunch, over the hind legs
+ 0.20 * bump(op.x, 0.60, 5.0) // head
- 0.17 * bump(op.x, -0.12, 5.2); // the tuck between them
// Back lit, belly not. On a flank that shares one normal this ramp is the
// whole difference between a cat and a stain.
float form = (0.55 + 0.85 * pow(max(hgt, 1e-4), 0.70))
* mass * (1.0 - 0.22 * tail);
// ...but only where the normal is not already doing the job. An up-facing
// back under an overhead tube is genuinely lit and does not want drawing
// on top of; the flank is not lit at all and is nothing else. Without this
// line the two cues stack and the spine blows out to a white stripe.
form = lerp(1.0, form, 1.0 - 0.72 * dif);
// Tabby banding, across the body the way a real one runs. Resolved rather
// than faded by hand: the amplitude dies the moment a band is thinner than
// a pixel, so the far cat is plain instead of a field of crawling noise.
float bands = lerp(4.5, 10.5, saturate(gTune.z));
float ph = (op.x + 0.96) * bands + op.y * 1.25;
float coat = sin(ph * 6.2831853) * saturate(1.0 - fwidth(ph) * 1.8)
* (0.55 + 0.45 * saturate(gTune.z)) * (1.0 + 0.30 * gSync.z);
// The gait, off the same fractional frame the vertex shader poses with, so
// the ripple down the coat lands on the footfalls and not on a wall clock.
// Two waves a cycle, which is the two-beat lope.
float ripp = sin(op.x * 3.2 - (gAnim.x / max(gAnim.y, 1.0)) * 12.566371);
// ---- assemble --------------------------------------------------------
// The cat is a silhouette with a rim on it. It is meant to be read as a
// shape first and a creature second, so the body stays close to black and
// the light lives on the edge.
float3 body = lerp(float3(0.020, 0.024, 0.032),
float3(0.55, 0.72, 0.42), gMisc.w);
float lum = (0.20 + 0.80 * dif + 0.16 * bnc) * form * bay * 1.12;
lum *= 1.0 + 0.20 * coat;
lum *= 1.0 + 0.09 * ripp;
float3 col = body * lum;
// The edge carries the shaping too: fat over the two masses, thin at the
// waist, and pushed up at the two places a cat is recognised from - the
// ears and the last hand's width of tail. A cat that lands small on screen
// gets more of it, because sixty pixels of animal is all outline; one
// pixel is worth about 0.005 mesh units on the near draw and 0.03 on the
// far one, which is what the threshold below is set against.
float small = saturate((pw - 0.008) * 50.0);
float ears = head * smoothstep(0.16, 0.244, op.y);
float rim = pow(1.0 - saturate(dot(n, vdir)),
lerp(4.4, 2.6, saturate(gTune.z)));
float edge = rim * (0.70 + 0.30 * mass)
* (1.0 + 0.45 * ears + 0.45 * tail + 0.45 * small)
* (1.0 + 0.20 * coat);
col += float3(0.42, 0.86, 0.46) * edge * (0.35 + 0.65 * gMisc.w) * bay;
col += float3(0.20, 0.26, 0.38) * saturate(n.y) * 0.15 * (0.60 + 0.40 * form);
// Two catchlights, at the eyes, measured off the mesh. A black cat at
// sixty pixels is read from its eyes before it is read from its outline,
// and this demo has a scene that is nothing but a cat's eye, so a green
// spark here is a callback and not a decoration. Two per cent of body
// length is a real cat's eye; the pixel floor under that radius means the
// spark neither crawls on the near draw nor disappears on the far one.
// It is gated by the same `head` weight the rig turns the head with, so it
// can never strand itself on a shoulder, and it holds a base level so the
// solo lifts it rather than switching it on.
float3 ep = float3(0.645, 0.070, 0.098);
float ed = min(length(op - ep), length(op - float3(ep.x, ep.y, -ep.z)));
float er = max(0.038, pw * 1.15);
float eye = exp(-(ed * ed) / (er * er)) * head
* saturate(abs(on.z) * 1.5 + 0.20);
col += float3(0.58, 1.00, 0.62) * eye
* (0.55 + 0.40 * gVoice.y + 0.35 * gMisc.w);
// Wireframe-to-solid, out of the barycentric the vertex shader got for
// nothing. At gMisc.y = 1 only the edges survive.
if (gMisc.y > 0.001)
{
float3 d = fwidth(i.bary);
float3 a = smoothstep(float3(0,0,0), d * 1.5, i.bary);
float wf = 1.0 - min(min(a.x, a.y), a.z);
col = lerp(col, float3(0.55, 0.95, 0.60) * wf, gMisc.y);
}
float fog = exp(-max(i.vz, 0.0) * 0.0075);
col = col * fog + float3(0.055, 0.050, 0.062) * (1.0 - fog);
return float4(col * gTime.z, 1.0);
}

321
fx/orbital.hlsl Normal file
View file

@ -0,0 +1,321 @@
// ORBITAL / original analytic worlds. D3D11 ps_5_0, no resources.
// gTune = (floor variant 0..2, animation rate 0..2, emission 0..2, tilt radians).
// Zero rate still moves. gTime.x is seconds; camera is never replaced.
// Suggested eye / at / vertical FOV degrees / camera speed / tune:
// 0: (0,3.8,-12) / (0,0,0) / 44 / TRACK .35 / (0,1,1,.22), ONE flyby.
// 1: (0,2.9,-13) / (0,0,0) / 46 / ORBIT .07 / (1,.8,1,-.18).
// 2: (0,1,-11) / (0,0,0) / 48 / TRACK .30 / (2,1,1,.15).
// Bounds centered at origin: 0 sphere R=5.7 (planet R=2.6),
// 1 sphere R=6.5 (opaque core R=1.48); 2 sphere R=5.3.
// Keep camera outside those bounds; slow track/orbit gives strong parallax.
// Transparent sheets composite in ray order, behind nearest opaque surface.
// Depth is nearest visible layer at .05/viewZ, sky is infinite (zero).
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
struct PSOut { float4 color : SV_Target; float depth : SV_Depth; };
static const float PI = 3.14159265359;
static const float FAR_T = 1e5;
static const float3 CYAN = float3(.12,.78,1.0);
static const float3 AMBER = float3(1.0,.43,.105);
static const float3 PINK = float3(.78,.095,.45);
static const float3 SUN = float3(-.57735,.57735,-.57735);
float hash31(float3 p)
{
p = frac(p * .1031);
p += dot(p, p.yzx + 33.33);
return frac((p.x + p.y) * p.z);
}
float noise3(float3 p)
{
float3 b = floor(p), f = frac(p);
f = f*f*(3.0-2.0*f);
return lerp(lerp(lerp(hash31(b), hash31(b+float3(1,0,0)), f.x),
lerp(hash31(b+float3(0,1,0)), hash31(b+float3(1,1,0)), f.x), f.y),
lerp(lerp(hash31(b+float3(0,0,1)), hash31(b+float3(1,0,1)), f.x),
lerp(hash31(b+float3(0,1,1)), hash31(b+1.0), f.x), f.y), f.z);
}
float2 rotate2(float2 p, float a)
{
float s, c; sincos(a,s,c);
return float2(c*p.x-s*p.y, s*p.x+c*p.y);
}
float3 localPoint(float3 p)
{
p.xy = rotate2(p.xy, -.32-clamp(gTune.w,-.8,.8));
return p;
}
// Analytic interval also handles a camera inside a sphere.
float2 sphere(float3 ro, float3 rd, float radius)
{
float b = dot(ro,rd), h = b*b-dot(ro,ro)+radius*radius;
if (h < 0.0) return float2(FAR_T,-FAR_T);
h = sqrt(h);
return float2(-b-h,-b+h);
}
float firstHit(float2 hit)
{
return hit.x > .001 ? hit.x : (hit.y > .001 ? hit.y : FAR_T);
}
// World-fixed far stars on cube faces; filtered footprints, no screen noise.
float3 sky(float3 d, float footprint)
{
float3 a = abs(d);
float2 uv; float face;
if (a.x >= a.y && a.x >= a.z) { uv=d.yz/a.x; face=d.x>0?1.0:2.0; }
else if (a.y >= a.z) { uv=d.xz/a.y; face=d.y>0?3.0:4.0; }
else { uv=d.xy/a.z; face=d.z>0?5.0:6.0; }
float2 st = uv*125.0, cell=floor(st), f=frac(st);
float h=hash31(float3(cell,face));
float2 center=.25+.5*float2(hash31(float3(cell,face+12.0)),hash31(float3(cell,face+31.0)));
float w=max(.035,footprint*125.0);
float star=exp(-dot(f-center,f-center)/(w*w)) * min(1.0,.008/(w*w));
star *= smoothstep(.986,.999,h);
float dust=pow(saturate(1.0-abs(d.y+.22*d.x-.13)*3.0),6.0);
float n=noise3(d*7.0);
return float3(.004,.007,.016) + dust*n*float3(.021,.012,.034)
+ lerp(float3(.42,.68,1.0),float3(1.0,.7,.4),h)*star*1.8;
}
float annulus(float r, float lo, float hi, float aa)
{
return smoothstep(lo-aa,lo+aa,r)*(1.0-smoothstep(hi-aa,hi+aa,r));
}
// Fade frequencies beyond the ray footprint before evaluating narrow grooves.
float wave(float phase, float frequency, float width)
{
return .5+.5*sin(phase)*saturate(1.0-frequency*width*.32);
}
float ringDensity(float r, float width)
{
float bands=.38+.28*wave(r*39.0,39.0,width)+.30*wave(r*113.0,113.0,width);
float gap=1.0-.94*exp(-pow((r-4.23)/max(.055,width),2.0));
return bands*gap*annulus(r,3.22,5.55,max(.012,width));
}
float3 planet(float3 p, float3 rd, float time, float px)
{
float3 n=p/2.6, q=n;
q.xz=rotate2(q.xz,time*.095);
float turbulence=noise3(q*8.0)+.38*noise3(q*23.0);
float lat=q.y*33.0+(turbulence-.65)*3.0;
float bands=.5+.5*sin(lat);
float fine=wave(lat*3.6+q.x*5.0,120.0,px);
float3 alb=lerp(float3(.12,.22,.31),float3(.83,.49,.22),bands);
alb=lerp(alb,float3(.76,.72,.56),.32*fine);
// A local oval storm travels with the rotating atmosphere.
float2 storm=float2(q.x+.37,(q.y+.19)*2.8);
float vortex=exp(-dot(storm,storm)*95.0)*smoothstep(.15,.6,-q.z);
alb=lerp(alb,float3(.70,.16,.095),vortex*.85);
float light=saturate(dot(n,SUN));
float shadow=1.0;
float ts=-p.y/SUN.y;
if (ts>0.0) shadow=1.0-.83*ringDensity(length((p+SUN*ts).xz),.02);
float rim=pow(1.0-saturate(dot(n,-rd)),3.5);
float3 col=alb*(.10+.94*light*shadow);
col+=CYAN*rim*(.12+.48*light)*(.97+.03*saturate(gSync.y));
return col;
}
// Three differently oriented sheets; true plane intersections, no screen halos.
float3 sheetNormal(int id)
{
if (id==0) return float3(0,1,0);
if (id==1) return normalize(float3(.13,.24,1.0));
return normalize(float3(-.64,1.0,.31));
}
float4 sheet(float3 p, float3 rd, int id, int mode, float time, float px)
{
float3 normal=sheetNormal(id);
float3 u=normalize(cross(normal,float3(1,0,0)));
float3 v=cross(normal,u);
float2 q=float2(dot(p,u),dot(p,v));
float r=length(q), angle=atan2(q.y,q.x);
float width=max(.008,px/max(.12,abs(dot(rd,normal))));
float4 result=float4(0,0,0,0);
if (mode==0) {
float density=ringDensity(r,width);
float3 c=lerp(float3(.22,.40,.48),float3(.85,.60,.31),wave(r*9.0,9.0,width));
float shadow=firstHit(sphere(p+SUN*.01,SUN,2.6))<FAR_T ? .14:1.0;
c*=shadow*(.52+.28*abs(dot(rd,normal)));
c+=CYAN*.12*pow(wave(r*29.0,29.0,width),6.0);
float alpha=1.0-exp(-density*.95/max(.18,abs(dot(rd,normal))));
result=float4(c,alpha);
} else {
float lo=id==0?1.80:(id==1?1.58:3.7);
float hi=id==0?5.05:(id==1?2.04:5.65);
float mask=annulus(r,lo,hi,width);
float spiral=angle*3.0-r*7.0+time*(1.7+float(id)*.37);
float thread=pow(wave(r*75.0+sin(spiral)*1.2,80.0,width),9.0);
float flow=.58+.42*sin(spiral);
float temperature=saturate((r-lo)/(hi-lo));
float3 c=lerp(AMBER,CYAN,temperature);
if (id==1) c=lerp(AMBER,float3(1.0,.83,.48),.55);
if (id==2) c=lerp(PINK,CYAN,.25+.25*sin(angle*2.0+time*.3));
float gain=(.65+1.6*thread+.36*flow)*(1.0+.06*saturate(gVoice.y));
float alpha=mask*(id==1?.90:(id==2?.48:.77));
result=float4(c*gain,alpha);
}
return result;
}
// Finite helical strands, tapered ends, independently traveling waves.
// The .38 march factor bounds the slope of this warped tube field.
float2 filaments(float3 p, float time)
{
float y=clamp(p.y,-3.8,3.8), taper=sqrt(max(.03,1.0-y*y/17.0));
float best=FAR_T, material=0.0;
[unroll] for (int k=0;k<5;k++) {
float fk=float(k), phase=fk*(2.0*PI/5.0);
float a=phase+y*.67+time*.24+.20*sin(y*1.3-time*.65+phase);
float radius=(1.22+.28*sin(y*1.15+phase+time*.31))*taper;
float2 center=radius*float2(cos(a),sin(a));
center+=float2(.30*sin(y*.78+time*.28),.18*cos(y*.85-time*.32));
float tube=.072+.035*taper;
float d=length(float3(p.x-center.x,p.y-y,p.z-center.y))-tube;
if (d<best) { best=d; material=fk; }
}
// A thin central spline, not a spherical core: asymmetric sculpture.
float2 spine=float2(.30*sin(y*.78+time*.28),.18*cos(y*.85-time*.32));
float d=length(float3(p.x-spine.x,p.y-y,p.z-spine.y))-.047;
if (d<best) { best=d; material=5.0; }
return float2(best,material);
}
float3 filamentColor(float3 p, float id, float time)
{
float hue=.5+.5*sin(id*1.8+p.y*.72-time*.52);
float3 c=lerp(CYAN,PINK,smoothstep(.28,.9,hue));
c=lerp(c,AMBER,pow(.5+.5*sin(p.y*1.1+id*2.3+time*.43),8.0)*.85);
float pulse=pow(.5+.5*sin(p.y*6.0-time*3.2+id*1.7),12.0);
return c*(.58+1.05*pulse)*(1.0+.06*saturate(gSync.x));
}
PSOut main(VSOut input)
{
PSOut o;
float3 fw=normalize(gDir.xyz);
float3 worldUp=abs(fw.y)>.98?float3(0,0,1):float3(0,1,0);
float3 right=normalize(cross(worldUp,fw)), up=cross(fw,right);
float2 uv=(input.uv*2.0-1.0)*float2(gTime.w,-1.0);
uv=rotate2(uv,gDir.w);
float3 worldRay=normalize(fw+(right*uv.x+up*uv.y)*gCam.w);
float footprint=max(length(ddx(worldRay)),length(ddy(worldRay)));
float3 ro=localPoint(gCam.xyz), rd=localPoint(worldRay);
int mode=(int)clamp(floor(gTune.x),0.0,2.0);
float time=gTime.x*(.55+.45*clamp(gTune.y,0.0,2.0));
float exposure=.65+.35*clamp(gTune.z,0.0,2.0);
float3 col=sky(worldRay,footprint);
float nearest=FAR_T;
[branch] if (mode<2) {
float radius=mode==0?2.6:1.48;
float t=firstHit(sphere(ro,rd,radius));
if (t<FAR_T) {
nearest=t;
float3 p=ro+rd*t;
col=mode==0?planet(p,rd,time,footprint*t):float3(.001,.002,.004);
}
// Ellipsoidal fragments on real orbital trajectories; analytic occlusion.
[loop] for (int j=0;j<22;j++) {
if (mode==0 && j>=5) break;
float h=hash31(float3(float(j),7.0,2.0));
float orbit=mode==0?5.55:(3.0+2.85*h);
float a=float(j)*2.39996+time*(.085+.06*h);
float3 center=float3(cos(a)*orbit,(mode==0?.11:1.15)*sin(a*2.0+float(j)),sin(a)*orbit);
float size=(mode==0?.035:.065)+h*h*(mode==0?.075:.15);
float3 axes=float3(size,size*(.55+.45*h),size*.76);
float3 er=(ro-center)/axes, ed=rd/axes;
float len=length(ed);
float hit=firstHit(sphere(er,ed/len,1.0));
t=hit<FAR_T?hit/len:FAR_T;
if (t<nearest) {
nearest=t;
float3 p=ro+rd*t;
float3 n=normalize((p-center)/(axes*axes));
float light=saturate(dot(n,SUN));
col=lerp(float3(.08,.13,.18),float3(.43,.33,.25),h)*(.3+light);
if (mode==1) {
float inner=saturate(dot(n,-normalize(center)));
col+=AMBER*inner*.42+CYAN*pow(1.0-saturate(dot(n,-rd)),3.0)*.18;
}
}
}
float opaque=nearest;
float distances[3]; int ids[3];
[unroll] for (int k=0;k<3;k++) {
float3 normal=sheetNormal(k);
float denom=dot(rd,normal);
float hit=abs(denom)>1e-5?-dot(ro,normal)/denom:FAR_T;
distances[k]=(hit>.001 && hit<opaque && (mode==1 || k==0))?hit:FAR_T;
ids[k]=k;
}
// Fixed three-element sorting network, far to near (invalid first).
[unroll] for (int a=0;a<2;a++) {
[unroll] for (int b=0;b<2;b++) {
if (distances[b]<distances[b+1]) {
float swapT=distances[b]; distances[b]=distances[b+1]; distances[b+1]=swapT;
int swapID=ids[b]; ids[b]=ids[b+1]; ids[b+1]=swapID;
}
}
}
[unroll] for (int layer=0;layer<3;layer++) {
t=distances[layer];
if (t<FAR_T) {
float4 ring=sheet(ro+rd*t,rd,ids[layer],mode,time,footprint*t);
col=lerp(col,ring.rgb,ring.a);
if (ring.a>.02) nearest=min(nearest,t);
}
}
// Analytic atmosphere shell: only its segment in FRONT of opaque matter.
if (mode==0) {
float2 atmo=sphere(ro,rd,2.66);
float start=max(.001,atmo.x), end=min(opaque,atmo.y);
if (end>start) {
float mid=(start+end)*.5;
float3 p=ro+rd*mid;
float light=.12+.88*saturate(dot(normalize(p),SUN));
// A foreground ring attenuates the atmosphere as well.
float visibility=1.0;
float planeT=abs(rd.y)>1e-5?-ro.y/rd.y:FAR_T;
if (planeT>0.0 && planeT<start) visibility=1.0-sheet(ro+rd*planeT,rd,0,0,time,footprint*planeT).a;
col+=CYAN*(1.0-exp(-(end-start)*2.5))*light*.23*visibility;
nearest=min(nearest,start);
}
}
} else {
float2 bound=sphere(ro,rd,5.3);
float t=max(.001,bound.x), end=bound.y;
float3 glow=0.0;
[loop] for (int step=0;step<112;step++) {
if (t>end) break;
float3 p=ro+rd*t;
float2 field=filaments(p,time);
float eps=max(.0015,footprint*t*.42);
if (field.x<eps) {
float e=max(.002,eps*.6);
float3 n=normalize(float3(
filaments(p+float3(e,0,0),time).x-filaments(p-float3(e,0,0),time).x,
filaments(p+float3(0,e,0),time).x-filaments(p-float3(0,e,0),time).x,
filaments(p+float3(0,0,e),time).x-filaments(p-float3(0,0,e),time).x));
float facing=saturate(dot(n,-rd));
float3 c=filamentColor(p,field.y,time);
col=c*(.55+.45*facing)+float3(.35,.52,.58)*pow(facing,18.0)*.45;
nearest=t;
break;
}
float stride=max(eps*.4,field.x*.38);
// Compact in-world corona, integrated only up to the first surface.
glow+=filamentColor(p,field.y,time)*exp(-max(0.0,field.x)*36.0)*min(stride,.12)*1.7;
t+=stride;
}
col+=min(glow,float3(.24,.24,.24));
}
o.color=float4(max(col,0.0)*exposure*gTime.z,1.0);
float viewZ=nearest*max(dot(worldRay,fw),1e-4);
o.depth=nearest<FAR_T?saturate(.05/max(viewZ,.05)):0.0;
return o;
}

1005
fx/plinths.hlsl Normal file

File diff suppressed because it is too large Load diff

229
fx/post.hlsl Normal file
View file

@ -0,0 +1,229 @@
// The CRT pass. Takes the low resolution scene target and puts it on a tube.
//
// The one thing that matters here and is easy to get wrong: this pass works
// in TWO coordinate spaces at once.
//
// virtual space - the low resolution grid the scene was drawn on
// (gRes.xy, a fixed 360 lines). Scanlines and the ordered
// dither live here, so a scanline is always one virtual
// row and the dither is always one virtual pixel. That is
// what keeps the look identical from 1366x768 to
// 5120x1440 instead of turning into fine grey noise on a
// big display.
//
// output space - real backbuffer pixels (SV_Position). The shadow mask
// and the rim of the glass live here, because an aperture
// grille is a property of the tube, not of the signal.
//
// Mixing the two up is why most CRT shaders look wrong at some resolution.
cbuffer Post : register(b0)
{
float4 gRes; // xy virtual size, zw output size
float4 gCrt; // x scanline depth, y mask depth, z aberration, w vignette
float4 gGrade; // x dither, y exposure, z dissolve mix, w fade to black
float4 gFx; // x flash, y whip smear, z bloom level, w letterbox
float4 gRamp[4];// the quantiser's four stops. this is the palette.
float4 gTone; // x hue kept, y quantiser steps, zw unused
};
Texture2D gScene : register(t0);
Texture2D gPrev : register(t1); // the outgoing shot, during a dissolve
Texture2D gBloom : register(t2); // half res, already blurred
SamplerState gPoint : register(s0);
SamplerState gLinear: register(s1);
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// 4x4 ordered Bayer, the Marathon look. Values 0..15.
static const float kBayer[16] = {
0.0, 8.0, 2.0, 10.0,
12.0, 4.0, 14.0, 6.0,
3.0, 11.0, 1.0, 9.0,
15.0, 7.0, 13.0, 5.0
};
// A narrow cold ramp. Quantising into this rather than into plain grey is
// what makes the dither read as an old shaded renderer instead of noise.
float3 rampColour(float v)
{
// The four stops come from the section's grade rather than from literals.
// Changing them changes what the picture is MADE OF - every pixel passes
// through here - which is a categorically stronger thing than tinting
// the output. Interpolated in C across a dissolve, so two sections in
// different palettes cross-fade as grades and not as a colour switch.
float3 a = gRamp[0].rgb;
float3 b = gRamp[1].rgb;
float3 c = gRamp[2].rgb;
float3 d = gRamp[3].rgb;
float3 lo = lerp(a, b, saturate(v * 3.0));
float3 md = lerp(b, c, saturate(v * 3.0 - 1.0));
float3 hi = lerp(c, d, saturate(v * 3.0 - 2.0));
return v < 0.3333 ? lo : (v < 0.6666 ? md : hi);
}
float4 main(VSOut i) : SV_Target
{
float2 uv = i.uv;
// Gentle barrel distortion. Enough to feel like glass, not enough to
// make anyone think about it.
float2 cc = uv * 2.0 - 1.0;
float r2 = dot(cc, cc);
uv = (cc * (1.0 + 0.028 * r2)) * 0.5 + 0.5;
// THE RIM OF THE TUBE, feathered over one OUTPUT pixel instead of being a
// hard in/out test. The barrel maps a straight screen edge to a shallow
// curve, and a binary test on a shallow curve is a staircase with steps
// tens of pixels long - which then crawls, one step at a time, whenever
// anything behind it moves. Measured in output pixels rather than virtual
// ones so the feather stays one pixel wide at every resolution instead of
// becoming a three pixel smear at 1080.
float2 inPx = min(uv, 1.0 - uv) * gRes.zw;
float rim = saturate(min(inPx.x, inPx.y) + 0.5);
if (rim <= 0.0)
return float4(0.0, 0.0, 0.0, 1.0);
// Chromatic aberration, growing towards the edge of the tube.
float2 ab = cc * gCrt.z * (0.4 + 0.6 * r2) / gRes.xy;
float3 col;
col.r = gScene.Sample(gPoint, uv + ab).r;
col.g = gScene.Sample(gPoint, uv).g;
col.b = gScene.Sample(gPoint, uv - ab).b;
// A whip-in is a lateral smear that settles. It is what lets a fast pan
// hand off into the next shot instead of just stopping dead.
if (gFx.y > 0.002) {
float3 sm = float3(0.0, 0.0, 0.0);
[unroll] for (int k = 1; k <= 6; k++) {
float2 o = float2(gFx.y * 0.085 * float(k), 0.0);
sm += gScene.Sample(gLinear, saturate(uv - o)).rgb;
}
col = lerp(col, sm / 6.0, saturate(gFx.y));
}
// A dissolve wants the two shots mixed BEFORE the tube, so the dither
// and the scanlines belong to the composite rather than to each half.
if (gGrade.z > 0.002)
col = lerp(col, gPrev.Sample(gPoint, uv).rgb, saturate(gGrade.z));
// BLOOM, added before the quantiser rather than after it. That order is
// the whole reason it works here: added afterwards it would sit on top of
// the dither as a smooth gradient and the two would visibly disagree
// about what resolution the picture is. Added first, the glow is
// dithered along with everything else and belongs to the same image.
col += gBloom.Sample(gLinear, uv).rgb * gFx.z;
col *= gGrade.y; // exposure
// --- virtual space: dither -------------------------------------------
// Quantise the luminance through the ordered matrix, then re-colour
// through the ramp and keep the original hue on top of it.
//
// THE WIDTH OF THE DITHER IS THE ENTIRE ARGUMENT IN THIS BLOCK, and it
// is measured, not tasted. An ordered dither spends NEIGHBOURING pixels
// to buy a value that lies between two quantiser levels, so it has to
// span the gap between two adjacent levels - one step - and the moment
// it spans more than that it stops carrying information and starts
// adding noise to a picture that is already quantised.
//
// As shipped, the Bayer threshold spans +-0.469 and was multiplied by
// gGrade.x = 0.85 against steps of 1/10. That is EIGHT levels wide.
// Two consequences, both of them visible in every single shot:
//
// - at the ends of the range the noise is rectified, because saturate()
// throws away the half of the swing that would have gone below black
// and keeps the half that goes above it. A scene value of exact black
// came off the tube as a 16 cell speckle reaching level 4 of 10;
// empty sky measured 4% mean with 20% peaks in a picture whose black
// stop is 3%. White was crushed the same way from the other side.
//
// - in the midtones a flat 50% grey became a mosaic running from near
// black to near white. Local contrast from the dither was five times
// the local contrast of anything the scene had drawn, so every shot
// converged on the same grey field and any two of them measured
// alike no matter what was in front of the camera.
//
// So the width is expressed in QUANTISER STEPS now, and bounded:
//
// one step at either end of the range. That is the mean preserving
// minimum, and it is the widest dither that provably cannot lift black
// or dirty white: the largest Bayer offset is 0.469 of a step, which
// never rounds up to the next level on its own. Black stays exactly on
// stop 0, white stays exactly on stop 3, and the dark gradients still
// dither rather than band.
//
// about two and a bit steps through the midtones, where a wider dither
// IS the texture the look is made of - scaled by the grade's own
// dither knob, so bleach (7 steps, dither 1.00) still speckles far
// harder than warm (11 steps, 0.82), which is what those numbers were
// chosen for.
//
// The taper between the two is the shape term, and it is smooth, so a
// gradient running down into black narrows its own dither on the way.
float2 vp = floor(uv * gRes.xy);
int bi = int(fmod(vp.y, 4.0)) * 4 + int(fmod(vp.x, 4.0));
float thr = (kBayer[bi] + 0.5) / 16.0 - 0.5; // +-0.469, evenly spaced
float lum = dot(col, float3(0.299, 0.587, 0.114));
float steps = max(gTone.y, 1.0);
float shape = smoothstep(0.0, 0.15, lum) * smoothstep(0.0, 0.12, 1.0 - lum);
float width = (1.0 + 1.30 * gGrade.x * shape) / steps;
float q = floor(saturate(lum + thr * width) * steps + 0.5) / steps;
float3 dithered = rampColour(q);
// The hue divide gets a floor of one 8-bit code rather than 1e-4. The
// scene target is 16 bit float, so it is full of values below that, and
// a 1/lum with a 1e-4 floor makes the difference between a pixel at zero
// and a pixel at one ten-thousandth a factor of 2.6 in the output. That
// was hidden under the old speckle. With black actually black it would
// read as an edge between two shades of nothing.
float3 hue = col / max(lum, 1.0 / 255.0);
col = lerp(dithered, dithered * hue, gTone.x);
// --- virtual space: scanlines ----------------------------------------
float sl = sin(uv.y * gRes.y * 3.14159265);
col *= 1.0 - gCrt.x * sl * sl;
// --- output space: aperture grille -----------------------------------
// Three-phosphor stripe on real pixels. On a small window this is almost
// invisible, which is correct: so is a real shadow mask.
float phase = fmod(i.pos.x, 3.0);
float3 mask = float3(phase < 1.0 ? 1.0 : 0.72,
(phase >= 1.0 && phase < 2.0) ? 1.0 : 0.72,
phase >= 2.0 ? 1.0 : 0.72);
col *= lerp(float3(1.0, 1.0, 1.0), mask, gCrt.y);
// Vignette, then the shot fade, then the flash. The flash is added last
// and deliberately after the dither: a cut should blow the quantiser
// out, not be quantised along with everything else. The vignette is
// clamped because 0.26 * r2 * r2 passes 1.0 in the extreme corners and a
// negative multiplier there would subtract from the flash instead of
// being masked by it.
col *= saturate(1.0 - gCrt.w * r2 * r2);
col *= gGrade.w;
col += gFx.x * float3(1.00, 0.97, 0.92);
// THE MATTE, last, and in the distorted uv rather than in output space:
// the bars are part of the signal, so they bow with the glass like
// everything else on the tube. A straight bar over a curved picture is
// the tell that the letterbox was pasted on afterwards.
//
// Softened over one virtual line, because the edge is a curve crossing a
// pixel grid and a hard threshold on it crawls.
if (gFx.w > 0.0005)
col *= smoothstep(0.0, 1.0 / gRes.y,
(0.5 - gFx.w) - abs(uv.y - 0.5));
// The rim goes on after the flash, so a cut blows out the picture and
// not the frame around it.
col *= rim;
return float4(col, 1.0);
}

598
fx/poweroff.hlsl Normal file
View file

@ -0,0 +1,598 @@
// Shot 39 - CRT POWER-OFF. The last shot of the demo.
//
// Nothing here is marched. This is a two dimensional shader, like the cat eye
// that opens the demo, and for the same reason: the subject is the picture
// itself, so there is no space to fly through. The camera fields are read and
// ignored on purpose - a tube dying is a locked-off frame, and a drifting
// camera would fight it.
//
// The collapse is not a squash, and getting the order right is the whole shot:
//
// 0. Before anything geometric happens the tube is ALREADY failing, and it
// has to be, or the collapse arrives out of nowhere. The vertical hold
// lets go first: the frame walks up the glass and wraps, dragging the
// blanking bar and its retrace streak across the picture. The vertical
// linearity goes with it, so the top of the frame compresses before the
// rest of it does. The three guns stop landing on the same spot, which
// is the red-left/blue-right fringe. That is the anticipation, and it is
// the difference between inevitable and abrupt.
//
// 1. The high voltage sags. The beam is accelerated less, the yoke
// therefore deflects it further, and the picture SWELLS a little, goes
// soft, and brightens before anything else happens. That swell is the
// detail that says "a tube switched off" rather than "a wipe".
//
// 2. The vertical deflection dies, and it dies far faster than the
// horizontal. The picture crushes to a full-width line while the width
// is still untouched. Every scanline in the frame is now landing on top
// of every other one, so the line carries the whole frame's beam energy
// in a single row - it is blown out, and it is brightest at the two
// ends, where the sweep turns around and the beam dwells. Behind it the
// whole picture is still faintly there in the phosphor, unlit.
//
// 3. Only then does the horizontal go, and the line closes to a point.
//
// 4. The point is not the end. Phosphor keeps glowing after the beam that
// lit it has stopped, green longest of the three, which is why the last
// thing left on a dead tube is a small green-white star that takes a
// second to go out - and a horizontal smear either side of it, where the
// line was a moment ago and the phosphor has not caught up.
//
// What is on screen when it dies is the cat eye, one last time, already sick
// with tearing and a rolling hum bar. The demo opened on that eye; ending on
// it and then killing the tube under it is the only cut this shot needs.
//
// gTune.x collapse progress on the FIRST frame of the shot, 0..1
// gTune.y how fast that progress advances, per second
// gTune.z signal decay the picture ALREADY had before the switch
// gTune.w phosphor persistence of the dot afterwards
//
// gTune.x is the driver the edit steers by, and it runs 0 to 1 - but tune is
// constant for the length of a shot, so the shader needs both the value it
// starts at and the rate it moves. x is where the collapse begins and y is
// how long it takes (rate = 1 / seconds).
//
// SELF-TIMED MODE. y = 0 used to mean "freeze at exactly x", and the shot
// this scene is actually cut into passes {1, 0, 0, 0} - which froze it at
// x = 1, i.e. parked the whole final 1.8 seconds of the demo on one static
// frame of an already-dead tube at full flare. Every envelope in here is a
// function of k, k was constant, and so the last thing the audience saw was
// a still. A held pose is worth having; a held pose is not worth having as
// the default that an unfilled tune falls into. So y = 0 now means "time
// yourself", and x becomes a tempo scale on the shader's own schedule:
//
// rate = 1.14 * x (x = 0 reads as 1, so {0,0,0,0} works too)
// k = (t - 0.62) * rate
//
// which holds the failing picture for the first six tenths, closes the line
// at t = 1.32 and leaves half a second of star. Those numbers are cut against
// what actually reaches the screen: the shot's TR_BLACK fades it up over 14
// rows, so brightness is under 15% for the first six tenths of a second and
// there is no point spending the collapse down there. In self-timed mode w =
// 0 likewise reads as "the usual persistence" rather than "none". Any shot
// that passes a real rate gets the documented behaviour, unchanged, including
// the freeze.
//
// Landmarks on that 0..1 clock, so a cut can be placed on one:
//
// < 0.00 the pre-roll: rolling frame, tearing, misconvergence
// 0.00 - 0.15 the swell, and the last stretch that is still a picture
// 0.18 - 0.48 the vertical dies (eased, so it is over near 0.36)
// 0.36 - 0.54 the held line, full width. this is the shot
// 0.54 - 0.80 the width closes
// 0.80 the flare, and the point
// 0.80 + the phosphor, on a clock in SECONDS, not in k
//
// The afterglow is deliberately NOT on the k clock. Held there it could never
// outlive k reaching 1, so "a second of glow" was only reachable by making the
// whole collapse four seconds long. It runs on real time now, so the collapse
// is as fast as the edit wants and the star still takes its second.
//
// The yoke ring is a sine in k, and at the rates this shot uses it advances
// most of a radian per frame - so it rings in POSITION, not in height. Height
// feeds the beam-energy gain, which is brightness, and a brightness wobble at
// that rate is a photosensitivity event. A displacement of the same size is
// a shudder, which is what a coil losing its drive actually does.
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look, w roll
float4 gTune;
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// One virtual row, in the [-1,1] units this shader works in. 360 lines, so a
// row is 2/360. Every softness in here is floored at roughly this, because a
// transition narrower than a pixel is not a soft edge, it is a stair that
// crawls - and the post pass dithers on top of it, which makes it worse.
#define ROW 0.00556
float hash12(float2 p)
{
float3 q = frac(float3(p.xyx) * 0.1031);
q += dot(q, q.yzx + 33.33);
return frac((q.x + q.y) * q.z);
}
// Everything the tube is doing wrong, gathered into one value. All six fields
// are uniform across the draw - they are functions of the collapse clock and
// nothing else - so this is passed by value into a function called up to
// seven times per pixel and the compiler keeps the whole thing in registers.
struct Fault
{
float sick; // how broken the signal is: tearing, hum, speckle
float hf; // how much authority per-row detail still has
float roll; // vertical hold slip, in picture units
float nlin; // vertical linearity error - the top compresses first
float bar; // blanking bar and retrace streak, at the wrap seam
float lift; // the one voice left in the outro, as a floor-safe lift
};
// The picture the tube is showing, in raster coordinates: x in [-aspect,
// aspect], y in [-1,1], regardless of what the deflection is currently doing
// to it. Everything the collapse does is a coordinate change on top of this.
//
// `hf` is how much authority the per-row detail still has. Once the vertical
// has crushed the picture, one output row is an average of dozens of picture
// rows, and five taps cannot average dozens of independent random rows - it
// samples five of them, which is not a filter, it is noise. Physically the
// tear and the speckle DO average away as the frame folds, so the honest fix
// and the cheap fix are the same one: fade them out with the fold.
float3 signalAt(float2 c, Fault f)
{
// ---- the vertical hold, which is the first thing to go ----------------
// The frame walks up the glass and wraps. This is a coordinate change on
// the PICTURE, not on the raster: the raster is still where it was, which
// is why the caller's extent test is done before this and not after.
float wr = frac((c.y - f.roll + 1.0) * 0.5); // 0..1 across the frame
float sd = min(wr, 1.0 - wr); // 0 at the wrap seam
float yy = wr * 2.0 - 1.0;
// Vertical linearity goes before vertical amplitude does: the sawtooth
// starts from the most depleted part of the supply, so the top of the
// picture squashes while the bottom is still the right size. Small, but
// it means the eventual crush is the end of something already happening
// rather than an event on its own.
yy += f.nlin * yy * saturate(yy);
float row = floor((yy + 1.0) * 180.0);
float tick = floor(gTime.x * 26.0);
// Line tearing, in BLOCKS of rows. This was per-row, and per-row tearing
// does not read as tearing: on the highest contrast edge in the frame -
// the pupil slit - it reads as a chewed edge, because neighbouring rows
// land on opposite sides of it. Real tearing displaces a contiguous run
// of lines, and it is the intact runs in between that make the broken
// ones read as broken.
float band = floor(row * 0.125); // 8-row blocks
float pick = hash12(float2(band * 0.37, tick + 7.0));
float jit = hash12(float2(band, tick)) - 0.5;
c.x += jit * 0.17 * f.sick * f.hf * step(0.72, pick);
// Near-black, slightly blue, a touch heavier at the top and bottom of the
// frame so the raster has a shape even before anything is drawn in it.
float3 col = float3(0.016, 0.019, 0.030) * (1.0 - 0.35 * abs(yy));
// The eye. One bold disc, a hard slit, one small specular - three shapes,
// which is all that survives a 4x4 dither at 360 lines. It is framed to
// sit on top of the demo's opening shot: eye.hlsl fills out to r = 0.84,
// so this does too. It was 0.70 and a quarter smaller, which is enough to
// break the rhyme with the shot the demo opened on - and a small disc in
// a black field is not a composition.
float2 e = float2(c.x, yy) - float2(0.0, 0.03);
float r = length(e * float2(1.0, 1.04));
float3 grn = lerp(float3(0.34, 0.95, 0.32), float3(0.05, 0.26, 0.09),
smoothstep(0.12, 0.92, r));
// The limbal ring. Without it the iris is one flat value across its whole
// area and the disc reads as a light bulb rather than as an eye - and a
// flat disc is also the first thing a ten step dither turns into a
// poster. One smoothstep buys the shape back.
grn *= 1.0 - 0.80 * smoothstep(0.60, 0.86, r);
float iris = smoothstep(0.95, 0.84, r);
float2 q = float2(e.x / 0.112, e.y / 0.62);
float pup = smoothstep(1.06, 0.90, length(q));
col += grn * iris * (1.0 - 0.94 * pup);
// The ambient glow is masked by the pupil as well. Added flat over the
// top it lifted the slit to a third of full green and the eye stopped
// having a dark centre, which is the one value the composition needs.
col += float3(0.09, 0.30, 0.11) * exp(-r * 1.55) * (1.0 - 0.45 * pup);
// The pupil is not a hole. It is glass with something behind it.
col += pup * float3(0.020, 0.030, 0.034);
// The wet specular, in the same place the opening shot puts it. This is
// the brightest thing in the picture and it has to stay that way, or the
// eye is a flat disc.
col += float3(0.60, 0.68, 0.63) *
smoothstep(0.150, 0.040, length(e - float2(-0.220, 0.340)));
// The hum bar: a soft bright band crawling UP the frame, which is what a
// failing supply looks like before it stops being a supply at all. It
// crawls FASTER as the supply gives up, because the ripple is drifting
// away from the field rate - a hum bar that keeps a constant speed is a
// hum bar on a tube that is fine.
float hum = frac(yy * 0.5 + 0.5 + gTime.x * (0.30 + 0.55 * f.sick));
hum = exp(-(hum - 0.5) * (hum - 0.5) * 26.0);
col += float3(0.050, 0.056, 0.070) * hum * f.sick * (1.0 + 0.45 * f.lift);
// Speckle, quantised to pairs of rows so it reads as signal and not as
// film grain, and so it is coarse enough to survive the box filter
// instead of turning into a crawl.
float sp = hash12(float2(floor(row * 0.5) * 1.7, tick * 3.1 + 19.0));
col += (sp - 0.45) * 0.10 * f.sick * f.hf;
// The blanking interval, dragged into shot by the roll. This is the one
// piece of the pre-roll that is unambiguous at a glance: a dark band with
// a thin bright retrace streak down the middle of it, crossing the frame.
// Nothing else in the demo looks remotely like it, which is the point -
// the audience has to be told the tube is going before it goes.
float blank = exp(-sd * sd * 900.0) * f.bar;
col *= 1.0 - 0.88 * blank;
col += float3(0.10, 0.15, 0.11) * exp(-sd * sd * 30000.0) * f.bar * 0.60;
return max(col, 0.0);
}
float4 main(VSOut i) : SV_Target
{
float2 p = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y flipped, same reason as every other scene: uv.y = 0 is the
// top of the screen, and a tube collapses towards its centre
// line, not away from it.
p.x *= gTime.w;
float A = gTime.w;
// ---- the clock --------------------------------------------------------
// Written as ku0 + t * rate in BOTH branches, so anything that needs to
// know "at what time does the clock read v" can invert it: t = (v - ku0)
// / rate. The roll uses that to stop itself.
float rate, ku0, persist;
if (gTune.y > 1e-4) {
rate = gTune.y; // the edit gave a rate
ku0 = gTune.x;
persist = saturate(gTune.w);
} else {
rate = 1.14 * ((gTune.x > 0.01) ? gTune.x : 1.0);
ku0 = -0.62 * rate; // six tenths of failing first
persist = (gTune.w > 0.001) ? saturate(gTune.w) : 0.60;
}
// ku is the collapse clock and it is NOT clamped at either end. The
// pre-roll needs it negative, so the failure has somewhere to live before
// the geometry moves; the phosphor after the closure needs it to keep
// running past 1, or the afterglow plateaus at whatever value it had
// reached when k hit its ceiling and the tube never actually goes out.
float ku = ku0 + gTime.x * rate;
float k = saturate(ku);
// How far into the failure we are, before the switch does anything
// geometric. In authored mode ku starts at gTune.x >= 0, so this is 1
// from the first frame and the shot behaves exactly as it always did.
float pre = smoothstep(-0.62, 0.02, ku);
// ---- the three envelopes ---------------------------------------------
// The swell is a bump, not a ramp: the picture grows, and then the thing
// that was making it grow takes the deflection with it.
float swell = smoothstep(0.00, 0.15, k) * smoothstep(0.32, 0.18, k);
// Vertical first, and fast. Cubic ease-out, so almost all of the travel
// happens in the first third of the window and the last sliver of height
// creeps away - which is what makes the line feel like it snapped shut.
float vv = smoothstep(0.18, 0.48, k);
float iv = 1.0 - vv;
float vc = 1.0 - iv * iv * iv;
// Horizontal only starts once vertical is done, and the gap between the
// two is the held line. That hold is the shot. This one is NOT eased out
// the way the vertical is: the width has to still be visibly closing
// right up to the last moment, or the point arrives before the line has
// finished being a line and the collapse loses its ending.
float hc = smoothstep(0.54, 0.80, k);
// ---- what is wrong with the signal ------------------------------------
// gTune.z is how sick the picture ALREADY was when the shot started. The
// death adds its own on top, and it has to: a tube whose vertical hold
// has let go is tearing, whatever the edit asked for. It peaks exactly on
// the switch, which is where the sync loses lock hardest.
float sick = saturate(gTune.z +
pre * (0.55 + 0.45 * smoothstep(0.02, 0.16, k)));
// The slip, in picture heights, and it STOPS. There is no rolling once
// there is no vertical sweep left to lose lock on, and a phosphor ghost
// that keeps sliding is a ghost of nothing. Freeze at k = 0.30, halfway
// through the crush, by clamping the time the roll integrates over.
float tStop = max((0.30 - ku0) / rate, 0.0);
float roll = 1.90 * pre * pre * min(gTime.x, tStop);
// ---- the deflection ---------------------------------------------------
// 0.0030 is roughly half a virtual row at 360 lines, so the line really
// is one scanline tall rather than a thin rectangle.
float h = lerp(1.0, 0.0030, vc) * (1.0 + 0.10 * swell);
float w = lerp(1.0, 0.0026, hc) * (1.0 + 0.06 * swell);
// The yoke does not stop cleanly, it rings - in POSITION. Peaks in the
// middle of the collapse and is gone by the time the line settles. The
// height keeps a much smaller share of the same ring so the line still
// reads as breathing, held under a tenth so it cannot count as a
// brightness transition however fast it goes.
float ringPh = k * 34.0;
float ringE = vc * (1.0 - vc);
float ring = 0.055 * ringE * sin(ringPh);
h *= 1.0 + 0.07 * ringE * sin(ringPh + 1.6);
// The raster centre slips down as the vertical hold goes, and the line
// keeps a little of the picture's pincushion, so it is not a ruled edge.
float xn = p.x / A;
float yc = 0.030 * vc * (1.0 - 0.5 * vc) + ring;
float bow = 0.010 * vc * xn * xn;
float sy = (p.y - yc - bow) / max(h, 1e-5);
float sx = p.x / max(w, 1e-5);
// ---- the raster -------------------------------------------------------
// One output row now covers 1/h rows of picture, so it has to be a box
// filter over that span or the collapse turns into aliased stripes
// instead of the picture folding into itself. Five taps is enough because
// by the time the span is wide the result is nearly a flat average.
//
// The floor on span is the HV sag defocus: less accelerating voltage is a
// fatter, softer spot, and without an explicit floor that softness never
// appeared, because span is derived from h and h has barely moved yet.
float span = min((2.0 / 360.0) / max(h, 1e-5), 2.4);
span = max(span * (1.0 + 0.8 * swell), 0.030 * swell);
// How much of the frame is folding into one output row, 0..1. Drives the
// suppression of per-row detail inside signalAt.
float fold = saturate((span - 0.010) * 26.0);
Fault F;
F.sick = sick;
F.hf = 1.0 - 0.92 * fold;
F.roll = roll;
F.nlin = 0.42 * pre * (1.0 - vc);
F.bar = pre * (1.0 - vc);
// The outro subtracts a voice a bar until only the organ is left, so the
// organ is the only thing still moving in the music under this shot. It
// lifts, it never scales: base + k*s, so no envelope can take the floor
// out from under the picture.
F.lift = saturate(gVoice.z);
// span is a function of h and swell, both uniform, so the tap count below
// is the same for every pixel in the draw and the branch never diverges:
// for the first half second, while the picture is still a picture and the
// span is under a row, one tap IS the filter and the other four are paid
// for nothing. The count is a variable rather than two copies of the loop
// because two copies is two copies of signalAt in the blob.
int nt = (span < 1.6 * ROW) ? 1 : 5;
float ctr = 0.5 * float(nt - 1);
float stp = 0.25 * span;
float3 sig = float3(0.0, 0.0, 0.0);
[loop] for (int t = 0; t < nt; t++) {
float y = sy + (float(t) - ctr) * stp;
if (abs(y) <= 1.0) sig += signalAt(float2(sx, y), F);
}
sig /= float(nt);
// Misconvergence. As the high voltage sags the three beams stop landing
// on the same triad and the guns separate - red short of where it should
// be, blue past it. It is the single most legible symptom a colour tube
// has, it is the one the swell shares a cause with, and it is worth two
// extra taps: about eight pixels of fringe at 1920 at its widest.
//
// Gated on a UNIFORM value, so the branch is taken by the whole draw or
// by none of it. Two things about that gate are load-bearing:
//
// - It is (1 - 14*vc), not (1 - vc). These two taps sit OUTSIDE the box
// filter, so they are neither extent-tested nor divided by the tap
// count. The moment the fold starts rejecting taps, sig.g is a fifth
// of a partly-rejected sum while a raw tap is not, and replacing r and
// b with raw taps turns the whole screen magenta - the folded picture
// tiling in two channels at full strength behind a dim green one. It
// is a real bug and it cost a contact sheet to find. Zero the fringe
// before the fold can begin: at 14 it is out by k = 0.21, and the
// swell peaks at 0.16, so the widest fringe still lands intact.
//
// - The blend weight, not the sampled value, carries the extent test.
// Multiplying the value instead pulls r and b to black in the two or
// three percent of rows the raster has already lost, which is a green
// seam across the top and bottom of the frame.
float conv = (0.006 * pre + 0.010 * swell) * saturate(1.0 - 14.0 * vc);
[branch] if (conv > 0.0005) {
float m = (abs(sy) <= 1.0) ? 0.90 : 0.0;
float3 lo = signalAt(float2(sx - conv, sy), F);
float3 hi = signalAt(float2(sx + conv, sy), F);
sig.r = lerp(sig.r, lo.r, m);
sig.b = lerp(sig.b, hi.b, m);
}
// Overscan: the picture runs past the glass at full width, so no edge is
// visible until the horizontal actually starts closing. This is measured
// in SCREEN units with a one-pixel floor on the softness. Written as a
// smoothstep on sx it was a fixed 4% of a half-width that ends up at
// 0.0026, i.e. a transition two thousandths of a pixel wide - a hard
// stair on the two ends of the line, exactly where the eye is looking.
// ROW is the softness floor in x as well as in y: the engine fixes the
// height at 360 lines and lets the width follow the aspect, so a virtual
// pixel is square at every aspect from 4:3 to 32:9 and 2/360 is one of
// them in either direction.
float halfW = A * w;
float xsoft = max(0.02 * halfW, ROW);
float xin = 1.0 - smoothstep(halfW - xsoft, halfW + xsoft, abs(p.x));
// Beam energy is conserved, so brightness goes up exactly as fast as the
// area goes down. Both gains are capped - the true 1/(h*w) is about six
// orders of magnitude and there is no point carrying it once the frame
// has clipped to white.
float vGain = min(1.0 / max(h, 0.0030), 42.0);
float hGain = min(1.0 / max(w, 0.0026), 4.5);
// The ends of a collapsed line are brighter than the middle because the
// sweep decelerates into the turnaround and the beam sits there longer.
// The ramp starts further in than it did: at 0.50 the bright part landed
// under the overscan roll-off and never showed.
float ax = abs(p.x) / max(halfW, 1e-5);
float ends = 1.0 + 2.6 * vc * (1.0 - hc) * smoothstep(0.35, 0.96, ax);
// The sweep is not steady either - it hunts, and a node travels along the
// line. Without this the held line is a still frame for a fifth of a
// second at the loudest moment of the shot. ax is clamped to 1 inside the
// visible line by xin, so this is always about one cycle across it,
// whatever the width has got down to.
ends *= 1.0 + 0.22 * vc * (1.0 - hc) *
sin(ax * 7.0 - gTime.x * 9.0);
// The swell is not only bigger, it is brighter: the same beam, less of it
// being thrown away in the shadow mask. And the sag that causes the swell
// starts long before the swell does, so the picture is already lifting
// while it is still a picture - which is also the only reason anything is
// visible under the shot's fade-up for the first six tenths of a second.
float lift = 1.0 + 0.45 * swell + 0.75 * pre * (1.0 - vc);
float3 col = sig * (vGain * hGain * ends * xin * lift);
// Once the line is carrying the whole frame it is past what any one gun
// can put out, so the colour walks to neutral - which is also why the
// classic power-off line is white and not the colour of the picture. Not
// all the way: the line is a column-average of the picture and holding a
// little of that is what stops it being a ruled white bar.
float lum = dot(col, float3(0.299, 0.587, 0.114));
col = lerp(col, float3(lum, lum, lum), 0.62 * vc);
// Bloom off the line. A row this overdriven does not stay inside its row:
// it blooms into its neighbours, white in the core and green at the
// edges, because that is the order the phosphors give up in.
float dl = abs(p.y - yc - bow);
float bloom = exp(-dl * 26.0) * vc * (1.0 - 0.85 * hc);
float bsoft = max(0.06 * halfW, ROW);
float bx = 1.0 - smoothstep(halfW - bsoft, halfW + 2.0 * bsoft,
abs(p.x));
col += lerp(float3(0.30, 0.95, 0.36), float3(1.00, 1.00, 0.95),
exp(-dl * 90.0)) * bloom * 0.60 * bx;
// ---- the dot ----------------------------------------------------------
// Past a certain point the raster is two pixels wide and sampling it is a
// lottery, so the brightest thing in the last second of the demo is drawn
// rather than filtered. Hand over, do not add on top.
//
// The handover happens LATE. Starting it at hc = 0.80 crossfaded a line
// still 45 pixels wide into a round dot, and the flare - the single
// brightest frame of the shot - arrived as a soft green cloud with the
// line dissolved inside it. At 0.93 the line is a dozen pixels across
// when the dot takes over and the cut between the two is invisible.
float dotOn = smoothstep(0.93, 1.00, hc);
col *= 1.0 - dotOn;
// 0.80 is where the width actually reaches zero, so both the flare and
// the decay are measured from the closure rather than from a round
// number - and they are measured in SECONDS, not in k.
//
// In k, the phosphor could never outlive k reaching 1, so "a second of
// afterglow" was only reachable by making the whole collapse four seconds
// long. Dividing by the rate decouples the two: the collapse is as fast
// as the edit wants and the dot still takes its second to go out.
float tAfter = max(ku - 0.80, 0.0);
float tSec = tAfter / rate;
float glowE = exp(-tSec * lerp(7.0, 1.3, persist));
// The instant the line closes, everything that was spread across a whole
// row arrives in one place. That is a flare, and it is over in a few
// frames - without it the line does not so much close as fade out.
float flare = exp(-tSec * 22.0) * smoothstep(0.93, 1.00, hc);
// p is isotropic - x was already scaled by the aspect - so a plain length
// is a circle on screen. The core shrinks as it fades, the way a real dot
// does; it does not simply dim in place.
//
// The flare widens the CORE, not the halo. Widening the halo made the
// single brightest frame of the shot a green ball with a pale pip lost
// inside it; a tube flashing off flashes WHITE, with green only at the
// fringe. The floor is two virtual rows: below that the gaussian is
// narrower than the pixel grid and the last image of the demo scintillates
// on and off as the dot lands between sample points.
float coreR = max(lerp(0.030, 0.0075, hc) * (0.55 + 0.45 * glowE)
+ 0.055 * flare, 2.0 * ROW);
float rd = length(p - float2(0.0, yc));
float cq = rd / coreR;
float core = exp(-cq * cq);
// The halo is phosphor that was lit a moment ago and is still coming
// down, so it is not tied to the core's radius - but it was a fixed 0.075
// wide, which is four times the core for the dot's whole life, and a green
// cloud that size does not read as a star, it reads as an out of focus
// smudge. It is tight now, and it comes down on the SLOW clock so the glow
// does not snap shut the instant the flare ends.
float halo = exp(-rd / (0.050 + 0.045 * flare + 0.030 * glowE));
// Underneath both, one very wide and very faint field, so the glow still
// has somewhere to sit rather than ending at the halo's edge.
float mist = exp(-rd / 0.17);
// Green longest of the three. The core is white while the beam is still
// arriving and walks green as it dies, which is what leaves a green-white
// star rather than a white one that turns off.
float3 coreC = lerp(float3(0.62, 1.00, 0.66), float3(1.00, 1.00, 0.96),
saturate(flare + 0.6 * glowE));
col += (coreC * core * (3.2 + 6.0 * flare) +
float3(0.24, 0.85, 0.32) * halo * (0.80 + 1.60 * flare +
0.35 * F.lift) +
float3(0.16, 0.55, 0.22) * mist * (0.28 + 0.50 * flare))
* dotOn * glowE;
// The line does not vanish when the dot takes over. It was there a
// hundredth of a second ago and the phosphor it lit is still coming down,
// so a horizontal smear survives the closure, narrowing and dimming on
// its own clock - slower than the flare, faster than the star. This is
// the last thing in the demo that MOVES, and it is what turns the point
// into the end of a collapse rather than a dot that was always there.
float trW = A * 0.62 * exp(-tSec * 2.4);
float trD = p.y - yc;
float trail = exp(-trD * trD * 5200.0) *
(1.0 - smoothstep(trW * 0.55, trW, abs(p.x)));
col += float3(0.20, 0.62, 0.24) * trail * dotOn * exp(-tSec * 3.0) * 0.85;
// ---- what is left -----------------------------------------------------
// Phosphor does not stop glowing because deflection did. For a while
// after the raster leaves, the whole picture is still faintly there,
// hanging in the dark behind the line with nothing driving it. The decay
// was fast enough that it was gone before the line had even settled; it
// is halved now, so the held line has the ghost of the eye behind it,
// which is the one moment in the shot where you can see both at once.
float ghost = vc * exp(-max(k - 0.24, 0.0) * 7.0) * 0.30;
[branch] if (ghost > 0.002) {
Fault G = F;
G.sick = sick * 0.3;
G.hf = 1.0;
G.bar = F.bar * 0.4;
col += signalAt(p, G) * ghost;
}
// The glass itself, lit by the room. It is almost nothing, but a frame of
// exactly zero gives the dither nothing to bite on, and the demo should
// end on a dark tube rather than on a hole.
// exp, not a linear falloff: at 32:9 the corner is 3.7 units out and a
// linear term would have gone negative long before it got there.
col += float3(0.008, 0.010, 0.016) * exp(-length(p) * 0.45);
return float4(col * gTime.z, 1.0);
}

205
fx/reactor.hlsl Normal file
View file

@ -0,0 +1,205 @@
// SOLO orders 16-39. Bounded, opaque sculpture; host owns camera and grading.
// Tune: variant [0,3], motion [0,2], cyan->magenta accent [0,1], deform [0,1].
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
struct VSOut { float4 pos : SV_Position; float2 uv : TEXCOORD0; };
static float sClock, sExpand, sFly, sCollapse, sDeform;
static float2 sCoreSpin;
static float2 sRingSpin[3];
static float2 sRingTilt[3];
static float sRadius[3];
static float sLift[3];
float3 safeUnit(float3 v, float3 fallback)
{
float d = dot(v, v);
return d > 1e-10 ? v * rsqrt(max(d, 1e-10)) : fallback;
}
float2 turn(float2 p, float2 cs)
{
return float2(cs.x*p.x - cs.y*p.y, cs.y*p.x + cs.x*p.y);
}
float box3(float3 p, float3 b)
{
float3 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
}
float box2(float2 p, float2 b)
{
float2 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}
// x conservative distance, y material: porous alloy / mechanical / hot heart.
float2 field(float3 p)
{
float3 q = p;
q.xz = turn(q.xz, sCoreSpin);
q.xy = turn(q.xy, float2(0.9393727, 0.3428978));
float collapse = 1.0 - 0.48*sCollapse;
float3 axes = float3(1.85, 1.34, 1.12)
+ sExpand*float3(0.90, 0.66, 0.65);
axes *= collapse;
// Ellipsoid bound and gyroid both use lower distance bounds.
float shell = (length(q / axes) - 1.0) * axes.z;
float frequency = lerp(2.65, 2.05, sExpand);
float3 u = q*frequency + float3(0.0, sClock*0.27, 0.0);
float gy = dot(sin(u), cos(u.yzx));
// Gradient norm <= 2*sqrt(3)*frequency. No spatial warp hidden in steps.
float thickness = 0.36 + 0.15*sDeform
+ 0.08*sin(sClock*1.1);
float porous = (abs(gy) - thickness) / (3.465*frequency);
float2 result = float2(max(shell, porous), 0.0);
// An elongated counter-rotating heart is visible through real holes.
float3 heart = p;
heart.yz = turn(heart.yz, sCoreSpin.yx);
float h = (dot(abs(heart), float3(1.0, 0.72, 1.0))
- (0.65 - 0.22*sCollapse)) / 1.588;
if (h < result.x) result = float2(h, 2.0);
[loop] for (int j = 0; j < 3; ++j)
{
float3 r = p;
r.yz = turn(r.yz, sRingTilt[j]);
r.xy = turn(r.xy, sRingSpin[j]);
r.z -= sLift[j];
float radial = length(r.xy) - sRadius[j];
// Bevelled rectangular cross-section, open quadrant and severed ends.
float arc = box2(float2(radial, r.z), float2(0.18, 0.13)) - 0.075;
arc = max(arc, -max(r.x, r.y));
arc = max(arc, 0.22 + 0.28*sFly - abs(r.y));
if (arc < result.x) result = float2(arc, 1.0);
// Broad pieces at the outer radius cross IN FRONT of the lattice.
// Opposed pieces are displaced in depth, not camera-facing sprites.
float3 shard = r;
float side = r.x < 0.0 ? -1.0 : 1.0;
shard.x = abs(shard.x) - (sRadius[j] + 0.12);
shard.y -= side * (0.75 + 0.25*sFly);
shard.z -= side * (0.25 + 0.38*sFly);
shard.yz = turn(shard.yz, float2(0.8, 0.6));
float piece = box3(shard, float3(0.25, 0.55, 0.18)) - 0.075;
if (piece < result.x) result = float2(piece, 1.0);
}
// Hard guarantee for the analytic ray interval, including all tune values.
result.x = max(result.x, length(p) - 5.95);
return result;
}
float3 normalAt(float3 p, float e)
{
float3 a = float3(1.0, -1.0, -1.0);
float3 b = float3(-1.0, -1.0, 1.0);
float3 c = float3(-1.0, 1.0, -1.0);
float3 d = float3(1.0, 1.0, 1.0);
return safeUnit(a*field(p+a*e).x + b*field(p+b*e).x
+ c*field(p+c*e).x + d*field(p+d*e).x,
float3(0.0, 1.0, 0.0));
}
float4 main(VSOut i, out float depth : SV_Depth) : SV_Target
{
depth = 0.0;
float variant = clamp(gTune.x, 0.0, 3.0);
sExpand = saturate(1.0 - abs(variant - 1.0));
sFly = saturate(1.0 - abs(variant - 2.0));
sDeform = saturate(gTune.w);
sClock = gTime.x * clamp(gTune.y, 0.0, 2.0);
// Collapse cycles continuously; neither beat resets nor full-frame flashes.
sCollapse = saturate(variant - 2.0)
* (0.58 + 0.32*sin(sClock*0.72));
float angle = sClock*0.29;
sCoreSpin = float2(cos(angle), sin(angle));
[loop] for (int j = 0; j < 3; ++j)
{
float fj = float(j);
float a = sClock*(0.22 + fj*0.09)*(j == 1 ? -1.0 : 1.0) + fj*2.1;
float b = 0.55 + fj*0.83 + (0.22 + 0.40*sFly)*sin(sClock*0.31 + fj);
sRingSpin[j] = float2(cos(a), sin(a));
sRingTilt[j] = float2(cos(b), sin(b));
sRadius[j] = 2.95 + fj*0.39 + 0.48*sFly + 0.22*sExpand
- 0.75*sCollapse + (0.10 + 0.12*sDeform)*sin(sClock*0.83 + fj*2.0);
sLift[j] = (0.18 + 0.38*sFly)*sin(sClock*0.57 + fj*2.3);
}
float2 uv = float2(i.uv.x*2.0 - 1.0, 1.0 - i.uv.y*2.0);
uv.x *= max(gTime.w, 0.01);
float3 fw = safeUnit(gDir.xyz, float3(0.0, 0.0, 1.0));
float3 reference = abs(fw.y) > 0.98 ? float3(0.0, 0.0, 1.0) : float3(0.0, 1.0, 0.0);
float3 rt = safeUnit(cross(reference, fw), float3(1.0, 0.0, 0.0));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 rd = safeUnit(fw + max(gCam.w, 0.001)
* (uv.x*(rt*cr + up*sr) + uv.y*(up*cr - rt*sr)), fw);
float3 ro = gCam.xyz;
float3 col = float3(0.003, 0.005, 0.012);
float bRay = dot(ro, rd);
float discriminant = bRay*bRay - dot(ro, ro) + 36.0;
if (discriminant < 0.0) return float4(col*gTime.z, 1.0);
float root = sqrt(max(discriminant, 0.0));
float t = max(0.0, -bRay - root);
float end = -bRay + root;
bool hit = false;
float2 sampleHit = float2(0.0, 0.0);
[loop] for (int step = 0; step < 80; ++step)
{
if (t > end) break;
sampleHit = field(ro + rd*t);
float epsilon = max(0.0025, t*0.00040);
if (sampleHit.x < epsilon) { hit = true; break; }
t += max(sampleHit.x*0.88, 0.001);
}
if (hit)
{
float3 p = ro + rd*t;
float3 n = normalAt(p, max(0.002, t*0.00022));
float3 key = safeUnit(float3(-5.0, 7.0, -4.0)-p, fw);
float3 fill = safeUnit(float3(5.0, 1.0, 4.0)-p, fw);
// Broad off-axis camera fill keeps lattice faces readable throughout
// an orbit. World-space key and opposing cyan fill retain modelling.
float3 cameraFill = safeUnit(ro + rt*4.0 + up*3.0 - p, -rd);
float3 warm = float3(1.0, 0.52, 0.24);
float3 cyan = float3(0.08, 0.73, 0.90);
float3 accent = lerp(cyan, float3(0.91, 0.09, 0.43), saturate(gTune.z));
float mechanical = sampleHit.y > 0.5 && sampleHit.y < 1.5 ? 1.0 : 0.0;
float heart = sampleHit.y > 1.5 ? 1.0 : 0.0;
float ao = 1.0;
// Conservative field is deliberately scaled; this is contact shading.
[loop] for (int k = 1; k <= 3; ++k)
{
float reach = 0.12*float(k);
ao -= max(0.0, reach - field(p+n*reach).x)*0.48;
}
ao = clamp(ao, 0.35, 1.0);
float diffuse = saturate(dot(n, key));
float back = saturate(dot(n, fill));
float front = saturate(dot(n, cameraFill));
float fresnel = pow(1.0-saturate(dot(n, -rd)), 3.0);
float spec = pow(saturate(dot(n, safeUnit(key-rd, n))), 42.0);
float spec2 = pow(saturate(dot(n, safeUnit(fill-rd, n))), 28.0);
float3 alloy = lerp(accent*0.66 + float3(0.055, 0.045, 0.06),
float3(0.36, 0.43, 0.50), mechanical);
col = alloy*(0.20 + diffuse*1.80 + front*0.85)*ao;
col += cyan*back*0.60*ao + warm*spec*0.85 + accent*spec2*0.60;
col += accent*fresnel*(0.15 + 0.13*saturate(gVoice.y))*ao;
float flow = 0.5 + 0.5*sin(p.y*3.0 + p.x*1.7 - sClock*2.0);
col += accent*(1.0-mechanical)*(0.05 + 0.12*flow);
col += heart*lerp(warm, accent, 0.35)
* (0.60 + 0.22*saturate(gVoice.y) + 0.10*saturate(gSync.y));
depth = saturate(0.05 / max(t*dot(rd, fw), 0.001));
}
return float4(col*gTime.z, 1.0);
}

504
fx/scene.hlsl Normal file
View file

@ -0,0 +1,504 @@
// Shot 05 - CATHEDRAL / ORGAN HALL.
//
// The one room in the demo that IS an organ, and it gets five seconds under
// the cold open with the camera barely moving - 1.15 units per second down a
// nave whose key light stays 74 units ahead forever. A push that never
// arrives is a still frame unless the ROOM moves, so everything here that
// reads is either built out of the bay rhythm the camera slides past, or it
// is animated on gTime.x on its own clock:
//
// the arcade real arches spanning every bay, so the colonnade is an
// arcade and not a row of posts. It is what turns the push
// into travel: arches pass overhead, one per bay.
// the aisle glass tall leaded lancets in the outer wall, one per bay,
// seen THROUGH the arcade. A slow wave of brightness runs
// down the row, and the whole rank breathes on gSync.y.
// the aisle light cool daylight pooling in the side aisles under those
// windows, against the warm key down the axis. The band it
// fills drifts vertically as if the sun were moving.
// the organ a rank of pipes on a gallery at |x| = 13.6, running the
// length of the hall behind the arcade, tips lit by
// gVoice.z. The organ is playing alone; the pipes should
// know that.
// the rose the light at the end of the nave is now a rose window
// with tracery, an oculus and a shimmer, still a bright
// disc dead centre so the MATCH CUT still has its shape.
// the lamps three lamps on chains down the axis, swaying on their
// own periods. Pure parallax: they are what tells you the
// camera is moving at all.
// the floor flagstones, and the key light smeared the length of the
// polished stone. The eye sits 6.5 above the floor on this
// shot, so that reflection is a third of the frame.
//
// NOTHING in here multiplies the whole picture by an audio envelope. Every
// music-driven term is base + k*s, so no floor ever drops out.
//
// Everything is [loop], never [unroll]. An unrolled march is the one thing
// that would blow the executable size out on its own.
//
// The volumetric is deliberately built out of LOW frequencies only. March
// steps in the open nave are five or six units long; anything with detail
// finer than that would flicker as the camera pushed through it. The
// per-bay rhythm you see in the air is a shallow 30% modulation on a smooth
// lobe - the sharp per-bay detail lives in the window SURFACES, where there
// is no sampling problem at all.
cbuffer Scene : register(b0)
{
float4 gTime; // x time, y beat, z shot fade, w aspect (w/h)
float4 gCam; // xyz eye, w tan(vfov/2)
float4 gDir; // xyz look direction, w roll
float4 gTune; // per shot knobs
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// ---- the per-shot dials, decoded once at the top of main() ---------------
//
// gTune.x the arcade. bay pitch and column proportion. 0 gives 13 unit
// bays and fat 1.3 columns; 1 gives 8 unit bays,
// slimmer columns and finer fluting. Everything
// that repeats down the nave - arches, ribs,
// windows, the shafts in the air - follows the bay,
// so this one float relays the whole hall.
// gTune.y the organ loft. -0.6 and below deletes the pipe rank and its
// gallery outright and you get a bare hall; 0 is a
// medium rank; +0.4 a full one with a tall skyline.
// gTune.z the air. haze, fog density, how much volumetric there is.
// gTune.w the glass. stained glass brightness, how much daylight pools
// in the aisles, the rake of the shafts, and the
// spoke count of the rose window (8 to 16).
static float sBay = 13.0;
static float sBayInv = 0.076923077;
static float sColR = 1.30;
static float sFlute = 18.0;
static float sLoft = 0.60;
static float sSpread = 0.55;
// ---- distance field ------------------------------------------------------
float vmax3(float3 v) { return max(v.x, max(v.y, v.z)); }
float sdBox(float3 p, float3 b)
{
float3 q = abs(p) - b;
return length(max(q, 0.0)) + min(vmax3(q), 0.0);
}
float sdBox2(float2 p, float2 b)
{
float2 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
}
// One column, centred on the origin, standing on the floor.
float column(float3 p)
{
float2 q = p.xz;
float d = length(q) - sColR;
d += 0.055 * sin(atan2(q.y, q.x) * sFlute); // flutes
d = max(d, p.y - 13.2); // stop under the capital
d = min(d, sdBox(p - float3(0.0, -5.3, 0.0), float3(sColR + 0.65, 0.75, sColR + 0.65)) - 0.10);
d = min(d, sdBox(p - float3(0.0, 13.0, 0.0), float3(sColR + 0.80, 0.85, sColR + 0.80)) - 0.14);
return d;
}
float map(float3 p)
{
float d = p.y + 6.0; // floor
// Walls, and a barrel vault springing from y = 12. Below the spring
// line the max() collapses this to a flat wall at |x| = 16.5.
float2 v = float2(p.x, max(p.y - 12.0, 0.0));
float lv = length(v);
d = min(d, 16.5 - lv);
// Two colonnades, repeated down the nave. cz is zero AT a column.
float3 c = p;
c.x = abs(c.x) - 10.0;
c.z = frac(p.z * sBayInv + 0.5) * sBay - sBay * 0.5;
d = min(d, column(c));
// A transverse rib over each bay, on the column line. Without them the
// vault is one smooth surface that takes the fill light evenly and reads
// as a flat grey ceiling rather than as a curve. It reuses lv, which is
// the same length() the wall already paid for.
d = min(d, max(15.75 - lv, abs(c.z) - 0.62));
// A ridge rib along the crown, running the length. It is the only line
// in the room that points where the camera is going, and on a five
// second push down the axis that is most of the composition.
d = min(d, max(15.80 - lv, abs(p.x) - 0.50));
// THE ARCADE. A semicircular arch spanning each bay between the columns,
// springing just above the capitals. Below the springing the same
// expression collapses to a 0.62 shaft standing exactly at the column
// centres, which is buried inside the columns and costs nothing.
{
float ax = abs(p.x) - 10.0;
float az = frac(p.z * sBayInv) * sBay - sBay * 0.5; // zero MID bay
float2 rq = float2(az, max(p.y - 13.9, 0.0));
float ring = length(rq) - sBay * 0.5;
d = min(d, length(float2(ring, ax)) - 0.62);
}
// THE ORGAN. A rank of pipes on a gallery behind the arcade, heights
// walked by a golden-ratio sequence so the skyline reads as random
// without a single transcendental. The 0.65 is a deliberate
// underestimate: neighbouring cells have different heights, which breaks
// the Lipschitz bound near a tip, and marching short is cheaper than
// marching a punched-through pipe.
if (sLoft > 0.02) {
float ax = abs(p.x) - 13.60;
float pu = p.z * 1.0526316; // period 0.95
float g = frac(floor(pu) * 0.61803399 + 0.137);
float pz = (frac(pu) - 0.5) * 0.95;
float top = 15.40 + (2.20 + 2.40 * sSpread) * g;
float pipe = length(float2(ax, pz)) - 0.32;
pipe = max(pipe, p.y - top);
pipe = max(pipe, 13.95 - p.y);
float ledge = sdBox2(float2(ax, p.y - 13.55), float2(1.15, 0.40)) - 0.08;
d = min(d, min(pipe * 0.65, ledge));
}
return d;
}
// Tetrahedral, not central-difference. The room got two new solids this
// pass and map() is inlined once per tap, so four taps instead of six is
// twenty percent off the compiled blob for a normal nobody can tell apart.
float3 mapNormal(float3 p)
{
const float e = 0.0022;
float3 k = float3(1.0, -1.0, 1.0);
return normalize(k.xyy * map(p + k.xyy * e) +
k.yyx * map(p + k.yyx * e) +
k.yxy * map(p + k.yxy * e) +
k.xxx * map(p + k.xxx * e));
}
float softShadow(float3 ro, float3 lightPos)
{
float3 toLight = lightPos - ro;
float lightDist = length(toLight);
float tMax = min(55.0, lightDist);
float res = 1.0, t = 0.35;
if (tMax <= t) return res;
float3 rd = toLight / lightDist;
[loop] for (int i = 0; i < 24; i++) {
// Test before map(): an overshooting step must not sample past the light.
if (t >= tMax) break;
float h = map(ro + rd * t);
if (h < 0.002) return 0.0;
res = min(res, 11.0 * h / t);
t += clamp(h, 0.12, 2.5);
}
return saturate(res);
}
// Cheap ambient occlusion: how much of the field is nearby along the normal.
float occlusion(float3 p, float3 n)
{
float o = 0.0, s = 1.0;
[loop] for (int i = 0; i < 5; i++) {
float d = 0.10 + 0.28 * float(i);
o += (d - map(p + n * d)) * s;
s *= 0.62;
}
return saturate(1.0 - 1.4 * o);
}
// ---- shading -------------------------------------------------------------
float4 main(VSOut i, out float depth : SV_Depth) : SV_Target
{
depth = 0.0; // far, under reversed Z
// ---- dials ----
float a = saturate(gTune.x);
sBay = 13.0 - 5.0 * a;
sBayInv = 1.0 / sBay;
sColR = 1.30 - 0.42 * a;
sFlute = 18.0 + 10.0 * a;
sLoft = saturate(0.60 + gTune.y);
sSpread = saturate(0.55 + gTune.y);
float air = saturate(0.55 + gTune.z);
float glass = saturate(0.70 + gTune.w);
float spokes = 8.0 + floor(glass * 8.0);
float tilt = 0.42 + 0.55 * glass; // rake of the daylight
float drift = gTime.x * 0.020 * (0.4 + air);
// The sun, moving. It is the slowest thing in the demo on purpose: over
// five seconds it lifts the lit band on the aisle wall by about a metre,
// which you do not see happen but do see the result of.
float sunTop = 12.6 + 1.7 * sin(gTime.x * 0.155);
float2 uv = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y is FLIPPED here on purpose. The fullscreen triangle emits
// uv.y = 0 at the top of the screen, so i.uv*2-1 gives -1 up
// there and the top of the frame ended up looking DOWNWARD -
// the cathedral vault springs at y=+12 and was rendering in the
// lower half, the monolith hung from the ceiling.
uv.x *= gTime.w;
float3 fw = normalize(gDir.xyz);
float3 rt = normalize(cross(float3(0.0, 1.0, 0.0), fw));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 r2 = rt * cr + up * sr;
float3 u2 = up * cr - rt * sr;
float3 ro = gCam.xyz;
float3 rd = normalize(fw + (uv.x * r2 + uv.y * u2) * gCam.w);
// The light at the end of the nave, and a much dimmer one over the
// camera so the nearest columns are not pure silhouette. Inverse square
// over 70 units eats almost everything, so the key is genuinely huge.
float3 lp = float3(0.0, 15.0, ro.z + 74.0);
float3 lp2 = float3(0.0, 16.0, ro.z + 4.0);
// The organ breathing the key. Small on purpose: the key lights the far
// end of a 74 unit nave, so this is a swell and not a flash.
float keyM = 1.0 + 0.25 * gVoice.z + 0.10 * gSync.x;
float t = 0.0;
float shaft = 0.0;
float beams = 0.0;
bool hit = false;
[loop] for (int k = 0; k < 104; k++) {
float3 p = ro + rd * t;
float h = map(p);
float w = min(h, 1.2);
// Volumetric: distance from this sample to the light, accumulated.
// It is what makes the hall read as full of air rather than vacuum.
float dl = length(p - lp);
shaft += 900.0 / (1.0 + dl * dl) * w;
// DAYLIGHT IN THE AISLES, on every other step. Trace the sample back
// along the rake to the outer wall and ask how far up that wall it
// came from: below the lit band you get light, above it you get the
// dark haunch of the vault. The per-bay lobe is only a 30% ripple on
// top - see the note at the head of the file about step length.
if ((k & 1) == 0) {
float ax = abs(p.x);
float s = max(16.5 - ax, 0.0);
float wy = p.y + tilt * s;
float bw = abs(frac(p.z * sBayInv + drift) - 0.5);
float lobe = saturate(1.0 - bw * 2.2); lobe *= lobe;
float pool = saturate((ax - 6.5) * 0.15) // aisles, not the nave
* saturate((sunTop - wy) * 0.22) // under the lit band
* saturate((p.y + 7.5) * 0.30); // and off the floor
// The air itself, turning over. Twenty unit wavelengths, so the
// march resolves it however long the steps get.
float swirl = 0.86 + 0.14 * sin(p.z * 0.29 + gTime.x * 0.47)
* sin(p.y * 0.25 - gTime.x * 0.31);
beams += pool * (0.70 + 0.30 * lobe) * swirl * w;
}
if (h < 0.0016 * t) {
hit = true;
// rd is normalised, so t is RAY LENGTH. Projecting it onto the
// forward axis is what makes this VIEW depth - without the dot
// the mesh punches through the field towards the screen edges
// while looking perfectly correct dead centre.
depth = saturate(0.05 / max(t * dot(rd, fw), 0.001));
break;
}
t += h * 0.86;
if (t > 190.0) break;
}
float3 col = float3(0.0, 0.0, 0.0);
float3 warm = float3(1.00, 0.74, 0.46);
float3 cool = float3(0.30, 0.38, 0.56);
float3 day = float3(0.60, 0.71, 0.96);
if (hit) {
float3 p = ro + rd * t;
float3 n = mapNormal(p);
float3 ld = normalize(lp - p);
float dl = length(lp - p);
float dif = saturate(dot(n, ld)) * (5200.0 * keyM / (1.0 + dl * dl));
dif *= softShadow(p + n * 0.03, lp);
float3 ld2 = normalize(lp2 - p);
float dl2 = length(lp2 - p);
float fil = saturate(dot(n, ld2)) * (260.0 / (1.0 + dl2 * dl2));
float ao = occlusion(p, n);
float fres = pow(1.0 - saturate(dot(n, -rd)), 4.0);
// ---- who am I standing on --------------------------------------
// Position is a cheaper material id than carrying one through the
// march, and in a room this rigid it is exact.
float ax = abs(p.x);
float onFloor = saturate((-5.80 - p.y) * 40.0) * saturate(n.y * 4.0 - 2.0);
float onPipe = saturate((p.y - 14.00) * 6.0)
* saturate((ax - 13.05) * 8.0) * saturate((14.15 - ax) * 8.0);
float onWall = saturate((ax - 15.75) * 5.0) * saturate((12.20 - p.y) * 4.0);
// Flagstones. A grid this coarse survives the CRT quantiser, which a
// finer one would not.
float3 alb = float3(1.0, 1.0, 1.0);
{
float2 fg = abs(frac(p.xz * 0.24) - 0.5);
float grout = saturate(min(fg.x, fg.y) * 26.0);
alb = lerp(alb, float3(0.90, 0.88, 0.85) * (0.55 + 0.45 * grout), onFloor);
}
alb = lerp(alb, float3(0.78, 0.80, 0.86), onPipe); // tin, not stone
col = warm * dif * alb;
col += cool * fil * 0.42 * alb;
col += cool * ao * 0.075 * (0.35 + 0.65 * saturate(n.y));
col += warm * fres * 0.30 * ao;
col *= 0.35 + 0.65 * ao;
// Specular. Polished stone and tin only; the rest of the hall is
// rough and gets essentially none.
{
float3 hv = normalize(ld - rd);
float spc = pow(saturate(dot(n, hv)), 60.0);
col += warm * spc * (0.08 + 2.4 * onPipe + 1.4 * onFloor) * saturate(dif * 4.0);
}
// The key light smeared the length of the polished floor. The eye
// sits 6.5 above the flagstones on the one shot this scene has, so
// this reflection runs from the bottom of the frame to the horizon
// and is doing as much work as the light itself.
{
float rk = saturate(dot(reflect(rd, n), ld));
col += warm * onFloor * (pow(rk, 30.0) * 0.60 + pow(rk, 5.0) * 0.09)
* (0.55 + 0.45 * keyM);
}
// The pipes catching the organ. Fresnel on a cylinder is an edge
// light, which is exactly how a rank of tin pipes reads at sixty
// units - two bright verticals per pipe and nothing in between.
col += float3(0.95, 0.80, 0.58) * onPipe * fres * ao * (0.30 + 0.85 * gVoice.z) * 1.6;
// ---- THE AISLE GLASS -------------------------------------------
// One tall leaded lancet per bay in the outer wall, centred MID bay
// so it sits under an arch rather than behind a column. Emissive, so
// it goes on after the ao multiply.
{
float bz = frac(p.z * sBayInv) * sBay - sBay * 0.5;
float bi = floor(p.z * sBayInv);
float wt = (p.y - 4.0) * 0.142857; // 0..1 up the window
float hw = 0.185 * sBay * saturate(1.0 - saturate((wt - 0.58) * 2.4));
float inw = saturate((hw - abs(bz)) * 6.0)
* saturate(wt * 8.0) * saturate((1.0 - wt) * 8.0);
float mull = saturate(abs(frac(bz * 1.30) - 0.5) * 7.0 - 0.55); // mullions
float tran = saturate(abs(frac(p.y * 0.95) - 0.5) * 7.0 - 0.55); // transoms
float cell = frac(floor(bz * 1.30) * 0.6180 + floor(p.y * 0.95) * 0.3125
+ bi * 0.271);
float3 tint = lerp(float3(0.98, 0.63, 0.28), float3(0.32, 0.57, 0.95),
frac(bi * 0.6180 + 0.31));
tint = lerp(tint, float3(0.82, 0.91, 1.00), 0.35 * cell);
// A wave of brightness running down the row, plus the mid band.
// Both are base + k*s; the rank never goes out.
float wave = 0.84 + 0.16 * sin(p.z * 0.085 - gTime.x * 0.62);
float lum = inw * mull * tran * (0.60 + 0.65 * cell)
* glass * (0.55 + 0.45 * gSync.y) * wave;
col += tint * lum * onWall * 1.5;
}
}
col += float3(1.00, 0.76, 0.50) * shaft * 0.0016 * (1.0 + 0.30 * gVoice.z);
// The aisles, cool, against the warm key down the axis. w is capped at
// 1.2 while steps in the open run to five units, so this accumulator
// under-weights open space by roughly four to one - which is where the
// 0.22 comes from and why it looks nothing like the 0.0016 above it.
col += day * beams * 0.220 * (0.35 + 0.65 * glass) * (0.5 + 0.5 * air);
// ---- THE ROSE WINDOW ---------------------------------------------------
// The source at the end of the nave used to be a featureless blob. It is
// still a bright disc dead centre - the MATCH CUT at bar 9 depends on
// that - but now it has tracery, an oculus and a shimmer, and it swells
// with the organ. The disc is a coherent region of screen, so the atan2
// behind the rr < 1.25 test is paid for by almost no wave that is not
// looking straight at it.
{
float3 tol = lp - ro;
float proj = dot(tol, rd);
if (proj > 0.0) {
float perp = length(tol - rd * proj);
float vis = (proj < t) ? 1.0 : 0.0;
col += float3(1.00, 0.80, 0.55) * (2.4 / (1.0 + perp * perp * 0.55))
* (proj < t ? 1.0 : 0.30) * (0.72 + 0.42 * keyM);
if (rd.z > 0.05 && vis > 0.5) {
float tz = (lp.z - ro.z) / rd.z;
float2 wp = float2(ro.x + rd.x * tz - lp.x, ro.y + rd.y * tz - lp.y);
float rr = length(wp) * 0.19231; // window radius 5.2
if (rr < 1.25) {
float an = atan2(wp.y, wp.x);
float sp = an * spokes * 0.15915494;
float sw = abs(frac(sp) - 0.5) * 2.0;
float rg = abs(frac(rr * 3.0) - 0.5) * 2.0;
float lead = saturate(sw * 5.0 - 0.45) * saturate(rg * 5.0 - 0.35);
float cell = frac(floor(sp) * 0.6180 + floor(rr * 3.0) * 0.317);
float disc = saturate((1.0 - rr) * 7.0);
float rim = saturate(1.0 - abs(rr - 1.0) * 14.0);
float ocu = saturate(1.0 - rr * 7.0);
float3 gc = lerp(float3(1.00, 0.72, 0.36),
float3(0.55, 0.72, 1.00), cell);
float shm = 0.90 + 0.10 * sin(rr * 16.0 - gTime.x * 0.9 + an * 2.0);
float bri = (0.58 + 0.52 * gVoice.z) * shm;
col += gc * disc * lead * (0.55 + 0.90 * cell) * bri * 2.1;
col += float3(1.00, 0.86, 0.62) * rim * 1.3 * bri;
col += float3(1.00, 0.92, 0.72) * ocu * 2.6 * bri;
}
}
}
}
// ---- LAMPS ON CHAINS ---------------------------------------------------
// Three of them down the axis, each on its own period so they never line
// up. They are the parallax: at 1.15 units per second the columns barely
// move, but a lamp passing the frame at eight units does.
[loop] for (int L = 0; L < 3; L++) {
float fl = float(L);
float lz = ro.z + 17.0 + fl * sBay * 1.5;
float sway = 1.05 * sin(gTime.x * (0.52 + 0.09 * fl) + fl * 2.4);
float3 lm = float3(sway, 6.2 - 0.10 * abs(sway), lz);
float3 tl = lm - ro;
float pj = dot(tl, rd);
if (pj > 0.0 && pj < t) {
float pe = length(tl - rd * pj);
col += float3(1.00, 0.72, 0.38) * (0.42 / (1.0 + pe * pe * 9.0))
* (1.0 + 0.50 * gSync.z);
}
}
// Exponential distance fog, so the far end of the nave dissolves.
float fog = exp(-t * (0.0042 + 0.0060 * air));
col = col * fog + float3(0.055, 0.050, 0.062) * (1.0 - fog) * (0.85 + 0.35 * glass);
return float4(col * gTime.z, 1.0);
}

315
fx/signoff.hlsl Normal file
View file

@ -0,0 +1,315 @@
// The only text in the demo.
//
// crt.fyi
// hi@crt.fyi
//
// Two lines, small, once. The author was explicit about that and it is the
// right call: a demo that tells you who made it in forty-point letters is
// advertising, and a demo that puts it in the corner once at the end is a
// signature. So this file is not allowed to grow the type or centre it. What
// it IS allowed to do is make the eleven seconds it owns worth watching:
// the line writes itself, character by character, with a caret ahead of it
// and the phosphor still hot behind it.
//
// No glyph atlas. Between them these two lines use eleven distinct
// characters, and a monoline stroke distance field draws them from about
// thirty line segments - less code than the loader for an atlas would be,
// and it stays sharp at any size because it is analytic. The strokes are
// deliberately even-weight and slightly wide: at 360 lines a typographic
// contrast would just alias into mush.
//
// gTune.x typing speed, 1.0 = the tuned default (about eleven glyphs a
// second). The reveal used to be an absolute 0..1 fed from the shot
// table, and the shot table fed it a constant 1.0 - so the "typing"
// the comment promised never happened once. It is derived from
// gTime.x now, and gTune.x only scales the rate.
// gTune.y size
// gTune.z which line: 0 both, 1 only the address
// gTune.w the matte, as a fraction of the height hidden at each edge
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
float4 gSync;
float4 gVoice;
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
// distance to a line segment, the primitive everything here is built from
float sdSeg(float2 p, float2 a, float2 b)
{
float2 pa = p - a, ba = b - a;
float h = saturate(dot(pa, ba) / dot(ba, ba));
return length(pa - ba * h);
}
// distance to an arc of a circle, for the round letters. a0..a1 in radians.
float sdArc(float2 p, float2 c, float r, float a0, float a1)
{
float2 q = p - c;
float a = atan2(q.y, q.x);
// wrap the angle into [a0, a0+2pi) so the comparison is unambiguous
float w = a - a0;
w -= 6.28318530718 * floor(w / 6.28318530718);
if (w <= a1 - a0) return abs(length(q) - r);
// outside the sweep: the nearer of the two end points
float2 e0 = c + float2(cos(a0), sin(a0)) * r;
float2 e1 = c + float2(cos(a1), sin(a1)) * r;
return min(length(p - e0), length(p - e1));
}
// Each glyph is drawn in a box 0.62 wide and 1.0 tall, with the baseline at
// y = 0 and the x-height at 0.58 - the proportions of a plain grotesque.
float glyph(float2 p, int c)
{
float d = 1e9;
if (c == 0) { // c
d = sdArc(p, float2(0.31, 0.31), 0.27, 0.55, 5.73);
} else if (c == 1) { // r
// The arm used to sweep from three o'clock, which hooks it down past
// the middle of the x-height and makes the r read as a curl. A
// grotesque r lets go earlier and higher: the shoulder tops out AT
// the x-height and the terminal stops just under it.
d = min(sdSeg(p, float2(0.14, 0.0), float2(0.14, 0.58)),
sdArc(p, float2(0.34, 0.40), 0.19, 0.30, 2.60));
} else if (c == 2) { // t
d = min(sdSeg(p, float2(0.24, 0.10), float2(0.24, 0.86)),
sdSeg(p, float2(0.06, 0.58), float2(0.44, 0.58)));
// the tail bottoms out ON the baseline and lifts again, instead of
// ending nose-down under it
d = min(d, sdArc(p, float2(0.38, 0.14), 0.14, 3.14, 4.95));
} else if (c == 3) { // .
d = length(p - float2(0.16, 0.065)) - 0.048;
} else if (c == 4) { // f
d = min(sdSeg(p, float2(0.26, 0.0), float2(0.26, 0.72)),
sdSeg(p, float2(0.08, 0.58), float2(0.46, 0.58)));
d = min(d, sdArc(p, float2(0.40, 0.72), 0.14, 1.57, 3.14));
} else if (c == 5) { // y
d = min(sdSeg(p, float2(0.08, 0.58), float2(0.30, 0.06)),
sdSeg(p, float2(0.52, 0.58), float2(0.20, -0.22)));
} else if (c == 6) { // i
d = sdSeg(p, float2(0.16, 0.0), float2(0.16, 0.58));
// The dot has to clear the STROKE, not the centreline. Ink extends
// w = 0.070 glyph units past the geometry on both sides, so a dot at
// 0.775 with r 0.048 left 0.775-0.048-0.070-0.58 = 0.007 units of
// gap: a sixth of a virtual pixel. The two merged and the demo spelt
// the author's own domain "crt.fyl". At 0.88 with a slightly smaller
// dot the gap is 0.120 units, two and a half virtual lines of real
// dark, and it reads as an i.
d = min(d, length(p - float2(0.16, 0.88)) - 0.040);
} else if (c == 7) { // h
// shoulder raised so the h reaches the same x-height as the c and
// the r; it was sitting two hundredths low and the word looked like
// it had a dip in it
d = min(sdSeg(p, float2(0.12, 0.0), float2(0.12, 0.90)),
sdSeg(p, float2(0.44, 0.0), float2(0.44, 0.42)));
d = min(d, sdArc(p, float2(0.28, 0.42), 0.16, 0.0, 3.14));
} else if (c == 8) { // @
// The inner ring has to clear the outer one by more than the ink
// reaches, or the counter fills in and the @ reads as a solid disc.
// The comment that used to sit here claimed this was measured. It was
// not, and it was wrong: at r 0.095 the annulus is
// (0.31 - 0.070) - (0.095 + 0.070) = 0.075 glyph units
// which at this size is 1.46 virtual pixels - BELOW the threshold the
// i's dot just established at 2.34. So the c beside it kept its
// counter and the @ filled in, and the demo signed off with a blob in
// the middle of the author's email address. 0.05 puts the annulus at
// 0.120 units, the same gap that works for the i.
d = sdArc(p, float2(0.31, 0.34), 0.31, 0.60, 6.10);
d = min(d, sdArc(p, float2(0.31, 0.34), 0.05, 0.0, 6.28));
d = min(d, sdSeg(p, float2(0.405, 0.34), float2(0.405, 0.15)));
}
return d;
}
// crt.fyi -> c r t . f y i (index 0, seven glyphs)
// hi@crt.fyi -> h i @ c r t . f y i (index 7, ten glyphs)
// One table, two offsets, so the loop can only ever index inside it.
static const int kText[17] = { 0, 1, 2, 3, 4, 5, 6,
7, 6, 8, 0, 1, 2, 3, 4, 5, 6 };
// METRICS. Every glyph used to advance 0.72 whatever it was, which is a
// teletype and not a grotesque: the period and the i sat in the middle of
// slots twice their width and "crt.fyi" came out with two holes punched in
// it. kLsb pulls each glyph over so its ink starts at the origin, kAdv is
// the ink width plus about 0.30 of tracking - the round letters tucked in by
// the usual optical hundredths, and the i and the @ given back what the ring
// and the bare stem need so "hi@" does not collide. The address ends up
// fifteen percent tighter than it was, which is the opposite of enlarging it.
// c r t . f y i h @
static const float kLsb[9] = { 0.04, 0.14, 0.06, 0.112, 0.08, 0.08, 0.16, 0.12, 0.00 };
static const float kAdv[9] = { 0.80, 0.70, 0.68, 0.40, 0.66, 0.70, 0.34, 0.62, 0.94 };
// One line of type, written on. Returns
// x ink coverage 0..1
// y tight phosphor glow the beam spot
// z halation light scattered in the glass
// w the write head, in glyph units, for the caret
//
// prog is measured in glyph slots: 3.4 means three characters are down and
// the fourth is 40 percent of the way through its slot.
float4 drawLine(float2 p, int base, int n, float prog, float fw, float w)
{
float ink = 0.0, hot = 0.0, hal = 0.0;
float x = 0.0, head = 0.0;
[loop] for (int k = 0; k < 10; k++)
{
if (k >= n) break;
float age = prog - (float)k;
if (age <= 0.0) break; // not typed yet
int c = kText[base + k];
float d = glyph(p - float2(x - kLsb[c], 0.0), c) - w;
// A character does not fade in over a fifth of a second - it is
// struck. Two frames from nothing to solid, and then the phosphor
// where it landed stays hot for about a sixth of a second after.
float f = saturate(age * 3.2);
float s = exp(-max(age - 1.0, 0.0) * 0.55);
ink = max(ink, (1.0 - smoothstep(0.0, fw, d)) * f);
hot = max(hot, exp(-max(d, 0.0) / 0.22) * f * (1.0 + 1.20 * s));
hal = max(hal, exp(-max(d, 0.0) / 0.45) * f);
head = x + kAdv[c] * saturate(age * 1.8);
x += kAdv[c];
}
return float4(ink, hot, hal, head);
}
float4 main(VSOut i) : SV_Target
{
float2 uv = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
uv.x *= gTime.w;
// Derivatives before any branch: below this point whole waves get thrown
// away by the bounding box and a gradient taken in there is undefined.
float px = fwidth(uv.x);
// 0.055 was chosen on paper and measured wrong on screen: at 360 lines
// the strokes came out under two pixels and the letterforms turned to
// mush. Small enough to be a signature, big enough to be legible, is
// about twice that.
float sz = 0.115 * max(gTune.y, 0.15);
// 0.16 of the glyph box is not a monoline, it is a marker pen: adjacent
// strokes merged and every letter turned into a blob. A real monoline
// grotesque sits nearer 7 percent, and at that weight the counters in
// the c, the r and the @ survive.
float w = 0.070; // stroke half width, glyph units
// Bottom left, with a margin. Not centred: centred type is a title card,
// and this is meant to be found rather than presented.
//
// TITLE SAFE. The bottom of the PICTURE is not the bottom of the frame:
// the outro closes a letterbox over this shot, and bars of b hide
// everything below y = -1 + 2b. Placed at a fixed -0.62 the second line
// sat at 0.896 in screen uv against a matte cutting at 0.872, so the
// author's own email address was sliced through the middle. Deriving the
// position from the matte instead of from a constant means the type
// stays legible whatever the edit does to the aspect ratio.
float bottom = -1.0 + gTune.w * 2.0;
// o0 is the FIRST line, so it clears the edge by the margin, plus the
// second line's descender, plus the line spacing.
float2 o0 = float2(-gTime.w + 0.20, bottom + 0.10 + sz * (0.22 + 1.5));
float2 o1 = o0 - float2(0.0, sz * 1.5);
// ---- bounding box -----------------------------------------------------
// Seventeen glyphs were being evaluated at every pixel of a 1920x1080
// frame to draw two words in one corner. Ninety-odd percent of the frame
// is nowhere near the type; skipping it there is what pays for the
// second and third light terms below. The window is smooth to the edge
// so the halation cannot leave a rectangle behind it.
float2 imin = float2(o1.x - 0.30 * sz, o1.y - 0.42 * sz);
float2 imax = float2(o1.x + 6.25 * sz, o0.y + 1.00 * sz);
// The margin is not slack, it is the only thing standing between the
// halation and a visible rectangle: the window has to finish its work
// out where the glow is already under the dither floor, or the place it
// cuts reads as a straight edge in the dark.
float marg = 2.00 * sz;
float2 dd = max(imin - uv, uv - imax);
float e = max(max(dd.x, dd.y), 0.0);
if (e > marg) return float4(0.0, 0.0, 0.0, 1.0);
float win = 1.0 - smoothstep(marg * 0.55, marg, e);
// ---- the reveal -------------------------------------------------------
// Eleven glyphs a second: fast enough that it is a signature being
// written and not a crawl, slow enough that you can read it happening.
// The first line clears in nine tenths of a second, the address is down
// by two, and the rest of the shot is the caret blinking on it.
float rate = 11.0 * max(gTune.x, 0.20);
float t = gTime.x - 0.26; // let the dissolve land first
float lead = (gTune.z < 0.5) ? 9.0 : 0.0;// seven slots of line, two of pause
float p0 = t * rate;
float p1 = t * rate - lead;
// one virtual scanline of tracking error, so the type sits IN the signal
// rather than on top of it. Tenths of a pixel - it must never be legible
// as a wobble, only as the picture not being perfectly still.
float2 q = uv;
q.x += 0.0009 * sin(uv.y * 88.0 + gTime.x * 3.7) * (0.45 + gSync.x);
float fw = px * 1.5 / sz; // one pixel, in glyph units
float4 L0 = float4(0, 0, 0, 0), L1;
if (gTune.z < 0.5) L0 = drawLine((q - o0) / sz, 0, 7, p0, fw, w);
L1 = drawLine((q - o1) / sz, 7, 10, p1, fw, w);
float ink = max(L0.x, L1.x);
float hot = max(L0.y, L1.y);
float hal = max(L0.z, L1.z);
// ---- the caret --------------------------------------------------------
// It leads the writing, drops to the second line at the break, and once
// the address is down it stays behind it and blinks at one hertz. A
// secondary element with its own clock, which is what stops the last
// second of a held shot from being a still.
bool onSecond = (p1 > 0.0) || (gTune.z >= 0.5);
float2 co = onSecond ? o1 : o0;
float ch = onSecond ? L1.w : L0.w;
float cp = onSecond ? p1 : p0;
float done = saturate((p1 - 10.0) * 1.5);
// solid while it is writing, blinking once it has nothing left to write
float blink = lerp(1.0, smoothstep(-0.22, 0.22, cos(gTime.x * 6.28)), done);
// and it only exists at all once the first character has landed
float cOn = saturate(cp * 2.0) * blink;
float2 cq = (q - co) / sz - float2(ch + 0.13, 0.0);
float cd = sdSeg(cq, float2(0.0, -0.02), float2(0.0, 0.60)) - w * 0.85;
ink = max(ink, (1.0 - smoothstep(0.0, fw, cd)) * cOn * 0.85);
hot = max(hot, exp(-max(cd, 0.0) / 0.22) * cOn * 0.60);
// ---- the row the beam is writing --------------------------------------
// A tube does not draw a letter, it draws a line and turns the beam on
// in the middle of it. So the row under the active text carries a little
// warmth, brightest just after a character lands, and it decays once the
// line is finished. It has to hug the x-height: at a lazier falloff it
// stops being a scan line and becomes a lit rectangle behind the type,
// which is a caption box, which is the one thing this must not look like.
float2 bp = (q - co) / sz;
float bx = max(max(-0.20 - bp.x, bp.x - ch - 0.20), 0.0);
float bt = saturate(cp * 2.0) * (0.30 + 0.70 * exp(-max(cp - 10.0, 0.0) * 1.2));
float band = 0.030 * bt
* exp(-abs(bp.y - 0.29) / 0.17) * exp(-bx / 0.30)
* (1.0 + 0.80 * exp(-frac(max(cp, 0.0)) * 6.0));
// ---- phosphor ---------------------------------------------------------
// Three terms, not one: the beam spot tight around the stroke, the
// halation that scatters through the glass and puts a soft field around
// the whole word, and the ink itself. The glow used to be doing the job
// of the first two at once, which is why it read as a second, fatter
// stroke instead of as light. Only the two GLOW terms move with the
// music - the ink never does, so nothing here can flash.
float lift = 1.0 + 0.34 * gVoice.z + 0.22 * gSync.w;
float3 col = float3(0.68, 0.94, 0.72)
* (ink + (hot * 0.18 + hal * 0.020 + band) * lift) * win;
return float4(col * gTime.z, 1.0);
}

483
fx/voidshot.hlsl Normal file
View file

@ -0,0 +1,483 @@
// Shot 30 - MONOLITH IN THE WHITE VOID.
//
// The contrast shot. Everything else in this demo is dark, so one shot is
// almost entirely white, and the subject is a black shape standing in it.
// The dither in the post pass does most of the work here: against a flat
// white field the Bayer pattern is the texture, which is exactly the
// Marathon loading screen look.
//
// It appears ONCE, at bar 82, on the loudest flash cut in the piece: a stab
// on beat one and then 1.36 s of real silence. So it was never a repetition
// problem, it was a nothing-happens problem - a rectangle standing still for
// two seconds, seen through a flash it did not use.
//
// What it does now is the only thing that moment wants: the stab HITS it.
// The monolith comes apart under the white of the flash, and by the time
// the flash has decayed the pieces are already slowing. They decelerate
// asymptotically, so by the middle of the shot everything has stopped dead
// and hangs in the air, unfallen, for the whole of the silence. The picture
// stops when the music does - it just stops somewhere the eye has never
// seen it stop before. The base stays planted, so it still reads as the
// monolith and not as a pile of boxes.
//
// gTune.x monolith lean, and which way the break throws
// gTune.y how far the horizon has been pushed back
// gTune.z fracture the shot STARTS at (0 = enters whole, 1 = already open)
// gTune.w strike delay in seconds (0 = struck on the cut, which is the cut
// this shot is written against)
//
// gSync.w a tremor in the pieces that dies out with the sound itself
// gVoice.y the solo, riding the dust ring the strike throws along the floor
cbuffer Scene : register(b0)
{
float4 gTime;
float4 gCam;
float4 gDir;
float4 gTune;
/* What the music is doing at this exact sample. The three bands
each drive a different SCALE of thing - low for big slow shapes,
mid for mid-sized ones, high for fine texture - so the image ends
up with the same frequency structure as the music instead of just
reacting to it. */
float4 gSync; // x low, y mid, z high, w master peak
float4 gVoice; // x guitar, y solo, z organ, w hat
};
struct VSOut
{
float4 pos : SV_Position;
float2 uv : TEXCOORD0;
};
#define NSLAB 9
#define NCHIP 26
// The sun sits BEHIND the monolith relative to the camera and low, so the
// shadow runs forward out of the frame towards the viewer instead of hiding
// behind the shape. On a white floor the shadow is the only other graphic
// element in the picture; it should not be pointing away from us.
static const float3 SUN = float3(-0.4870, 0.7190, 0.4953); // normalised
// Where the monolith is cut. Deliberately uneven - equal bands read as a
// stack of pancakes, uneven ones read as something that broke.
static const float kEdge[NSLAB + 1] = {
0.000, 0.082, 0.171, 0.268, 0.352, 0.463, 0.576, 0.701, 0.848, 1.000
};
// Three more of them, standing out in the haze. They are almost entirely
// fogged out - a tenth of a stop each - and that is the point: they give
// the void a scale, so the white is a distance and not a backdrop.
static const float4 kFar[3] = {
float4(-46.0, 70.0, 2.30, 20.0), // x, z, half width, height
float4( 74.0, 138.0, 3.40, 34.0),
float4(-96.0, 232.0, 2.90, 22.0)
};
static float4 gSA[NSLAB]; // xyz: piece centre in monolith space, w: half height
static float4 gSB[NSLAB]; // cos/sin of its two tumble angles
static float3 gBmin, gBmax; // world box that contains every piece
static float3 gCmin, gCmax; // and one that contains every chip
static float gLeanS, gLeanC;
static float gA; // how far the break has got. 0 whole, 1 open
float sdBox(float3 p, float3 b)
{
float3 q = abs(p) - b;
return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);
}
// Slab test against an axis aligned box. Used to BOUND the raymarch rather
// than to draw anything: the pieces occupy a small part of the frame, so
// most pixels never take a march step at all, and the shader ends up
// cheaper than the one box version it replaces despite carrying nine.
bool hitAABB(float3 o, float3 d, float3 bn, float3 bx, out float t0, out float t1)
{
float3 inv = 1.0 / (d + 1e-9);
float3 a = (bn - o) * inv;
float3 b = (bx - o) * inv;
float3 lo = min(a, b), hi = max(a, b);
t0 = max(max(lo.x, lo.y), lo.z);
t1 = min(min(hi.x, hi.y), hi.z);
return t1 > max(t0, 0.0);
}
/* ---- the break -------------------------------------------------------
Everything about a piece depends only on constants and on uniforms, so
it is solved once per pixel here and the marcher just reads it. Doing it
inside map() would put nine normalize() and eighteen sincos inside a
sixty step loop, which is the difference between a shot and a stall. */
void setupSlabs(float A, float trem, float ts)
{
gLeanS = sin(gTune.x * 0.14);
gLeanC = cos(gTune.x * 0.14);
[unroll] for (int k = 0; k < NSLAB; k++) {
float e0 = kEdge[k], e1 = kEdge[k + 1];
float cy = (e0 + e1) * 4.6 - 4.6; // band centre, monolith space
float hy = (e1 - e0) * 4.6; // and its half height
// R3 low discrepancy, so nine pieces are well spread without a
// hash and without a table to maintain.
float3 r = frac(float3(0.7548776, 0.5698402, 0.3819660) * (float(k) + 2.0));
// Thrown outward and slightly up. The lean biases the throw, so a
// monolith that leans is one that comes apart the way it leans.
float3 dir = normalize(float3((r.x - 0.5) * 2.00 + 0.55 * gTune.x,
(r.y - 0.18) * 0.80,
(r.z - 0.5) * 2.00) + float3(0.0, 0.02, 0.0));
// The bottom of the shape barely moves and does not turn AT ALL.
// What is left standing is what keeps this readable as the monolith
// rather than as a pile of boxes - and a stump that spun in place
// would both look wrong and swing geometry down through the floor,
// so the hold gates the tumble exactly as it gates the throw.
float hold = smoothstep(-0.02, 0.30, e0);
float spd = (0.55 + 2.35 * r.z) * hold;
// A tremor that lives and dies with the sound, not with the clock.
// Three centimetres of it - a vibration, never a flash.
float wob = sin(ts * 26.0 + float(k) * 2.1) * trem * 0.035 * hold;
float3 c = float3(0.0, cy, 0.0) + dir * (A * spd + wob);
float a = (r.x - 0.5) * 2.10 * A * hold;
float b = (r.y - 0.5) * 1.55 * A * hold;
gSA[k] = float4(c, hy);
gSB[k] = float4(cos(a), sin(a), cos(b), sin(b));
}
/* The bound is fitted to the exact swept extent of the nine oriented
pieces with about fifteen percent to spare, because it is doing two
jobs at once: a bound that clips is geometry that silently vanishes,
and a bound that is loose is march steps spent on empty white. */
gBmin = float3(-(1.55 + 2.60 * A), -0.50, -(1.80 + 1.95 * A));
gBmax = float3( 1.55 + 2.60 * A, 9.60 + 1.70 * A, 1.80 + 1.95 * A);
// The chips throw much further than the pieces do, and twenty six
// analytic spheres is the one cost this shader pays on every single
// pixel. Same trick: bound them, and the white two thirds of the frame
// stops paying for debris it cannot see.
gCmin = float3(-(1.20 + 6.60 * A), 0.50, -(1.60 + 5.70 * A));
gCmax = float3( 1.20 + 6.60 * A, 9.40 + 5.50 * A, 1.60 + 5.70 * A);
}
// Just the pieces. The floor is solved analytically, so it is not in here.
float mapObj(float3 p)
{
float3 m = p - float3(0.0, 4.6, 0.0);
m.xy = float2(m.x * gLeanC - m.y * gLeanS, m.x * gLeanS + m.y * gLeanC);
float d = 1e9;
[unroll] for (int k = 0; k < NSLAB; k++) {
float3 q = m - gSA[k].xyz;
float4 R = gSB[k];
q.xy = float2(q.x * R.x + q.y * R.y, -q.x * R.y + q.y * R.x);
q.yz = float2(q.y * R.z + q.z * R.w, -q.y * R.w + q.z * R.z);
d = min(d, sdBox(q, float3(0.608, gSA[k].w - 0.012, 1.538)) - 0.012);
}
return d;
}
float3 objNormal(float3 p)
{
const float2 e = float2(1.0, -1.0) * 0.0022;
return normalize(e.xyy * mapObj(p + e.xyy) + e.yyx * mapObj(p + e.yyx) +
e.yxy * mapObj(p + e.yxy) + e.xxx * mapObj(p + e.xxx));
}
/* Is this surface one of the faces the strike MADE? The monolith is
polished black on the four faces it was born with; a fracture is raw.
Finding which piece we are on costs one extra pass of nine boxes at a
single point, and it buys the whole reason to break something on camera -
you have to be able to see the inside.
The test is on the normal turned back into the piece's own frame, not on
the position: a cut face is the one whose local normal is +-y. Testing
position instead wraps a grey stripe around the top edge of every side
face, which reads as a bug rather than as an exposed section. */
float cutFace(float3 p, float3 n)
{
float3 m = p - float3(0.0, 4.6, 0.0);
m.xy = float2(m.x * gLeanC - m.y * gLeanS, m.x * gLeanS + m.y * gLeanC);
float3 nl0 = float3(n.x * gLeanC - n.y * gLeanS, n.x * gLeanS + n.y * gLeanC, n.z);
float best = 1e9, ny = 0.0;
[unroll] for (int k = 0; k < NSLAB; k++) {
float4 R = gSB[k];
float3 q = m - gSA[k].xyz;
q.xy = float2(q.x * R.x + q.y * R.y, -q.x * R.y + q.y * R.x);
q.yz = float2(q.y * R.z + q.z * R.w, -q.y * R.w + q.z * R.z);
float d = sdBox(q, float3(0.608, max(gSA[k].w - 0.012, 0.02), 1.538)) - 0.012;
if (d < best) {
best = d;
float2 t = float2(nl0.x * R.x + nl0.y * R.y, -nl0.x * R.y + nl0.y * R.x);
ny = t.y * R.z + nl0.z * R.w;
}
}
return smoothstep(0.55, 0.86, abs(ny));
}
// The fine stuff the strike threw off. Analytic spheres rather than SDF
// geometry: at this distance a chip is three to ten pixels across, so a
// silhouette is all of it, and twenty six of them cost less than one more
// box inside the march.
float4 chipAt(int k)
{
float3 r = frac(float3(0.7548776, 0.5698402, 0.3819660) * (float(k) + 5.0));
float3 r2 = frac(float3(0.8191725, 0.6710436, 0.5497004) * (float(k) + 11.0));
float3 rest = float3((r.x - 0.5) * 1.10, (r.y - 0.5) * 9.00, (r.z - 0.5) * 2.70);
float3 dir = normalize(float3(rest.x * 1.70 + (r2.x - 0.5) * 1.90,
(r2.y - 0.15) * 1.20,
rest.z * 0.90 + (r2.z - 0.5) * 1.90)
+ float3(0.0, 0.03, 0.0));
// Same rule as the pieces: what is low down stays where it was.
float3 lp = rest + dir * (gA * (1.6 + 6.4 * r2.x)
* smoothstep(-3.6, -1.8, rest.y));
float3 w = float3(lp.x * gLeanC + lp.y * gLeanS,
4.6 - lp.x * gLeanS + lp.y * gLeanC,
lp.z);
float rad = 0.035 + 0.095 * r.z * r.z;
w.y = max(w.y, rad * 0.92); // nothing sinks into the floor
return float4(w, rad);
}
float shadowSlabs(float3 o, float3 d)
{
float t0, t1;
if (!hitAABB(o, d, gBmin, gBmax, t0, t1)) return 1.0;
float t = max(t0, 0.05), te = min(t1, 90.0), res = 1.0;
[loop] for (int i = 0; i < 28; i++) {
if (t > te) break;
float h = mapObj(o + d * t);
if (h < 0.0022) return 0.0;
res = min(res, 7.5 * h / t);
t += clamp(h, 0.05, 2.0);
}
return saturate(res);
}
// Twenty six little shadows scattered across a white floor. This is most of
// what sells the freeze: without them the chips are stickers.
float chipShade(float2 g)
{
float s = 1.0;
[unroll] for (int k = 0; k < NCHIP; k++) {
float4 c = chipAt(k);
float lift = max(c.y, 0.0) / SUN.y;
float2 gp = c.xz - SUN.xz * lift;
float rad = c.w * (1.7 + 0.55 * lift);
float dd = length(g - gp);
s *= 1.0 - 0.55 * (1.0 - smoothstep(rad * 0.25, rad, dd));
}
return s;
}
// Ambient contact under the hanging pieces. The sun shadow is directional
// and long; this is the short dark bloom directly beneath a mass, and it is
// the difference between a piece that hangs and a piece that was pasted on.
float slabContact(float2 g)
{
float o = 1.0;
[unroll] for (int k = 0; k < NSLAB; k++) {
float3 lp = gSA[k].xyz;
float2 w = float2(lp.x * gLeanC + lp.y * gLeanS, lp.z);
float h = max(4.6 - lp.x * gLeanS + lp.y * gLeanC, 0.35);
float rad = 1.5 + h * 0.42;
o *= 1.0 - 0.30 * exp(-dot(g - w, g - w) / (rad * rad)) / (1.0 + h * 0.22);
}
return o;
}
float4 main(VSOut i) : SV_Target
{
float2 uv = float2(i.uv.x * 2.0 - 1.0, 1.0 - i.uv.y * 2.0);
// y is FLIPPED here on purpose. The fullscreen triangle emits
// uv.y = 0 at the top of the screen, so i.uv*2-1 gives -1 up
// there and the top of the frame ended up looking DOWNWARD -
// the cathedral vault springs at y=+12 and was rendering in the
// lower half, the monolith hung from the ceiling.
uv.x *= gTime.w;
float3 fw = normalize(gDir.xyz);
float3 rt = normalize(cross(float3(0.0, 1.0, 0.0), fw));
float3 up = cross(fw, rt);
float cr = cos(gDir.w), sr = sin(gDir.w);
float3 ro = gCam.xyz;
float3 rd = normalize(fw + (uv.x * (rt * cr + up * sr) +
uv.y * (up * cr - rt * sr)) * gCam.w);
/* ---- the strike clock ----------------------------------------------
1 - exp(-kt) is the whole idea. Velocity is highest at the instant of
the hit and decays from there, so the break is violent under the
flash and has visibly stopped by the time the silence is half over.
The tiny linear term on the end means it never becomes a literal
still frame - the pieces creep about six centimetres across the rest
of the shot, which you do not see so much as fail to be bored by. */
float ts = max(gTime.x - gTune.w, 0.0);
float A = saturate(gTune.z) + (1.0 - exp(-ts * 3.4)) + ts * 0.030;
gA = min(A, 1.35);
setupSlabs(gA, saturate(gSync.w), ts);
// The void. Not pure white at the top, or there is nothing for the
// dither to bite on. The last term is a one percent swell across the
// whole field - far too small to see as a gradient, just enough to
// walk the dither threshold so the white is alive rather than dead.
float3 sky = lerp(float3(0.972, 0.972, 0.962),
float3(0.780, 0.800, 0.840),
saturate(rd.y * 1.6 + 0.10));
sky += 0.009 * sin(rd.x * 2.7 + gTime.x * 0.30) * sin(rd.y * 3.3 - gTime.x * 0.21);
float3 col = sky;
float tScene = 1e9;
// ---- the floor, solved rather than marched ----
float tG = (rd.y < -1e-5) ? (-ro.y / rd.y) : 1e9;
if (tG < 0.0) tG = 1e9;
// ---- the pieces, marched only inside their own bound ----
float tObj = 1e9;
{
float t0, t1;
if (hitAABB(ro, rd, gBmin, gBmax, t0, t1)) {
float t = max(t0, 0.05);
float te = min(t1, min(tG, 300.0));
[loop] for (int k = 0; k < 60; k++) {
if (t > te) break;
float h = mapObj(ro + rd * t);
if (h < 0.0010 * t) { tObj = t; break; }
t += h;
}
}
}
if (tObj < 1e8) {
float3 p = ro + rd * tObj;
float3 n = objNormal(p);
float sh = shadowSlabs(p + n * 0.02, SUN);
float di = saturate(dot(n, SUN));
// Polished black where the shape was born, raw grey where the stab
// opened it. The grain is coarse on purpose: it has to survive a
// seven step quantiser to be a texture rather than a smudge.
float cut = cutFace(p, n);
float3 gp = floor(p * 21.0);
float gr = frac(sin(dot(gp, float3(12.9898, 78.233, 37.719))) * 43758.5453);
float3 albedo = lerp(float3(0.030, 0.032, 0.038),
float3(0.400, 0.394, 0.380) * (0.72 + 0.50 * gr),
cut);
// The void is a lit dome, so upward faces pick up a lot of it.
float amb = 0.30 + 0.42 * saturate(n.y * 0.5 + 0.5);
col = albedo * (amb + 0.95 * di * sh);
// A white world puts a hard rim on a black edge. On the quantiser
// this becomes a one pixel outline, which is exactly the look.
float fres = pow(1.0 - saturate(dot(n, -rd)), 4.0);
col += (0.13 + 0.10 * cut) * fres * float3(0.95, 0.96, 1.00);
tScene = tObj;
}
else if (tG < 400.0) {
float3 p = float3(ro.x + rd.x * tG, 0.0, ro.z + rd.z * tG);
float2 g = p.xz;
float r = length(g);
// Every chip shadow lands inside r = 18.8 and every contact bloom
// inside r = 22, measured against the throw. Past that the floor is
// clean white and there is nothing to compute.
float sh = shadowSlabs(p + float3(0.0, 0.015, 0.0), SUN);
if (r < 20.0) sh = min(sh, chipShade(g));
/* The ground opened where it was hit. The crack FRONT races out on
its own envelope and then halts, so for the first third of a
second there is something travelling across the floor even after
the pieces have slowed - a second thing with its own timing,
which is what keeps a held shot from being one idea. */
float front = 2.5 + 58.0 * (1.0 - exp(-ts * 4.6));
float a = atan2(g.y, g.x);
float u = a * (9.0 / 6.28318) + sin(r * 0.21) * 0.55
+ sin(r * 0.065 + 1.7) * 0.85;
float arc = abs(frac(u) - 0.5) * r * 0.698; // ~world width
float crack = 1.0 - smoothstep(0.045, 0.24 + r * 0.02, arc);
float ru = r * 0.155 + sin(a * 5.0) * 0.22 + sin(a * 2.0 + 0.9) * 0.15;
float ring = abs(frac(ru) - 0.5) * 6.45;
crack = max(crack, (1.0 - smoothstep(0.10, 0.42 + r * 0.02, ring)) * 0.55);
crack *= 1.0 - smoothstep(front * 0.80, front, r); // the front
crack *= smoothstep(0.6, 2.2, r); // not under the stump
crack *= saturate(1.0 - r / 150.0);
// Keep the fracture front subordinate to the standing silhouette.
// Near-black rings used to compete with every suspended slab.
float3 albedo = lerp(float3(0.940, 0.940, 0.930),
float3(0.085, 0.088, 0.095), crack * 0.32);
// Dust swept out along the front. Written base + k*voice so the
// floor never drops out from under the ring - this is a local
// eleven percent smudge, never a frame that changes brightness.
float dust = exp(-abs(r - front) * 0.30);
albedo *= 1.0 - 0.11 * dust * (0.55 + 0.45 * saturate(gVoice.y));
if (r < 22.0) albedo *= slabContact(g);
col = albedo * (0.20 + 0.90 * SUN.y * sh);
tScene = tG;
}
// ---- the chips ----
{
float ct0, ct1;
if (hitAABB(ro, rd, gCmin, gCmax, ct0, ct1) && ct0 < tScene) {
[unroll] for (int c = 0; c < NCHIP; c++) {
float4 ch = chipAt(c);
float3 oc = ro - ch.xyz;
float b = dot(oc, rd);
float cc = dot(oc, oc) - ch.w * ch.w;
float hh = b * b - cc;
if (hh > 0.0) {
float tt = -b - sqrt(hh);
if (tt > 0.05 && tt < tScene) {
float3 cn = (ro + rd * tt - ch.xyz) / ch.w;
float cd = saturate(dot(cn, SUN));
col = float3(0.045, 0.047, 0.053) * (0.34 + 0.90 * cd)
+ 0.10 * pow(1.0 - saturate(dot(cn, -rd)), 4.0);
tScene = tt;
}
}
}
}
}
// ---- the others, standing out in the haze ----
[unroll] for (int f = 0; f < 3; f++) {
float4 F = kFar[f];
float t0, t1;
if (hitAABB(ro, rd, float3(F.x - F.z, 0.0, F.y - F.z * 2.3),
float3(F.x + F.z, F.w, F.y + F.z * 2.3), t0, t1)
&& t0 > 0.0 && t0 < tScene) {
col = float3(0.055, 0.058, 0.066);
tScene = t0;
}
}
// Aerial haze back into the void, so the ground has no visible end.
// Fogging towards the sky rather than towards a constant is what makes
// the horizon a seam you cannot find.
if (tScene < 1e8) {
// Clear foreground air preserves black faces through the bleach
// quantiser. The old zero-distance haze lifted the subject about
// 0.4 towards white; the remote monoliths still dissolve normally.
float fog = 1.0 - exp(-max(tScene - 18.0, 0.0) * 0.021);
col = lerp(col, sky, fog * (0.55 + 0.45 * gTune.y));
}
return float4(col * gTime.z, 1.0);
}

2594
gfx.c Normal file

File diff suppressed because it is too large Load diff

7
makevideo_gpu.bat Normal file
View file

@ -0,0 +1,7 @@
@echo off
setlocal
cd /d "%~dp0"
rem Always rebuild: an existing video renderer may embed stale shaders.
call buildgfx.bat video || exit /b 1
python tools\export_video.py
exit /b %errorlevel%

526
shots.h Normal file
View file

@ -0,0 +1,526 @@
/* ==========================================================================
T H E E D I T
--------------------------------------------------------------------------
The old demo had one continuous camera integral and decorated it. That is
why 85% of it was a single shot: there was nowhere for a cut to live.
Here a shot is data. Once that is true, jump cuts, match cuts, holds,
reverses, whip pans and aspect changes are all just fields in a row, and
the edit becomes something you write rather than something that falls out
of a sine wave.
Time is addressed in ROWS - one sixteenth note - never in seconds, so no
cut can land off the music:
row = 5000 samples @ 44100 = 0.113378 s
beat = 4 rows = 0.453515 s
bar = 16 rows = 1.814059 s
pattern = 32 rows = 3.628118 s
song = 96 bars = 1536 rows = 174.15 s (132.30 BPM)
`eye` is where the camera is. `at` is ALWAYS a point in the world that it
looks at - never a direction. Motion behaviours take their axis from
(at - eye), so aiming a shot is one idea rather than two.
FIXED 48-ORDER MUSIC MAP (32 rows/order):
orders 0-1 rows 0-63 intro: Commodore tube, then CRTKAFA (7.256 s)
orders 2-7 rows 64-255 synthwave
orders 8-11 rows 256-383 single metal verse
orders 12-15 rows 384-511 single chorus
orders 16-39 rows 512-1279 evolving solo (87.075 s)
orders 40-45 rows 1280-1471 arrival
orders 46-47 rows 1472-1535 outro
All runtime scenes are spatial. Legacy shader IDs remain stable; LOGO is
appended for the parent's shader registration. Its shader owns the actual
flypast and tune interpretation; this edit supplies one 32-row slot.
No flash transitions, stutter or matte pumping. Two isolated one-beat
bursts join phrases; other shots last two to four bars except the final
three-beat solo pickup. Reactor camera distances stay outside radius six.
========================================================================== */
#define ROWS_PER_BEAT 4
#define ROWS_PER_BAR 16
#define SONG_ROWS 1536
/* BAR(n) is one-based, the way a musician counts. */
#define BAR(n) (((n) - 1) * ROWS_PER_BAR)
#define BEAT(n, b) (BAR(n) + ((b) - 1) * ROWS_PER_BEAT)
#define ROWAT(n, b, r) (BEAT(n, b) + (r))
/* ---- which pixel shader draws this shot -------------------------------- */
enum {
SC_EYE = 0, /* macro cat eye */
SC_CATHEDRAL, /* the organ hall */
SC_VOID, /* monolith in the white void */
SC_HORIZON, /* synthwave: grid, banded sun, ridge, slabs */
SC_KALEIDO, /* kaleidoscopic IFS tunnel - the acid trip. */
/* travels along its axis only: a crane or a track */
/* walks the camera out of the tunnel and the frame */
/* goes black. */
SC_FRAMES, /* flat 2D design frames: rules, blocks, big type */
SC_PLINTH, /* vaporwave plinth room lit by a wall of CRTs */
SC_DRIVE, /* the road at night, from inside the car */
SC_CORRIDOR, /* the liminal corridor that never arrives */
SC_POWEROFF, /* the tube collapsing to a line, then a point */
SC_BURST, /* streaks past the camera at the fastest passage */
SC_C64, /* the original boot text inside a spatial CRT */
SC_SIGNOFF, /* crt.fyi and hi@crt.fyi, small, once */
SC_LOGO, /* one spatial CRTKAFA flypast, intro only */
SC_REACTOR, /* finite porous core, broken rings and shards */
SC_ORBITAL, /* gas giant, eclipse and luminous filaments */
SC_COUNT
};
/* ---- what the camera does ---------------------------------------------- */
enum {
CAM_HOLD = 0, /* completely still. the demo has never had one of these */
CAM_PUSH, /* forward, towards `at` */
CAM_PULL, /* backwards, away from it - a reveal */
CAM_TRACK, /* lateral dolly across the look axis */
CAM_CRANE, /* vertical */
CAM_ORBIT, /* around `at` */
CAM_WHIP, /* the look sweeps fast across the shot */
CAM_DRIFT /* held, but breathing */
};
/* ---- what, if anything, is IN the shot --------------------------------- */
enum {
ACT_NONE = 0,
ACT_CAT_RUN, /* the black cat, running. 24 baked frames */
ACT_CAT_STILL, /* the same mesh, held on one frame */
ACT_CAT_SWARM, /* several of them, instanced across the frame */
ACT_TARDIS, /* single-frame blue-box callback */
ACT_SPIN_CAT /* one short spinning meme cut */
};
/* ==========================================================================
T H E G R A D E
--------------------------------------------------------------------------
The CRT pass quantises luminance into a four-stop ramp, so the ramp is
what the picture is built out of: every pixel is re-coloured through it,
and then the scene's own hue is mixed back on top by hueKeep - which is
why the stops are felt everywhere without flattening the scenes to four
literal colours. Changing them is still a far stronger instrument than
multiplying the output by a tint, and it makes the step count the single biggest lever in the
renderer: at seven steps the picture is a woodcut, at twelve it is nearly
continuous. Both were hardcoded until now, which is why 174 seconds of
demo all looked like the same afternoon.
A grade belongs to the SECTION, not to the shot. The music is what changes
colour; the camera just happens to be pointing somewhere while it does.
So this is a schedule in rows, exactly like the arrangement it follows,
and not a field in the shot table.
========================================================================== */
enum { GR_COLD = 0, GR_WARM, GR_NEON, GR_BLEACH, GR_PHOSPHOR, GR_COUNT };
typedef struct {
float ramp[4][4]; /* the four stops. this is the whole palette */
/* How much of the SOURCE hue is allowed back on top of the ramp. Read it
backwards from how it sounds: 1.0 means the scene's own colour wins and
the palette is barely felt, 0.0 means the frame is made of nothing but
the four stops. So the grades that exist to be noticed sit low. */
float hueKeep;
float steps; /* quantiser levels */
float dither;
float exposure;
} Grade;
static const Grade g_grades[GR_COUNT] = {
/* COLD - the metal, the breakdown, the corridors. A blue black, neutral
midtones, a slightly warm white. This is the look the whole demo had. */
{ { {0.030f,0.034f,0.048f,0.0f}, {0.150f,0.180f,0.235f,0.0f},
{0.520f,0.545f,0.585f,0.0f}, {0.980f,0.965f,0.940f,0.0f} },
0.62f, 10.0f, 0.85f, 1.00f },
/* WARM - the turn, the chorus, and the arrival: everywhere the music is
at its biggest. Amber shadows, and the ramp opens up a step. */
{ { {0.042f,0.031f,0.030f,0.0f}, {0.205f,0.150f,0.120f,0.0f},
{0.600f,0.530f,0.430f,0.0f}, {1.000f,0.960f,0.880f,0.0f} },
0.50f, 11.0f, 0.82f, 1.05f },
/* NEON - the synthwave half and the solo. A magenta-leaning shadow and a
cyan white is most of the genre in two numbers. Measured at hueKeep
0.78 this came out plain red: the horizon and the drive are both lit
by an orange sun, and at that setting their own hue simply overrode
the palette. Half is where the magenta survives contact with them. */
{ { {0.048f,0.026f,0.062f,0.0f}, {0.210f,0.115f,0.250f,0.0f},
{0.510f,0.470f,0.690f,0.0f}, {0.890f,0.980f,1.000f,0.0f} },
0.50f, 12.0f, 0.90f, 1.06f },
/* BLEACH - the void, and the design frames. Almost no shadow at all and
few enough steps that the dither stops being texture and becomes the
subject. Two bars of this is why the solo lands. */
{ { {0.125f,0.128f,0.138f,0.0f}, {0.430f,0.435f,0.450f,0.0f},
{0.765f,0.770f,0.780f,0.0f}, {1.000f,1.000f,0.995f,0.0f} },
0.35f, 7.0f, 1.00f, 1.00f },
/* PHOSPHOR - the eye, the C64 screen, the power-off, the sign-off. One
hue and eight steps: it should read as a tube, not as a render. */
{ { {0.018f,0.030f,0.022f,0.0f}, {0.085f,0.225f,0.115f,0.0f},
{0.350f,0.645f,0.395f,0.0f}, {0.870f,1.000f,0.895f,0.0f} },
0.30f, 8.0f, 0.95f, 1.02f },
};
/* Section keys follow the fixed 48-order score, including solo chapters. */
typedef struct { short row; unsigned char grade; } GradeKey;
static const GradeKey g_gradeKeys[] = {
{ BAR(1), GR_COLD }, /* orders 0-1: logo */
{ BAR(5), GR_NEON }, /* orders 2-7: synthwave */
{ BAR(17), GR_COLD }, /* orders 8-11: single verse */
{ BAR(25), GR_WARM }, /* orders 12-15: single chorus */
{ BAR(33), GR_NEON }, /* solo I: space, clean lead */
{ BAR(45), GR_COLD }, /* solo II: angular, low architecture */
{ BAR(57), GR_WARM }, /* solo III: expansion and ascent */
{ BAR(66), GR_PHOSPHOR }, /* three-bar green iris climax */
{ BAR(69), GR_NEON }, /* solo IV: broad release */
{ BAR(81), GR_WARM }, /* orders 40-45: arrival */
{ BAR(93), GR_COLD }, /* orders 46-47: withdrawal */
};
#define GRADE_KEYS ((int)(sizeof(g_gradeKeys) / sizeof(g_gradeKeys[0])))
/* Some scenes carry their own look wherever they appear. A green cat eye in
the middle of the synthwave section is a callback rather than a mistake,
and a C64 screen graded warm would simply be wrong. GR_FOLLOW means "take
the section's grade", which is what most scenes do. */
#define GR_FOLLOW 0xFF
static const unsigned char g_sceneGrade[SC_COUNT] = {
GR_PHOSPHOR, /* SC_EYE */
GR_FOLLOW, /* SC_CATHEDRAL */
GR_BLEACH, /* SC_VOID */
GR_FOLLOW, /* SC_HORIZON */
GR_FOLLOW, /* SC_KALEIDO */
GR_BLEACH, /* SC_FRAMES */
GR_FOLLOW, /* SC_PLINTH */
GR_FOLLOW, /* SC_DRIVE */
GR_FOLLOW, /* SC_CORRIDOR */
GR_PHOSPHOR, /* SC_POWEROFF */
GR_FOLLOW, /* SC_BURST */
GR_PHOSPHOR, /* SC_C64 */
GR_PHOSPHOR, /* SC_SIGNOFF */
GR_FOLLOW, /* SC_LOGO */
GR_FOLLOW, /* SC_REACTOR */
GR_FOLLOW /* SC_ORBITAL */
};
/* ==========================================================================
T H E M A T T E
--------------------------------------------------------------------------
Full frame throughout. The ending withdraws through 3D space; the parent
renderer supplies the final darkness fade, without an aspect-ratio cue.
========================================================================== */
typedef struct {
short row; /* when it starts moving */
short rows; /* how long it takes. 0 is instant */
float bars; /* fraction of the height hidden at each edge.
0.128 turns 16:9 into 2.39:1, 0.056 into 2.00:1 */
} MatteKey;
static const MatteKey g_mattes[] = {
{ BAR(1), 0, 0.000f },
};
#define MATTE_KEYS ((int)(sizeof(g_mattes) / sizeof(g_mattes[0])))
static float matteAt(double row)
{
int i, k = 0;
float from, u;
for (i = 0; i < MATTE_KEYS; i++)
if ((double)g_mattes[i].row <= row) k = i;
if (g_mattes[k].rows <= 0) return g_mattes[k].bars;
u = (float)((row - (double)g_mattes[k].row) / (double)g_mattes[k].rows);
if (u >= 1.0f) return g_mattes[k].bars;
if (u < 0.0f) u = 0.0f;
/* The one before it is where we are coming from - and for the first key
that is the LAST one, because the demo loops. The outro closes the
bars to exactly where the cold open starts them, so the wrap is
continuous rather than a snap. */
from = (k > 0) ? g_mattes[k - 1].bars : g_mattes[MATTE_KEYS - 1].bars;
u = u * u * (3.0f - 2.0f * u); /* ease, so it reads as a move */
return from + (g_mattes[k].bars - from) * u;
}
/* ---- how we get INTO this shot ----------------------------------------- */
enum {
TR_CUT = 0, /* hard. the default, and it should be */
TR_FLASH, /* white blown through the cut */
TR_BLACK, /* up from black */
TR_DISSOLVE, /* both shots rendered and crossfaded */
TR_MATCH, /* a hard cut placed so a shape survives it */
TR_WHIPIN /* smeared in - pairs with CAM_WHIP on the shot before */
};
typedef struct {
short start; /* first row of the shot */
unsigned char scene;
unsigned char cam;
unsigned char trans; /* transition INTO this shot */
unsigned char transRows;/* how long that transition lasts, in rows */
float eye[3]; /* where the camera is */
float at[3]; /* the point it looks at */
float speed; /* units per second, or radians per second */
float fov; /* tan(vfov/2) */
float roll;
float tune[4]; /* handed to the scene shader untouched */
/* An actor is a mesh standing in the scene, and it is addressed in the
same language as everything else here: where it starts, where it ends,
and how fast its cycle runs in FRAMES PER ROW. Tying the animation to
the song's row clock rather than to a wall clock is the whole point -
the old demo stepped the cat against wall-clock seconds and it never
once landed on the beat. */
unsigned char actor;
float from[3]; /* world position at the start of the shot */
float to[3]; /* and at the end of it */
float actScale;
float actRate; /* animation frames per row. 3.0 is a lope */
/* STUTTER. The clock the picture reads, quantised to this many rows -
0 is smooth, 1.0 holds each frame for a full sixteenth, 2.0 for an
eighth note. The edit clock underneath it keeps running, so the cut
still lands where it was written; only what is inside the frame
judders.
It has to be COARSER than the motion it quantises or it does nothing
at all, which is a thing you cannot see by reading the table - the
self test measures it per shot.
Nothing here is decoded video, so there is nothing to datamosh and no
frame ring worth carrying: freezing a procedural picture means holding
the time you hand it. Which is also why the actor freezes with the
scene rather than sliding through a held frame - they read the same
clock, so they stop together or not at all. */
float stutter;
} Shot;
/* --------------------------------------------------------------------------
The 48-order spatial edit. Start rows determine actual shot durations.
Cat actors retain four appearances; their from/to paths span the next cut.
Kaleido moves are strictly axial. Plinth paths stay in the centre aisle.
Source shaders, C64 prose and music are frozen by this edit.
-------------------------------------------------------------------------- */
static const Shot g_shots[] = {
/* INTRO: the Commodore tube gets the first bar: short, physical, phosphor-lit
and already inside the 3D world. It is the threshold, not a waiting room. */
{ BAR(1), SC_C64, CAM_PUSH, TR_CUT, 0,
{0.0f, 0.0f, -7.0f}, {0.0f, 0.0f, 0.0f}, 0.35f, 0.58f, 0.0f,
{1.0f, 0.72f, 0.16f, 0.0f} },
/* The spatial CRTKAFA flypast occupies intro bars 3-4.
The mark appears once and is then left behind for the rest of the run. */
{ BAR(3), SC_LOGO, CAM_HOLD, TR_CUT, 0,
{0.0f, 0.0f, -12.0f}, {0.0f, 0.0f, 0.0f}, 0.0f, 0.48f, 0.0f,
{0.0f, 0.0f, 0.0f, 0.0f} },
/* SYNTHWAVE: first a distant TARDIS callback, almost swallowed by the void.
It is there early, but never becomes a mascot or a repeated prop. */
{ BAR(5), SC_BURST, CAM_HOLD, TR_CUT, 0,
{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 10.0f}, 0.0f, 0.6f, 0.0f,
{30.0f, 0.10f, 0.12f, 0.0f},
ACT_TARDIS, {-2.4f, 0.2f, 8.0f}, {2.9f, 0.6f, 4.4f}, 2.1f, 0.0f },
/* Immediate tunnel acceleration after the one-bar TARDIS crossing. */
{ BAR(6), SC_KALEIDO, CAM_PUSH, TR_CUT, 0,
{0.15f, -0.1f, 0.0f}, {0.15f, -0.1f, 10.0f}, 7.0f, 0.74f, 0.08f,
{0.15f, 1.45f, 0.25f, 1.0f} },
/* First running cat, near enough to read during the initial 15 seconds. */
{ BAR(8), SC_CORRIDOR, CAM_TRACK, TR_CUT, 0,
{-0.8f, 0.9f, 0.0f}, {0.0f, 0.8f, 4.0f}, 0.3f, 0.58f, 0.0f,
{0.24f, 0.68f, 0.3f, 0.0f},
ACT_CAT_RUN, {-1.2f, 0.60f, 3.4f}, {1.3f, 0.60f, 3.4f}, 1.35f, 2.5f },
/* Rise over the ridge; small distant sun and deeper haze. */
{ BAR(10), SC_HORIZON, CAM_CRANE, TR_CUT, 0,
{5.0f, 2.1f, -14.0f}, {0.0f, 4.0f, 40.0f}, 0.45f, 0.58f, 0.0f,
{58.0f, 0.14f, 0.86f, 0.45f} },
{ BAR(12), SC_REACTOR, CAM_ORBIT, TR_CUT, 0,
{-5.0f, 2.0f, -10.0f}, {0.0f, 0.0f, 0.0f}, 0.22f, 0.45f, 0.0f,
{0.0f, 1.0f, 0.15f, 0.3f} },
/* Waveform gallery, high transverse move, mirror floor. */
{ BAR(14), SC_PLINTH, CAM_TRACK, TR_CUT, 0,
{-2.0f, 6.0f, 8.0f}, {0.0f, 7.2f, 30.0f}, 0.3f, 0.58f, 0.0f,
{1.1f, 0.6f, 0.2f, 0.65f} },
/* VERSE: low left arcade, rising sightline into the organ rank. */
{ BAR(17), SC_CATHEDRAL, CAM_PUSH, TR_CUT, 0,
{-6.0f, -3.0f, -22.0f}, {-3.0f, 8.0f, 26.0f}, 2.0f, 0.64f, 0.0f,
{0.15f, 0.4f, 0.0f, 0.0f} },
/* Cat 1: +X jamb crossing, 32-row run, fixed z matches the mesh facing. */
{ BAR(19), SC_CORRIDOR, CAM_TRACK, TR_CUT, 0,
{-1.0f, 1.6f, 0.0f}, {1.0f, 1.5f, 8.0f}, 0.18f, 0.62f, 0.0f,
{0.26f, 0.66f, 0.3f, 0.0f},
ACT_CAT_RUN, {-0.65f, 0.56f, 5.0f}, {0.65f, 0.56f, 5.0f}, 1.25f, 3.0f },
/* Night drive: close asphalt and distant lamps supply layered parallax. */
{ BAR(21), SC_DRIVE, CAM_HOLD, TR_CUT, 0,
{0.0f, 1.3f, 0.0f}, {0.0f, 1.3f, 20.0f}, 0.0f, 0.70f, 0.0f,
{22.0f, 0.25f, 0.05f, 0.65f} },
/* Cat 2: +X floor reflection crossing over 32 rows. */
{ BAR(23), SC_CORRIDOR, CAM_TRACK, TR_CUT, 0,
{0.5f, 0.55f, 0.0f}, {0.0f, -0.35f, 6.0f}, -0.25f, 0.66f, 0.0f,
{0.22f, 0.7f, 0.5f, 0.0f},
ACT_CAT_RUN, {-0.65f, 0.63f, 4.2f}, {0.65f, 0.63f, 4.2f}, 1.4f, 3.0f },
/* CHORUS: crane up through nave, broad organ-and-vault composition. */
{ BAR(25), SC_CATHEDRAL, CAM_CRANE, TR_CUT, 0,
{3.0f, -2.0f, -16.0f}, {0.0f, 10.0f, 34.0f}, 0.65f, 0.78f, 0.0f,
{0.55f, 0.35f, -0.1f, 0.2f} },
/* Wide low sun, level travel keeps camera above the grid. */
{ BAR(27), SC_HORIZON, CAM_PUSH, TR_CUT, 0,
{-5.0f, 3.0f, 0.0f}, {-5.0f, 3.0f, 40.0f}, 5.0f, 0.76f, 0.0f,
{44.0f, 0.52f, 0.62f, 0.28f} },
/* A luminous filament sculpture turns independently of the lateral camera. */
{ BAR(29), SC_ORBITAL, CAM_TRACK, TR_CUT, 0,
{0.0f, 1.0f, -11.0f}, {0.0f, 0.0f, 0.0f}, 0.30f, 0.445f, 0.0f,
{2.0f, 1.0f, 1.0f, 0.15f} },
/* Four-sector entry, axial movement keeps the camera inside the bore. */
{ BAR(31), SC_KALEIDO, CAM_PUSH, TR_CUT, 0,
{0.2f, -0.16f, 0.0f}, {0.2f, -0.16f, 6.0f}, 4.0f, 0.72f, 0.0f,
{0.1f, 1.35f, 0.2f, 0.0f} },
/* One beat only, restrained connective accent into the solo. */
{ BEAT(32,4), SC_BURST, CAM_DRIFT, TR_CUT, 0,
{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 6.0f}, 0.0f, 0.64f, 0.0f,
{70.0f, 0.3f, 0.55f, 0.12f} },
/* SOLO I: delayed fracture, orbit uncovers suspended slab depth. */
{ BAR(33), SC_VOID, CAM_ORBIT, TR_CUT, 0,
{-6.0f, 3.0f, -22.0f}, {0.0f, 4.8f, 0.0f}, 0.055f, 0.48f, 0.0f,
{0.3f, 0.6f, 0.0f, 1.4f} },
/* Compact reactor: close low orbit, radius 12.25, tighter portrait lens. */
{ BAR(36), SC_REACTOR, CAM_ORBIT, TR_CUT, 0,
{-5.0f, -2.0f, -11.0f}, {0.0f, 0.0f, 0.0f}, 0.12f, 0.38f, 0.05f,
{0.0f, 0.7f, 0.15f, 0.2f} },
/* Cat 3: 48-row crane, y ends at 2.30; run uses actual shot span. */
{ BAR(39), SC_CORRIDOR, CAM_CRANE, TR_CUT, 0,
{0.0f, 1.65f, 0.0f}, {0.0f, 2.5f, 8.0f}, 0.12f, 0.65f, 0.0f,
{0.24f, 0.68f, 0.2f, 0.0f},
ACT_CAT_RUN, {-0.7f, 0.61f, 5.8f}, {0.7f, 0.61f, 5.8f}, 1.35f, 3.0f },
/* Faster night drive as the solo answers. */
{ BAR(42), SC_DRIVE, CAM_HOLD, TR_CUT, 0,
{0.0f, 1.3f, 0.0f}, {0.0f, 1.3f, 20.0f}, 0.0f, 0.76f, 0.0f,
{42.0f, 0.80f, 0.45f, 0.9f} },
/* SOLO II: orbit the eclipse and its intersecting accretion sheets. */
{ BAR(45), SC_ORBITAL, CAM_ORBIT, TR_CUT, 0,
{0.0f, 2.9f, -13.0f}, {0.0f, 0.0f, 0.0f}, 0.09f, 0.425f, 0.0f,
{1.0f, 0.8f, 1.0f, -0.18f} },
/* Six-sector reverse passage; axis remains fixed, no sideways wall impact. */
{ BAR(48), SC_KALEIDO, CAM_PULL, TR_CUT, 0,
{-0.2f, 0.2f, 0.0f}, {-0.2f, 0.2f, 6.0f}, 4.0f, 0.64f, 0.0f,
{0.35f, 1.5f, 0.4f, 1.0f} },
/* Close moving monitor wall; 'signal found' appears once inside one CRT. */
{ BAR(51), SC_PLINTH, CAM_TRACK, TR_CUT, 0,
{3.0f, 7.0f, 9.0f}, {0.0f, 7.2f, 30.0f}, -0.4f, 0.58f, 0.0f,
{1.0f, 0.4f, 0.2f, 0.15f} },
/* Expanded reactor: eye-level lateral reveal, distance 12.33..12.47. */
{ BAR(54), SC_REACTOR, CAM_TRACK, TR_CUT, 0,
{6.0f, 4.0f, -10.0f}, {0.0f, 0.0f, 0.0f}, -0.35f, 0.42f, 0.0f,
{1.0f, 1.0f, 0.4f, 0.55f} },
/* SOLO III: organ ascent, eye ends below vault spring. */
{ BAR(57), SC_CATHEDRAL, CAM_CRANE, TR_CUT, 0,
{-3.0f, -2.0f, -20.0f}, {0.0f, 11.0f, 36.0f}, 0.9f, 0.7f, 0.0f,
{0.35f, 0.4f, -0.2f, 0.25f} },
/* Accelerating debris passage with restrained warm highlights. */
{ BAR(60), SC_BURST, CAM_DRIFT, TR_CUT, 0,
{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 10.0f}, 0.0f, 0.78f, -0.15f,
{105.0f, 0.48f, 0.2f, 0.1f} },
/* The sole gas-giant flyby: a tilted ring plane and a lit atmosphere. */
{ BAR(63), SC_ORBITAL, CAM_TRACK, TR_CUT, 0,
{0.0f, 3.8f, -12.0f}, {0.0f, 0.0f, 0.0f}, 0.35f, 0.404f, 0.0f,
{0.0f, 1.0f, 1.0f, 0.22f} },
/* Ten-sector open iris hall; forward travel, wider architecture. */
{ BAR(66), SC_KALEIDO, CAM_PUSH, TR_CUT, 0,
{0.32f, -0.25f, 0.0f}, {0.32f, -0.25f, 6.0f}, 6.0f, 0.8f, 0.0f,
{0.65f, 1.85f, 0.7f, 2.0f} },
/* SOLO IV: close collapse study, gentle withdrawal 12.05 -> 12.92 over 64 rows.
Narrow lens keeps the shrinking core substantial through the whole phrase. */
{ BAR(69), SC_REACTOR, CAM_PULL, TR_CUT, 0,
{-3.0f, 2.0f, -11.5f}, {0.0f, 0.0f, 0.0f}, 0.12f, 0.35f, 0.0f,
{3.0f, 1.5f, 0.95f, 1.0f} },
/* Fast axial tunnel passage during the dense solo run. */
{ BAR(73), SC_KALEIDO, CAM_PUSH, TR_CUT, 0,
{0.1f, 0.1f, 0.0f}, {0.1f, 0.1f, 10.0f}, 10.0f, 0.76f, 0.25f,
{0.35f, 1.7f, 0.45f, 0.0f} },
/* Lateral +X run over 32 rows, camera tracks beside the cat. */
{ BAR(77), SC_CORRIDOR, CAM_TRACK, TR_CUT, 0,
{-0.65f, 1.35f, 0.0f}, {0.15f, 1.15f, 6.0f}, 0.12f, 0.7f, 0.0f,
{0.2f, 0.75f, 0.6f, 0.0f},
ACT_CAT_RUN, {-0.7f, 0.6f, 4.8f}, {0.7f, 0.6f, 4.8f}, 1.1f, 3.0f },
/* One-bar spinning meme cat, then a short skyline pickup into arrival. */
{ BAR(79), SC_BURST, CAM_HOLD, TR_CUT, 0,
{0.0f, 0.1f, -4.0f}, {0.0f, 0.1f, 0.0f}, 0.0f, 0.62f, 0.0f,
{40.0f, 0.15f, 0.2f, 0.0f},
ACT_SPIN_CAT, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, 1.5f, 0.55f },
{ BAR(80), SC_HORIZON, CAM_CRANE, TR_CUT, 0,
{-6.0f, 2.5f, -14.0f}, {0.0f, 4.0f, 40.0f}, 0.55f, 0.72f, 0.0f,
{12.0f, 0.36f, 0.44f, 0.6f} },
/* One beat into arrival, no white-flash transition. */
{ BEAT(80,4), SC_BURST, CAM_DRIFT, TR_CUT, 0,
{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 6.0f}, 0.0f, 0.64f, 0.0f,
{84.0f, 0.35f, 0.5f, 0.1f} },
/* ARRIVAL: central nave opens, full rank and stained glass. */
{ BAR(81), SC_CATHEDRAL, CAM_PUSH, TR_CUT, 0,
{0.0f, -2.0f, -30.0f}, {0.0f, 8.0f, 50.0f}, 1.6f, 0.76f, 0.0f,
{0.25f, 0.4f, -0.2f, 0.25f} },
{ BAR(83), SC_ORBITAL, CAM_PULL, TR_CUT, 0,
{4.0f, -1.5f, -10.0f}, {0.0f, 0.0f, 0.0f}, 0.55f, 0.64f, -0.12f,
{1.0f, 1.5f, 0.9f, 0.65f} },
/* Two-bar monitor-wall inscription: 'stay strange'. */
{ BAR(85), SC_PLINTH, CAM_CRANE, TR_CUT, 0,
{0.0f, 6.5f, 5.0f}, {0.0f, 7.2f, 30.0f}, 0.18f, 0.60f, 0.0f,
{1.1f, 0.6f, 0.15f, 0.7f} },
{ BAR(87), SC_VOID, CAM_PULL, TR_CUT, 0,
{7.0f, 5.0f, -16.0f}, {0.0f, 4.0f, 0.0f}, 0.4f, 0.62f, 0.0f,
{-0.4f, 0.4f, 0.8f, 0.0f} },
/* Broad sunset release with sustained lateral parallax. */
{ BAR(89), SC_HORIZON, CAM_TRACK, TR_CUT, 0,
{-5.0f, 3.0f, -10.0f}, {0.0f, 4.0f, 40.0f}, 0.8f, 0.82f, 0.0f,
{6.0f, 0.6f, 0.72f, 0.34f} },
/* OUTRO: retreat from the filament sculpture. */
{ BAR(93), SC_ORBITAL, CAM_PULL, TR_CUT, 0,
{3.0f, 2.0f, -12.0f}, {0.0f, 0.0f, 0.0f}, 1.0f, 0.52f, 0.0f,
{2.0f, 0.45f, 0.7f, -0.40f} },
/* Last two bars: withdraw through the dark nave; parent applies endfade. */
{ BAR(95), SC_CATHEDRAL, CAM_PULL, TR_CUT, 0,
{0.0f, -1.0f, -26.0f}, {0.0f, 5.0f, 46.0f}, 3.0f, 0.62f, 0.0f,
{0.3f, -0.7f, 0.35f, -0.7f} },
};
#define NSHOTS ((int)(sizeof(g_shots) / sizeof(g_shots[0])))

763
song_data.h Normal file
View file

@ -0,0 +1,763 @@
/* Through-composed form: 48 orders / 96 bars / 174.149659864 seconds.
Notes use MIDI-12; X=-1 means no trigger. No audio mastering validation.
Drum API: 6 = kick + crash; 7 = kick + snare (synthwave backbeats).
INTRO orders 0- 1; section ID 0; proposed trim -14 dB
SYNTHWAVE orders 2- 7; section ID 1; proposed trim -14 dB
METAL VERSE orders 8-11; section ID 4; proposed trim -8 dB
CHORUS orders 12-15; section ID 5; proposed trim -6 dB
SOLO orders 16-39; section ID 8; proposed trim -10 dB
ARRIVAL orders 40-45; section ID 9; proposed trim -3 dB
OUTRO orders 46-47; section ID 10; proposed trim -14 dB
SOLO spacious lead orders 16-19; proposed trim -14 dB
SOLO melodic guitar orders 20-24; proposed trim -11 dB
SOLO driving shredding orders 25-30; proposed trim -9 dB
SOLO organ counterpoint orders 31-35; proposed trim -12 dB
SOLO climactic burst orders 36-39; proposed trim -6 dB
Outro final order trim -22 dB. Generated by tools/arrange_v11.py. */
#define SNG_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1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
45,-1,-1,-1,-1,-1,53,-1,-1,-1,52,-1,52,-1,-1,-1,
-1,-1,48,-1,-1,-1,50,-1,-1,-1,-1,47,-1,-1,-1,-1,
-1,60,-1,-1,-1,64,-1,-1,-1,67,-1,-1,65,-1,-1,-1,
-1,62,-1,-1,-1,60,-1,-1,57,-1,-1,-1,59,-1,-1,-1,
65,-1,-1,64,-1,-1,-1,60,-1,-1,57,-1,-1,-1,-1,-1,
60,-1,-1,62,-1,-1,67,-1,-1,64,-1,-1,62,-1,-1,-1,
62,-1,-1,-1,64,-1,-1,67,-1,-1,69,-1,69,-1,-1,-1,
65,-1,-1,-1,64,-1,-1,-1,60,-1,-1,59,-1,64,-1,-1,
57,-1,60,-1,64,-1,69,-1,69,-1,69,-1,-1,67,65,64,
-1,-1,60,-1,62,-1,65,-1,-1,64,-1,64,-1,-1,-1,-1,
62,-1,65,-1,69,-1,72,71,69,-1,65,-1,64,-1,60,-1,
57,-1,60,-1,64,-1,64,-1,64,-1,-1,62,-1,59,-1,-1,
65,-1,65,-1,-1,69,72,74,72,-1,69,-1,67,-1,64,-1,
60,-1,62,-1,65,-1,69,67,64,-1,64,-1,-1,60,-1,-1,
60,64,67,-1,69,-1,72,-1,69,-1,64,-1,60,-1,57,-1,
60,64,67,-1,65,-1,62,-1,60,-1,57,-1,57,-1,59,-1,
62,64,65,69,72,-1,74,-1,72,-1,69,-1,65,-1,62,-1,
60,64,67,69,67,-1,64,-1,60,-1,59,-1,57,-1,57,-1,
57,59,60,62,64,65,67,69,67,65,64,62,60,59,57,55,
57,60,64,69,72,69,64,60,57,59,60,64,69,67,64,57,
62,65,64,67,65,69,67,72,69,65,62,60,57,60,64,67,
60,64,67,69,64,67,69,72,67,69,72,74,72,69,64,-1,
69,64,69,65,69,64,69,62,69,64,69,60,69,64,69,59,
69,64,69,67,69,64,69,65,69,64,69,64,69,67,69,71,
60,67,72,76,72,67,60,64,65,72,77,72,65,62,57,62,
69,72,69,67,65,64,62,60,59,57,55,59,60,64,67,-1,
62,60,57,55,57,60,62,65,67,62,65,67,69,65,67,69,
72,67,69,72,74,72,69,65,64,60,59,60,64,67,69,-1,
65,57,67,59,69,60,72,64,74,65,72,64,69,60,67,59,
64,65,67,69,72,74,77,74,72,69,67,64,60,57,-1,-1,
-1,-1,69,-1,72,-1,76,-1,-1,-1,-1,72,-1,-1,74,-1,
-1,-1,77,-1,-1,-1,74,-1,-1,-1,-1,72,-1,-1,-1,-1,
-1,79,-1,-1,76,-1,76,-1,-1,-1,74,-1,-1,-1,71,-1,
-1,-1,69,-1,-1,-1,72,-1,-1,76,-1,-1,72,-1,-1,-1,
-1,-1,74,-1,-1,77,-1,-1,81,-1,-1,77,-1,-1,76,-1,
-1,-1,72,-1,-1,69,-1,-1,72,-1,-1,76,-1,79,-1,-1,
-1,77,-1,76,-1,72,-1,-1,-1,74,-1,-1,77,-1,-1,74,
-1,-1,71,-1,-1,69,-1,-1,72,-1,76,-1,79,-1,76,-1,
74,-1,74,-1,-1,77,-1,79,-1,77,-1,74,-1,-1,72,-1,
-1,69,-1,-1,72,-1,76,-1,79,-1,76,-1,74,-1,71,-1,
57,64,69,72,69,64,60,65,62,65,69,74,72,69,65,62,
65,69,72,77,74,72,69,65,67,69,72,74,77,74,72,69,
72,69,65,60,65,69,72,77,74,72,69,65,62,65,69,74,
69,67,64,60,64,67,69,76,72,69,67,64,60,64,67,69,
77,69,76,69,74,67,72,65,69,72,74,77,81,77,74,72,
69,65,67,69,72,74,77,81,77,74,72,69,67,64,60,59,
62,65,69,74,72,69,65,62,65,69,72,77,74,69,64,64,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,64,67,69,72,
83,-1,83,-1,83,-1,-1,-1,-1,-1,79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,
21,-1,21,21,-1,21,21,-1,21,-1,21,21,21,-1,21,21,
31,-1,31,-1,-1,31,-1,-1,28,-1,28,28,28,-1,28,-1,
26,26,26,-1,26,26,26,-1,29,-1,-1,29,29,-1,29,-1,
21,-1,21,21,21,21,21,-1,28,-1,-1,28,28,-1,28,28,
29,-1,29,-1,29,29,-1,-1,31,-1,31,31,31,-1,31,-1,
26,-1,26,-1,26,26,26,-1,28,28,-1,28,28,-1,28,28,
24,24,24,-1,24,24,24,-1,31,-1,31,31,31,-1,31,-1,
28,-1,28,-1,28,28,28,-1,21,-1,21,21,21,21,21,-1,
21,-1,-1,-1,21,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
24,-1,-1,-1,24,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
31,-1,-1,-1,31,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
21,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
24,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
31,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,
28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
21,-1,-1,-1,21,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
24,-1,-1,-1,24,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,
28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
24,-1,-1,-1,24,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
21,-1,-1,-1,21,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
28,-1,-1,-1,28,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,
21,-1,21,-1,-1,21,-1,-1,31,-1,-1,31,-1,-1,31,-1,
29,-1,29,-1,-1,29,-1,-1,28,-1,-1,28,-1,-1,28,-1,
26,-1,26,-1,-1,26,-1,-1,21,-1,-1,21,-1,-1,21,-1,
24,-1,24,-1,-1,24,-1,-1,28,-1,-1,28,-1,-1,28,-1,
29,-1,29,-1,-1,29,-1,-1,26,-1,-1,26,-1,-1,26,-1,
31,-1,31,-1,-1,31,-1,-1,28,-1,-1,28,-1,-1,28,-1,
24,-1,24,-1,-1,24,-1,-1,29,-1,-1,29,-1,-1,29,-1,
21,-1,21,-1,-1,21,-1,-1,31,-1,-1,31,-1,-1,31,-1,
26,-1,26,-1,-1,26,-1,-1,31,-1,-1,31,-1,-1,31,-1,
24,-1,24,-1,-1,24,-1,-1,28,-1,-1,28,-1,-1,28,-1,
29,-1,29,-1,-1,29,-1,-1,31,-1,-1,31,-1,-1,31,-1,
28,-1,28,-1,-1,28,-1,-1,21,-1,-1,21,-1,-1,21,-1,
21,-1,-1,-1,21,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
31,-1,-1,-1,31,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,21,-1,-1,-1,21,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,24,-1,-1,-1,24,-1,-1,-1,
29,-1,-1,-1,29,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,
24,-1,-1,-1,24,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,29,-1,-1,-1,29,-1,-1,-1,
31,-1,-1,-1,31,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
21,-1,21,-1,-1,21,-1,-1,26,-1,-1,26,-1,-1,26,-1,
29,-1,29,-1,-1,29,-1,-1,31,-1,-1,31,-1,-1,31,-1,
24,-1,24,-1,-1,24,-1,-1,29,-1,-1,29,-1,-1,29,-1,
26,-1,26,-1,-1,26,-1,-1,28,-1,-1,28,-1,-1,28,-1,
29,-1,29,-1,-1,29,-1,-1,31,-1,-1,31,-1,-1,31,-1,
21,-1,21,-1,-1,21,-1,-1,28,-1,-1,28,-1,-1,28,-1,
26,-1,26,-1,-1,26,-1,-1,29,-1,-1,29,-1,-1,29,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,28,-1,
23,-1,-1,-1,23,-1,-1,-1,23,-1,-1,-1,23,-1,-1,-1,
23,-1,-1,-1,23,-1,-1,-1,23,-1,-1,-1,23,-1,-1,-1,
31,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,31,-1,-1,-1,
26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,26,-1,-1,-1,
28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,28,-1,-1,-1,
33,-1,-1,-1,33,-1,-1,-1,33,-1,-1,-1,33,-1,-1,-1,
26,-1,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0,0,0,0,0,0,1,0,0,0,0,0,0,0,
};
static const signed char g_sqArpOct[] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
};
static const unsigned char g_sqOrgMode[] = {
2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
2,2,2,2,0,0,0,0,0,0,0,0,0,0,2,2,
};
static const unsigned char g_sqRiser[] = {
0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,
};
static const short g_sqGain[] = {
204,204,204,204,204,204,204,204,408,408,408,408,513,513,513,513,
204,204,204,204,289,289,289,289,289,363,363,363,363,363,363,257,
257,257,257,257,513,513,513,513,725,725,725,725,725,725,204,81,
};
static const unsigned char g_sqSyn[] = {
0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
static const unsigned char g_sqSect[] = {
0,0,1,1,1,1,1,1,4,4,4,4,5,5,5,5,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,9,9,9,9,9,9,10,10,
};

1055
synth.h Normal file

File diff suppressed because it is too large Load diff

505
tardis_mesh.h Normal file
View file

@ -0,0 +1,505 @@
/* --------------------------------------------------------------------------
baked mesh: "TARDIS" by Andrewsha, CC-BY-4.0
https://sketchfab.com/3d-models/tardis-576b10bd7fb64af987c4f59e3ba475cd
~100k triangles decimated offline by vertex clustering to the table below;
nothing is parsed at runtime.
-------------------------------------------------------------------------- */
#define TAR_NV 454
#define TAR_NT 912
#define TAR_QS (1.0f / 16384.0f)
static const short g_tarV[] = {
-7088,-12342,7421,-6977,-11788,6523,-6812,9146,4679,-494,6249,-6263,
-355,9168,-6718,-7026,-11867,-259,-6351,-10343,-378,-371,9166,6702,
-6402,-10343,-4867,-6402,-5910,-4867,-5011,9088,6705,-6323,-5910,4614,
-6323,-1555,4614,4826,9103,-6711,-6323,-10343,4614,-6787,9122,-297,
-5029,9089,-6723,-6160,3826,1574,-6184,6249,-1995,-6171,3841,-1995,
6530,9084,1537,-6153,-5910,-3388,-6153,-1555,-3388,-6402,-1555,-4867,
-6663,9029,-1995,-6836,9152,-4890,-6153,-10343,-3388,-6346,6249,-411,
-6351,3789,-378,-6402,6249,-4867,-6402,3789,-4867,-6171,3841,-3388,
-6375,-566,-309,-6429,-589,-4914,-6122,-654,-3388,-6369,-1555,-320,
-6351,-5910,-378,-6174,6249,1561,-6465,3020,-4975,-7017,-11836,-4943,
-6153,-5910,-1995,-6153,-1555,-1995,-6122,-654,-1995,-6384,3020,-295,
-6679,9054,1525,-6323,6249,4614,-6084,3020,1404,-6392,3020,4819,
-6326,3789,4621,-6153,-5910,1545,-6153,-1555,1545,-6153,-10343,1545,
-7020,-11943,1523,-6133,-640,1504,-6350,-606,4694,-6904,-11813,4692,
7339,-12314,7421,7339,-12282,6248,6145,-10343,4638,6491,-11527,4716,
6457,-11527,-206,6175,-10343,-378,6624,9170,-278,6212,-1156,-479,
6175,-1555,-378,6227,6249,-4868,6227,3789,-4868,6170,3789,-411,
6170,6249,-411,6484,9021,-1995,5995,3841,-1995,6254,-589,-4914,
6227,-1555,-4868,6227,-5910,-4868,6175,-5910,-378,6227,-10343,-4868,
6110,1960,-474,5977,-10343,1544,6453,-11563,1561,5977,-5910,1544,
6142,-5884,4653,6145,-1555,4638,5977,-1555,1544,5988,3819,1554,
5860,2369,1319,6004,6249,1572,6134,3799,4591,6126,6249,4577,
6642,9143,4665,5901,-566,1561,6000,-345,4551,1488,-5910,-6077,
1488,-1555,-6077,1488,-10343,-6077,1444,-638,-6057,-3467,-5910,-6071,
-4947,-5910,-6320,-4947,-1555,-6320,-3467,-1555,-6071,-3467,-10343,-6071,
-4947,-10343,-6320,-2077,9019,-6578,6388,-11809,-6938,7339,-12314,-6846,
-494,-10343,-6263,-494,-5910,-6263,-494,-1555,-6263,-378,3020,-6301,
-494,3789,-6263,-5056,3020,-6382,-4947,3789,-6320,-4947,6249,-6320,
-2077,3841,-6088,-442,-585,-6280,-328,-11833,-6907,-5038,-11788,-6820,
-4994,-589,-6347,-3467,-654,-6040,-3467,3841,-6088,1560,6249,-6098,
1539,9029,-6583,4787,6253,-6343,1341,3020,-6009,1509,3807,-6083,
4880,3020,-6382,4772,3789,-6320,4772,-5910,-6320,4772,-1555,-6320,
4772,-10343,-6320,3291,9019,-6578,1491,-11933,-6932,4819,-589,-6347,
4848,-11836,-6935,3291,3841,-6088,3291,-5910,6060,4772,-5910,6309,
4772,-1555,6309,3291,-1555,6060,3291,-10343,6060,4772,-10343,6309,
4802,-581,6319,3291,-601,6010,-336,-11513,6540,-493,-10343,6253,
1494,-11560,6489,1488,-10343,6066,1488,-5910,6066,-493,-5910,6253,
1488,-1555,6066,-493,-1555,6253,1481,-599,6029,-442,-585,6269,
4837,3020,6332,4772,3789,6309,1560,6249,6087,1527,3824,6077,
1539,9029,6572,4772,6249,6309,4826,9103,6700,3291,3841,6077,
4880,-11502,6576,-378,3020,6290,1470,3020,5974,-493,3789,6253,
-3472,-1555,6060,-4950,-1555,6309,-4950,-5910,6309,-3472,-5910,6060,
-4950,-10343,6309,-3472,-10343,6060,-5086,3020,6422,-4980,3789,6353,
-4980,6249,6353,-3470,9019,6567,-493,6249,6253,-3471,3841,6078,
-5012,-581,6361,-5066,-11520,6537,-3472,-654,6029,-2077,6249,6091,
-2077,9019,6567,-3473,6252,6088,-2079,3841,6077,-3471,-11542,6526,
3287,9031,6585,3291,6249,6091,3291,6249,-6102,-3467,9019,-6578,
-3460,-11846,-6856,-3467,6249,-6101,-2077,6249,-6101,-6184,6249,-3388,
-7037,-11902,-3388,-6663,9029,-3388,-6029,3020,-3388,-6663,9029,3378,
-6153,3850,3378,-6184,6249,3378,5995,3841,3378,6535,9074,3386,
6484,9021,-3388,5995,3841,-3388,5977,-5910,-3388,5977,-10343,-3388,
6659,9148,-4926,5977,-1555,-3388,5946,-654,-3388,6008,6249,3378,
6008,6249,-1995,6008,6249,-3388,6443,-11542,-3388,6493,-11502,-4975,
-6664,10947,-6541,-4957,10907,-6948,-4959,10908,6936,-3638,10389,7092,
7037,10352,-232,7008,10411,3455,6992,10461,1702,-7176,10530,1408,
4288,10603,-7046,3359,10375,-7118,6472,10948,-6544,-3171,10344,-7111,
1342,10500,7089,-200,10352,-7134,-7190,10375,-1979,-7214,10350,6,
-7198,10320,2865,-6788,-10343,-6706,-7080,-12035,-6839,-6788,-10343,6695,
-6665,9294,6595,-6699,10952,6482,6613,6249,6695,6613,3789,6695,
6556,9376,6545,6612,-10343,-6706,6613,-10343,6695,6530,-11487,6612,
6856,10887,-4896,6166,-12314,7421,7339,-12314,-4898,5917,2677,4502,
6289,3020,-4975,6508,10953,6483,6476,9321,-6621,6876,10872,4589,
-6678,9388,-6614,-7173,10423,-3613,7024,10459,-1648,-7042,10907,4618,
-7044,10861,-4840,-1975,10366,7095,5792,3020,3377,6613,3020,6695,
6613,-566,6695,7339,-12314,-1995,7339,-12337,-266,-7020,-11925,-2001,
7339,-12314,1470,7339,-12282,4621,6443,-11542,-1995,4802,-12314,7421,
3291,-11902,-6954,1488,-12364,7421,-316,-12305,7421,-2077,-11950,-6919,
-3467,-12314,7421,-4977,-12393,7422,-2077,-12393,7421,-2080,-11571,6469,
3298,-12350,7421,3297,-11556,6499,6613,-1555,6695,6613,-5910,6695,
6488,6257,-6795,6612,3789,-6706,6612,-566,-6706,6612,-1555,-6706,
6612,-5910,-6706,5856,2150,-3039,-6908,-11870,3378,6443,-11542,3378,
7339,-12282,3378,-6029,3020,3378,-6153,-5910,3378,-6153,-1555,3378,
-6122,-654,3378,-6153,-10343,3378,5977,-1555,3378,5885,-566,3378,
5977,-10343,3378,5977,-5910,3378,5856,2213,-2211,5977,-10343,-1995,
5977,-5910,-1995,5977,-1555,-1995,5946,-654,-1995,-6029,3020,-1995,
-6153,-10343,-1995,7339,-12314,-3388,6612,3020,-6706,3291,-654,-6040,
3291,3020,-5947,3291,-1555,-6071,3291,-10343,-6071,3291,-5910,-6071,
-2077,-654,-6040,-2077,3020,-5947,-3467,3020,-5947,-6788,-5910,-6706,
-6788,-1555,-6706,-6788,-566,-6706,-6788,6249,-6706,-6788,3789,-6706,
-6788,3020,-6706,-2077,-10343,-6071,-2077,-1555,-6071,-2077,-5910,-6071,
-2081,-10343,6060,-2081,-654,6029,-2081,-1555,6060,-2081,-5910,6060,
3291,3020,5936,-3472,3020,5936,-2081,3020,5936,-6588,3764,6803,
-6557,6249,6811,-6623,3020,6794,-6664,-552,6784,-6788,-1555,6695,
-6788,-5910,6695,1749,10423,-7101,-1866,10399,-7130,7025,10316,-3040,
4661,10857,6911,2850,10309,7114,27,10353,7117,5792,12280,1394,
4566,12265,5891,5751,12313,-1681,5714,12343,-77,6158,11979,-6251,
5683,12424,-4976,-3469,11979,-6251,-1881,11979,-6251,2957,11979,-6251,
5722,12337,3161,-159,12343,5796,-1764,12313,5833,-3251,12313,5833,
-349,11979,-6251,-6334,11979,-3390,-6334,11979,-5091,5792,12280,4679,
-6334,11979,4823,5731,12380,5813,-5173,11979,-6251,5751,12313,-3169,
-6334,11979,3318,1368,11979,-6251,4653,11979,-6251,-6334,11979,1368,
-6334,11979,-1798,1460,12265,5891,-6333,11979,6240,-6334,11979,-6251,
-6334,11979,-266,2961,12355,5782,-5166,12401,5758,-5723,12480,-3059,
-5723,12480,3140,4500,12480,-5641,2962,12480,-5641,-3138,12480,-5641,
-5723,12480,-1623,-5723,12480,1412,-5723,12551,4583,-5723,12480,-5,
-1705,12480,-5641,-5413,12498,-5175,-88,12480,-5641,1528,12480,-5641,
-128,13687,897,-121,13579,-950,-1032,13541,-950,821,13669,-20,
-1032,13576,-4,821,13579,889,798,13558,-950,-1032,13541,876,
-141,13973,-37,4802,-12950,-4897,4802,-12950,-1995,4802,-12950,-295,
4802,-12950,1519,4802,-12950,4621,3291,-12950,4621,3291,-12950,-295,
3291,-12950,1519,3291,-12950,-1995,3291,-12950,-4897,-377,-12950,-4897,
1527,-12950,-4897,-377,-12950,-1995,1528,-12950,-1995,1528,-12950,-295,
-377,-12950,-295,1528,-12950,1519,-377,-12950,1519,-377,-12950,4621,
1528,-12950,4621,-2077,-12950,4621,-2077,-12950,-295,-2077,-12950,1520,
-2077,-12950,-1995,-2077,-12950,-4897,-4977,-12950,-4897,-4977,-12950,-1995,
-4977,-12950,-295,-4977,-12950,1520,-4977,-12950,4621,-4977,-12950,3378,
-2077,-12950,3378,-377,-12950,3378,1528,-12950,3378,3292,-12950,3378,
4802,-12950,3378,4802,-12950,-3388,3291,-12950,-3388,-377,-12950,-3388,
1528,-12950,-3388,-2077,-12950,-3388,-4977,-12950,-3388,-3467,-12950,4621,
-3467,-12950,-295,-3467,-12950,1520,-3467,-12950,-1995,-3467,-12950,-4897,
-3467,-12950,3378,-3467,-12950,-3388,5881,1253,1060,6109,811,-476,
-134,15806,-52,812,15640,-166,675,15646,757,-88,15646,-1035,
-1117,15646,-5,-248,15640,895,-88,16384,-5,5857,1011,-3067,
5857,1081,-2191,5874,184,4477,
};
static const signed char g_tarN[] = {
-13,89,89,-99,-79,3,-126,-18,-2,-2,-13,-126,
0,-29,-124,-112,-59,-3,-126,13,0,1,-28,124,
-124,14,23,-125,0,24,-4,-20,125,-125,0,-24,
-125,0,-24,6,-15,-126,-124,17,-20,-124,-28,2,
3,-15,-126,-127,-3,8,-126,-14,-5,-127,-3,-9,
123,-31,2,-127,0,11,-127,1,7,-125,0,23,
-123,-29,-6,-126,-16,-1,-125,18,13,-126,-11,-3,
-127,1,3,-126,-6,16,-125,-1,25,-126,-6,12,
-127,1,-2,-125,-1,24,-125,2,20,-127,0,1,
-127,0,0,-126,-10,6,-124,1,27,-111,-61,8,
-127,0,-8,-126,0,-11,-127,3,-7,-127,-2,-2,
-124,-28,3,-126,-8,-14,-126,-2,13,-125,1,-21,
-126,0,-17,-127,0,7,-127,0,9,-126,13,5,
-122,-36,4,-127,2,8,-125,1,-21,-86,-88,30,
51,103,54,-75,-102,14,124,7,-24,111,-61,-6,
114,-55,2,127,8,4,124,-26,0,127,3,0,
127,0,-3,126,-9,12,125,2,22,127,-1,0,
127,-11,0,124,-29,-3,127,-4,-10,125,-1,24,
125,0,24,125,0,24,127,0,0,125,3,24,
127,-2,0,127,9,5,115,-53,0,127,0,7,
125,0,-24,125,2,-23,127,1,9,127,-4,7,
126,-3,12,126,-14,5,124,-6,-25,126,-9,-15,
126,-16,5,127,4,7,123,4,-31,6,0,-127,
6,0,-127,6,22,-125,9,2,-127,11,0,-127,
24,0,-125,24,0,-125,9,0,-127,12,15,-126,
20,10,-125,-5,-28,-124,31,-115,-45,88,90,-19,
0,12,-126,0,0,-127,0,0,-127,-1,-1,-127,
1,-1,-127,27,0,-124,23,1,-125,21,-9,-125,
-8,-6,-127,-1,1,-127,2,-56,-114,5,-59,-113,
25,-1,-125,18,2,-126,12,-3,-126,6,-12,-126,
5,-29,-124,-18,-7,-125,10,0,-127,5,-4,-127,
-28,-1,-124,-26,-1,-124,-24,0,-125,-24,0,-125,
-22,11,-125,-5,-26,-124,-2,-52,-116,-26,0,-124,
24,-71,-102,-14,-4,-126,-9,0,127,-24,0,125,
-24,0,125,-7,1,127,-11,10,126,-21,8,125,
-27,1,124,-6,3,127,-2,-77,101,3,10,127,
2,-53,116,5,7,127,6,0,127,0,0,127,
8,1,127,-3,0,127,9,2,127,5,0,127,
-27,-1,124,-22,0,125,7,-10,126,5,-4,127,
3,-27,124,-21,-10,125,-1,-8,127,-11,-5,126,
-2,-77,101,-5,0,127,11,0,127,1,-1,127,
13,1,126,25,-2,125,24,0,125,11,0,127,
24,3,125,7,9,126,33,-2,123,31,1,123,
20,-6,125,8,-29,123,-2,-13,126,14,-3,126,
31,-1,123,-6,-68,107,11,3,126,-6,-10,126,
-5,-28,124,9,-14,126,-8,-6,127,0,-62,111,
-4,-26,124,-8,-11,126,-8,-10,-126,8,-29,-123,
-5,-52,-116,8,-14,-126,-6,-10,-126,-126,-12,9,
-115,-55,3,-124,-26,2,-126,0,14,-123,-33,-5,
-127,-5,-4,-126,-14,-7,127,-8,-5,124,-26,-2,
123,-30,9,127,-3,9,127,0,11,126,9,8,
125,-21,-5,126,1,13,126,1,19,127,-10,-4,
126,-10,-7,126,-14,8,116,-53,1,111,-61,-5,
-108,22,-63,-14,18,-125,-12,39,120,1,29,124,
123,32,0,124,30,1,124,29,0,-126,15,1,
11,20,-125,1,13,-126,56,22,-112,-1,17,-126,
2,26,124,0,18,-126,-126,15,-2,-126,17,1,
-126,17,0,-64,11,-109,-50,-71,-93,-117,3,50,
-75,-6,102,-76,38,94,102,-2,75,82,-5,96,
116,-3,53,88,12,-91,67,3,108,76,-21,99,
123,29,-9,9,-98,-80,41,-86,84,124,-2,-27,
124,1,26,95,31,78,96,-8,-83,122,34,8,
-103,-4,-74,-126,15,-3,124,28,-1,-125,18,11,
-125,20,-10,0,29,124,127,-3,-2,122,1,37,
80,2,98,95,84,-6,-74,-55,87,-114,-56,1,
-94,71,-48,104,73,-3,114,-56,-3,53,-86,77,
-2,-55,-114,-111,60,-17,122,27,22,-4,-56,-114,
21,-41,-118,79,-82,57,-49,80,86,-1,-66,109,
-31,-110,-55,-3,-62,111,118,0,48,98,0,80,
90,2,-89,90,3,-90,90,-1,-90,90,0,-90,
90,0,-90,126,0,14,-115,-54,2,116,-52,-3,
-76,-101,-8,-127,0,-8,-127,0,-7,-127,0,-6,
-126,2,-14,-125,18,-8,127,2,-4,127,6,-7,
126,12,-8,127,0,-7,126,-1,-12,126,10,-10,
127,0,-8,127,0,-7,127,4,-8,-126,-2,-15,
-126,18,-6,-110,-51,-39,90,-1,-90,-6,3,-127,
-15,-2,-126,-13,0,-126,-6,18,-126,-9,0,-127,
-8,3,-127,-16,-1,-126,13,-1,-126,-90,0,-89,
-113,0,-57,-63,-1,-110,-94,-3,-85,-62,1,-111,
-113,0,-58,-6,17,-126,-10,1,-127,-8,0,-127,
-9,9,126,-14,2,126,-7,0,127,-8,0,127,
-16,-2,126,21,-3,125,-11,0,127,-115,2,53,
-97,-6,82,-67,1,108,-114,0,56,-67,0,108,
-98,0,80,1,15,-126,-1,15,-126,123,32,0,
11,25,124,2,27,124,-2,32,123,67,108,0,
0,113,58,66,109,0,69,107,0,70,92,-51,
52,116,-4,-3,80,-99,0,73,-104,-1,75,-103,
63,110,-2,0,107,69,0,107,68,3,110,64,
0,73,-104,-102,76,2,-95,85,-6,56,114,3,
-94,85,1,27,116,44,3,85,-94,67,108,1,
-106,70,2,0,73,-104,5,72,-105,-101,77,-1,
-104,73,0,-1,109,65,-88,85,33,-47,89,-78,
-107,69,0,1,108,67,-10,117,47,-37,121,-2,
-45,119,-2,8,123,-30,0,120,-40,-4,121,-37,
-40,121,0,-37,122,0,-28,123,9,-43,120,0,
0,121,-40,-18,124,-21,0,121,-40,0,121,-40,
1,123,32,-1,124,-28,-15,125,-14,32,123,0,
-29,124,-2,17,125,17,12,125,-19,-18,125,15,
-5,127,-2,49,-112,-34,54,-115,0,52,-116,0,
51,-116,0,34,-117,35,0,-116,51,0,-127,0,
0,-127,0,0,-127,0,0,-122,-36,2,-122,-37,
-1,-122,-36,0,-127,0,0,-127,0,0,-127,0,
0,-127,0,0,-127,0,0,-127,0,0,-116,53,
0,-116,51,0,-115,53,0,-127,0,0,-127,0,
0,-127,0,-2,-122,-35,-22,-123,-25,-34,-122,0,
-36,-122,1,-35,-122,-1,-34,-112,49,-39,-121,2,
0,-127,0,0,-127,0,0,-127,0,0,-127,0,
49,-117,0,51,-116,0,0,-127,0,0,-127,0,
0,-127,0,0,-127,0,-37,-121,-1,0,-116,51,
0,-127,0,0,-127,0,0,-127,0,-1,-121,-40,
0,-127,0,0,-127,0,0,0,0,0,0,0,
-12,-126,-12,-22,-125,-3,-12,-126,-12,0,0,0,
0,0,0,-3,-125,-22,0,0,0,127,0,0,
127,0,0,0,0,0,
};
static const unsigned short g_tarI[] = {
21,22,23,21,23,9,26,21,9,26,9,8,
41,35,32,41,32,42,6,5,52,6,52,51,
6,51,49,6,49,36,36,49,50,36,50,35,
35,50,53,35,53,32,43,46,17,43,17,28,
15,27,37,15,37,44,77,78,60,77,60,61,
79,77,61,79,61,74,76,67,83,76,83,84,
89,82,64,89,64,63,82,79,74,82,74,64,
95,96,97,95,97,98,99,100,96,99,96,95,
98,97,116,98,116,117,93,130,114,93,114,104,
91,93,104,91,104,105,92,91,105,92,105,106,
94,92,106,94,106,113,119,123,108,119,108,3,
134,135,136,134,136,137,138,139,135,138,135,134,
137,136,140,137,140,141,144,145,143,144,143,142,
143,145,146,143,146,147,147,146,148,147,148,149,
149,148,150,149,150,151,161,162,155,161,155,163,
164,165,166,164,166,167,167,166,168,167,168,169,
178,176,165,178,165,164,169,168,177,169,177,183,
99,188,115,99,115,100,192,26,8,192,8,39,
194,31,30,194,30,38,202,203,75,202,75,73,
205,202,73,205,73,72,206,205,72,206,72,71,
203,210,211,203,211,75,229,230,39,229,39,8,
237,75,211,237,211,102,238,239,59,238,59,58,
237,102,132,237,132,128,231,1,177,231,177,168,
57,239,56,241,56,239,85,68,62,85,62,20,
255,256,90,255,90,243,103,102,211,103,211,242,
258,60,78,258,78,260,257,262,60,257,60,258,
0,269,177,0,177,1,270,266,142,270,142,271,
266,265,144,266,144,142,272,263,160,272,160,273,
234,235,86,234,86,87,256,274,81,256,81,90,
274,275,80,274,80,81,275,238,58,275,58,80,
276,277,125,276,125,121,276,65,66,276,66,277,
278,279,127,278,127,131,278,71,72,278,72,279,
279,280,126,279,126,127,279,72,73,279,73,280,
280,237,128,280,128,126,280,73,75,280,75,237,
281,244,66,281,66,201,235,255,243,235,243,86,
284,283,59,284,59,261,285,47,48,285,48,196,
287,12,54,287,54,288,289,14,11,289,11,286,
286,11,12,286,12,287,81,290,291,81,291,90,
14,289,282,14,282,55,80,58,292,80,292,293,
81,80,293,81,293,290,58,59,283,58,283,292,
86,243,254,86,254,198,260,78,283,260,283,284,
46,285,196,46,196,17,50,287,288,50,288,53,
51,289,286,51,286,49,49,286,287,49,287,50,
290,82,89,290,89,291,289,51,52,289,52,282,
293,292,77,293,77,79,290,293,79,290,79,82,
292,283,78,292,78,77,198,254,84,198,84,83,
76,294,70,76,70,67,61,60,262,61,262,295,
63,64,297,63,297,298,64,74,296,64,296,297,
74,61,295,74,295,296,43,28,19,43,19,299,
5,6,300,5,300,259,6,36,40,6,40,300,
36,35,41,36,41,40,22,41,42,22,42,34,
301,210,262,301,262,257,294,281,201,294,201,70,
295,262,210,295,210,203,298,297,205,298,205,206,
297,296,202,297,202,205,296,295,203,296,203,202,
299,19,31,299,31,194,259,300,26,259,26,192,
300,40,21,300,21,26,40,41,22,40,22,21,
23,22,34,23,34,33,242,211,210,242,210,301,
67,68,85,67,85,83,302,244,71,302,71,278,
302,278,131,302,131,124,277,302,124,277,124,125,
277,66,244,277,244,302,298,206,281,298,281,294,
63,298,294,63,294,76,63,76,84,63,84,89,
246,204,65,246,65,276,246,276,121,246,121,13,
123,122,107,123,107,108,122,94,113,122,113,107,
131,303,304,131,304,124,206,71,244,206,244,281,
124,304,133,124,133,125,139,138,273,139,273,160,
128,132,264,128,264,306,131,127,305,131,305,303,
128,306,307,128,307,126,126,307,305,126,305,127,
146,134,137,146,137,148,145,138,134,145,134,146,
148,137,141,148,141,150,265,272,273,265,273,144,
307,91,92,307,92,305,306,93,91,306,91,307,
303,305,92,303,92,94,306,264,130,306,130,93,
138,145,144,138,144,273,304,122,123,304,123,133,
303,94,122,303,122,304,309,107,113,309,113,308,
118,310,109,118,109,110,311,229,8,311,8,9,
312,311,9,312,9,23,313,312,23,313,23,33,
314,315,30,314,30,29,315,316,38,315,38,30,
316,313,33,316,33,38,108,107,309,108,309,112,
104,114,267,104,267,317,143,320,271,143,271,142,
151,321,322,151,322,149,147,323,320,147,320,143,
149,322,323,149,323,147,106,318,308,106,308,113,
104,317,319,104,319,105,105,319,318,105,318,106,
268,270,271,268,271,183,310,309,308,310,308,117,
112,309,310,112,310,118,317,267,188,317,188,99,
320,169,183,320,183,271,321,178,164,321,164,322,
323,167,169,323,169,320,322,164,167,322,167,323,
318,98,117,318,117,308,317,99,95,317,95,319,
319,95,98,319,98,318,269,268,183,269,183,177,
109,310,117,109,117,116,120,119,3,120,3,4,
261,59,239,261,239,57,14,55,1,14,1,231,
155,162,324,155,324,159,159,324,152,159,152,153,
151,150,162,151,162,161,182,175,325,182,325,326,
163,182,326,163,326,161,175,171,170,175,170,325,
53,288,285,53,285,46,288,54,47,288,47,285,
32,53,46,32,46,43,42,299,194,42,194,34,
32,43,299,32,299,42,162,150,141,162,141,324,
324,141,140,324,140,152,326,325,178,326,178,321,
161,326,321,161,321,151,325,170,176,325,176,178,
34,194,38,34,38,33,45,48,327,45,327,328,
328,327,171,328,171,172,48,47,329,48,329,327,
327,329,170,327,170,171,47,54,330,47,330,329,
329,330,176,329,176,170,54,12,331,54,331,330,
330,331,165,330,165,176,12,11,332,12,332,331,
331,332,166,331,166,165,11,14,231,11,231,332,
332,231,168,332,168,166,156,7,174,156,174,154,
163,155,154,163,154,174,236,234,87,236,87,88,
232,328,172,232,172,10,2,45,328,2,328,232,
37,27,28,37,28,17,248,314,29,248,29,25,
158,157,234,158,234,236,153,152,255,153,255,235,
152,140,256,152,256,255,135,139,238,135,238,275,
136,135,275,136,275,274,140,136,274,140,274,256,
263,241,239,263,239,160,139,160,239,139,239,238,
157,153,235,157,235,234,16,111,314,16,314,248,
109,116,313,109,313,316,110,109,316,110,316,315,
111,110,315,111,315,314,116,97,312,116,312,313,
97,96,311,97,311,312,96,100,229,96,229,311,
100,115,230,100,230,229,216,250,341,216,341,342,
240,222,343,240,343,344,334,223,345,334,345,346,
217,218,339,217,339,348,253,338,349,253,349,350,
215,253,350,215,350,351,252,249,353,252,353,354,
247,217,348,247,348,355,336,245,357,336,357,340,
250,335,359,250,359,341,221,333,361,221,361,347,
222,220,362,222,362,343,249,226,364,249,364,353,
251,233,366,251,366,356,212,252,354,212,354,367,
226,227,368,226,368,364,245,247,355,245,355,357,
224,337,369,224,369,365,338,224,365,338,365,349,
333,225,352,333,352,361,225,334,346,225,346,352,
214,215,351,214,351,370,218,216,342,218,342,339,
228,251,356,228,356,360,220,221,347,220,347,362,
219,228,360,219,360,363,233,214,370,233,370,366,
335,240,344,335,344,359,337,336,340,337,340,369,
223,213,358,223,358,345,213,212,367,213,367,358,
227,219,363,227,363,368,360,356,372,362,347,374,
363,360,372,363,372,377,363,377,379,345,358,381,
345,381,375,358,367,381,361,382,383,368,363,379,
346,345,375,346,375,380,354,353,371,354,371,381,
356,378,372,347,361,383,347,383,374,343,362,373,
343,373,344,353,364,376,353,376,371,356,366,370,
356,370,378,367,354,381,364,368,379,364,379,376,
362,374,373,361,352,382,352,346,380,352,380,382,
375,381,385,349,365,384,381,386,385,383,382,385,
355,348,387,340,389,384,342,341,387,344,390,387,
380,375,385,348,339,387,350,349,384,351,350,384,
339,342,387,381,371,388,372,378,388,340,357,389,
341,359,387,374,383,385,344,373,390,371,376,388,
378,370,391,381,388,386,376,379,388,357,355,389,
369,340,384,355,387,389,373,374,385,365,369,384,
382,380,385,370,351,384,373,385,390,377,372,388,
370,384,391,378,391,388,359,344,387,379,377,388,
387,390,385,387,385,392,389,387,392,389,392,384,
391,384,392,391,392,388,388,392,385,388,385,386,
62,68,208,62,208,69,69,208,209,69,209,200,
200,209,65,200,65,204,201,209,208,201,208,70,
67,70,208,67,208,68,199,207,85,199,85,20,
87,86,198,87,198,207,83,85,207,83,207,198,
133,186,121,133,121,125,186,133,123,186,123,119,
129,186,119,129,119,120,121,186,129,121,129,13,
112,190,3,112,3,108,3,190,101,3,101,4,
101,190,189,101,189,187,111,16,187,111,187,189,
118,110,111,118,111,189,118,189,190,118,190,112,
65,209,201,65,201,66,29,30,31,29,31,191,
193,191,18,193,18,24,24,18,27,24,27,15,
19,18,191,19,191,31,27,18,19,27,19,28,
44,37,197,44,197,195,196,197,37,196,37,17,
48,45,197,48,197,196,2,195,197,2,197,45,
175,181,172,175,172,171,172,181,173,172,173,10,
180,173,181,180,181,179,175,182,179,175,179,181,
182,163,174,182,174,179,174,7,180,174,180,179,
156,154,185,156,185,184,155,159,185,155,185,154,
153,157,185,153,185,159,157,158,184,157,184,185,
25,29,191,25,191,193,199,88,87,199,87,207,
243,90,291,243,291,254,254,291,89,254,89,84,
88,247,245,88,245,236,25,252,212,25,212,248,
158,236,245,158,245,336,213,16,248,213,248,212,
102,103,242,102,242,211,262,257,258,262,258,60,
60,258,260,60,260,78,273,160,263,273,263,272,
399,395,396,399,396,400,401,394,395,401,395,399,
264,132,393,264,393,402,114,130,404,114,404,403,
405,406,407,405,407,408,408,407,409,408,409,410,
142,144,265,142,265,266,271,142,266,271,266,270,
414,408,410,414,410,415,416,405,408,416,408,414,
267,114,403,267,403,417,1,177,269,1,269,0,
5,420,421,5,421,52,259,419,420,259,420,5,
230,115,418,230,418,39,282,423,422,282,422,55,
424,425,411,424,411,413,425,426,412,425,412,411,
427,428,397,427,397,398,283,284,261,283,261,59,
52,421,423,52,423,282,415,410,425,415,425,424,
410,409,426,410,426,425,400,396,428,400,428,427,
78,260,284,78,284,283,210,301,257,210,257,262,
430,429,394,430,394,401,431,432,406,431,406,405,
433,431,405,433,405,416,192,434,419,192,419,259,
211,242,301,211,301,210,402,393,429,402,429,430,
403,404,432,403,432,431,417,403,431,417,431,433,
39,418,434,39,434,192,144,273,272,144,272,265,
407,399,400,407,400,409,406,401,399,406,399,407,
130,264,402,130,402,404,426,427,398,426,398,412,
409,400,427,409,427,426,432,430,401,432,401,406,
404,402,430,404,430,432,183,271,270,183,270,268,
436,414,415,436,415,437,438,416,414,438,414,436,
188,267,417,188,417,439,440,424,413,440,413,435,
437,415,424,437,424,440,441,433,416,441,416,438,
439,417,433,439,433,441,177,183,268,177,268,269,
420,436,437,420,437,421,419,438,436,419,436,420,
115,188,439,115,439,418,423,440,435,423,435,422,
421,437,440,421,440,423,434,441,438,434,438,419,
418,439,441,418,441,434,422,435,183,422,183,177,
435,413,271,435,271,183,412,398,273,412,273,144,
55,422,177,55,177,1,413,411,142,413,142,271,
411,412,144,411,144,142,398,397,160,398,160,273,
59,261,57,59,57,239,397,59,239,397,239,160,
429,210,262,429,262,394,396,78,283,396,283,428,
428,283,59,428,59,397,395,60,78,395,78,396,
394,262,60,394,60,395,132,102,211,132,211,393,
160,239,241,160,241,263,393,211,210,393,210,429,
222,246,13,222,13,220,220,13,129,220,129,221,
221,129,120,221,120,333,333,120,4,333,4,225,
225,4,101,225,101,334,334,101,187,334,187,223,
223,187,16,223,16,213,246,222,240,246,240,204,
199,217,247,199,247,88,204,240,335,204,335,200,
200,335,250,200,250,69,69,250,216,69,216,62,
62,216,218,62,218,20,20,218,217,20,217,199,
232,10,214,232,214,233,10,173,215,10,215,214,
173,180,253,173,253,215,184,158,336,184,336,337,
156,184,337,156,337,224,7,156,224,7,224,338,
180,7,338,180,338,253,232,233,251,232,251,2,
193,249,252,193,252,25,24,226,249,24,249,193,
2,251,228,2,228,195,15,227,226,15,226,24,
195,228,219,195,219,44,44,219,227,44,227,15,
444,445,446,444,446,449,294,452,451,281,294,451,
};
static const unsigned char g_tarM[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,
};
static const unsigned char g_tarPal[] = {
26,54,108,214,224,236,255,238,190,26,26,32,198,168,62,
};

186
tools/arrange_v11.py Normal file
View file

@ -0,0 +1,186 @@
"""Bake 48 through-composed orders, without rendering or playback.
5000 samples/row at 44100 Hz: 174.149659864 seconds, unchanged.
Section gains are compositional estimates, NOT calibrated mastering results.
Run python tools/arrange_v11.py to regenerate song_data.h.
"""
from pathlib import Path
import motif as MO
HERE = Path(__file__).resolve().parent
ROWS, ORDERS, SPR, SRATE = 32, 48, 5000, 44100
X = -1
SECTIONS = [
("INTRO", 0, 1, -14), ("SYNTHWAVE", 2, 7, -14),
("METAL VERSE", 8, 11, -8), ("CHORUS", 12, 15, -6),
("SOLO", 16, 39, -10), ("ARRIVAL", 40, 45, -3), ("OUTRO", 46, 47, -14),
]
# Preserve synth.h's quiet-section ABI (IDs 0 and 10), not list indices.
SECTION_IDS = (0, 1, 4, 5, 8, 9, 10)
SOLO_PHASES = [
("spacious lead", 16, 19, -14), ("melodic guitar", 20, 24, -11),
("driving shredding", 25, 30, -9), ("organ counterpoint", 31, 35, -12),
("climactic burst", 36, 39, -6),
]
KEYCHANGE_ORDER, KEYCHANGE = 40, 2
# Four eight-row harmonic slots per order, in A natural minor degrees.
# Riffs use this global scale, not a new minor scale at each chord root.
PROGRESSION = [
(0,0,4,4), (5,5,6,4),
(0,0,5,5), (2,2,6,6), (3,3,0,0), (5,5,4,4), (2,2,3,3), (6,6,4,4),
(0,0,6,4), (3,5,0,4), (5,6,3,4), (2,6,4,0),
(0,5,2,6), (3,0,5,4), (5,2,6,3), (3,5,4,4),
(0,0,5,5), (2,2,3,3), (5,5,6,6), (3,3,4,4),
(0,5,2,6), (3,0,4,4), (5,2,3,6), (2,6,0,5), (3,5,4,0),
(0,6,5,4), (3,0,2,4), (5,3,6,4), (2,5,0,6), (3,6,2,4), (5,6,4,0),
(0,2,3,5), (6,5,3,2), (3,0,5,2), (5,3,2,6), (3,5,6,4),
(0,3,5,6), (2,5,3,4), (5,6,0,4), (3,5,4,4),
(0,0,0,0), (5,5,2,2), (3,3,6,6), (2,5,3,4), (5,6,3,4), (3,4,0,0),
(5,3,0,0), (0,0,0,0),
]
def section_of(o):
return next(i for i, (_, a, b, _) in enumerate(SECTIONS) if a <= o <= b)
def kit(kind):
out = [0] * ROWS
if kind == "syn":
for r in range(0, ROWS, 4): out[r] = 1
for r in (4,12,20,28): out[r] = 7 # kick + snare
for r in range(2, ROWS, 4): out[r] = 3
elif kind == "ride":
for r in range(0, ROWS, 2): out[r] = 1 if r % 8 == 0 else 3
elif kind == "half":
for r in (0,16): out[r] = 1
for r in (8,24): out[r] = 2
for r in (6,14,22,30): out[r] = 3
elif kind in ("metal", "drive"):
for r in range(ROWS): out[r] = 3 if r % 2 == 0 else 0
for r in (0,6,8,16,22,24): out[r] = 1
if kind == "drive":
for r in (1,3,10,17,19,26): out[r] = 1
for r in (4,12,20,28): out[r] = 2
return out
def order_spec(o):
# Organ mode 2 and riff guitar never coincide. The melodic guitar is
# g_sqSolo's existing guitar voice; no new voice or runtime API is needed.
d = dict(owner="organ", kit=None, bass=0, org=2, syn=0, riff=False)
if 2 <= o <= 7:
d.update(owner="synth arp", kit="syn", bass=1, org=0, syn=1)
elif 8 <= o <= 11:
d.update(owner="riff", kit="metal", bass=2, org=0, riff=True)
elif 12 <= o <= 15:
d.update(owner="lead", kit="drive", bass=1, org=0)
elif 16 <= o <= 19:
d.update(owner="solo", kit="ride", bass=1, org=0)
elif 20 <= o <= 24:
d.update(owner="solo", kit="metal", bass=1, org=0)
elif 25 <= o <= 30:
d.update(owner="solo", kit="drive", bass=2, org=0)
elif 31 <= o <= 35:
# Organ owns the midrange; sparse solo answers above the voicings.
d.update(owner="organ", kit="half", bass=1)
elif 36 <= o <= 39:
d.update(owner="solo", kit="drive", bass=2, org=0)
elif 40 <= o <= 45:
d.update(owner="solo", kit="metal" if o in (40,45) else "drive", bass=1, org=0)
elif o == 46:
d.update(kit="half", bass=1)
return d
lead, solo, harm, bass, gtr = ([[X]*ROWS for _ in range(ORDERS)] for _ in range(5))
hold, drum = ([[0]*ROWS for _ in range(ORDERS)] for _ in range(2))
root, ctyp = ([[0]*4 for _ in range(ORDERS)] for _ in range(2))
arpo = [X]*ORDERS
orgm, rise, trim, syn, sect = ([0]*ORDERS for _ in range(5))
SOLO = {o: MO.extended_solo(o - 16) for o in range(16,40)}
for o in range(ORDERS):
d, si = order_spec(o), section_of(o)
sect[o], trim[o] = SECTION_IDS[si], SECTIONS[si][3]
for _, a, b, t in SOLO_PHASES:
if a <= o <= b: trim[o] = t
orgm[o], syn[o] = d["org"], d["syn"]
shift = KEYCHANGE if o >= KEYCHANGE_ORDER else 0
for ci, degree in enumerate(PROGRESSION[o]):
root[o][ci] = MO.deg(degree, 9 + shift) % 12
ctyp[o][ci] = int(degree in (2,5,6))
drum[o] = kit(d["kit"])
if o in (2,8,12,20,25,36,40): drum[o][0] = 6 # kick + crash
if o in (7,11,15,24,30,35,38,45):
drum[o][28:32] = [2,0,2,4] if o % 2 else [2,1,2,2]
if d["syn"]: drum[o][28] = 7 # fill preserves four-on-the-floor
if 12 <= o <= 15: lead[o] = MO.lead_chorus(o - 12)
if o in SOLO: solo[o] = list(SOLO[o])
if 40 <= o <= 45:
solo[o] = [n + shift if n >= 0 else X for n in MO.arrival_phrase(o - 40)]
# Upper thirds punctuate two burst phrases, not a second continuous line.
if o in (37,38):
for r in (0,8,16,24):
n = solo[o][r]
if n >= 0: harm[o][r] = MO.scale_step(n, 2)
if d["bass"]:
rhythm = (0,4,8,12,16,20,24,28) if d["bass"] == 1 else (0,2,5,8,11,14,16,18,21,24,27,30)
for r in rhythm:
bass[o][r] = MO.deg(PROGRESSION[o][r // 8], 21 + shift)
if d["riff"]:
for r, degree in enumerate(MO.verse_riff(o - 8)):
if degree is not None:
gtr[o][r] = MO.deg(PROGRESSION[o][r // 8] + degree, 21)
# The voice adds a fixed perfect fifth. B itself is in Am,
# but B5 adds F#: return to this chord's root (E here).
scale = {(9 + shift + n) % 12 for n in MO.MIN_IV}
if (gtr[o][r] + 7) % 12 not in scale:
gtr[o][r] = MO.deg(PROGRESSION[o][r // 8], 21 + shift)
bass[o][r] = MO.deg(PROGRESSION[o][r // 8], 21)
if o == 39:
# Twelve rows without triggers, then a four-note pickup. Envelopes
# decay rather than hold: this does not promise digital silence.
for lane, rest in ((solo,X),(bass,X),(drum,0)):
lane[o][16:28] = [rest]*12
if o == 47: trim[o] = -22
for o in (7,15,35,39): rise[o] = 1
gain = [round(1024 * 10 ** (t / 20)) for t in trim]
TABLES = {
"g_sqLead": ("signed char", lead), "g_sqSolo": ("signed char", solo),
"g_sqHarm": ("signed char", harm), "g_sqBass": ("signed char", bass),
"g_sqGtr": ("signed char", gtr), "g_sqHold": ("unsigned char", hold),
"g_sqDrum": ("unsigned char", drum), "g_sqRoot": ("signed char", root),
"g_sqType": ("unsigned char", ctyp), "g_sqArpOct": ("signed char", arpo),
"g_sqOrgMode": ("unsigned char", orgm), "g_sqRiser": ("unsigned char", rise),
"g_sqGain": ("short", gain), "g_sqSyn": ("unsigned char", syn),
"g_sqSect": ("unsigned char", sect),
}
def flatten(rows):
return [v for row in rows for v in (row if isinstance(row,list) else [row])]
def header():
out = "/* Through-composed form: 48 orders / 96 bars / 174.149659864 seconds.\n"
out += " Notes use MIDI-12; X=-1 means no trigger. No audio mastering validation.\n"
out += " Drum API: 6 = kick + crash; 7 = kick + snare (synthwave backbeats).\n"
for i, (name,a,b,t) in enumerate(SECTIONS):
out += f" {name:12s} orders {a:2d}-{b:2d}; section ID {SECTION_IDS[i]}; proposed trim {t:+d} dB\n"
for name,a,b,t in SOLO_PHASES:
out += f" SOLO {name:18s} orders {a}-{b}; proposed trim {t:+d} dB\n"
out += " Outro final order trim -22 dB. Generated by tools/arrange_v11.py. */\n"
out += f"#define SNG_ORDERS {ORDERS}\n#define SNG_ROWS {ROWS}\n\n"
for name,(ctype,rows) in TABLES.items():
values = flatten(rows)
out += f"static const {ctype} {name}[] = {{\n"
for i in range(0,len(values),16):
out += " " + ",".join(map(str,values[i:i+16])) + ",\n"
out += "};\n"
return out
if __name__ == "__main__":
(HERE.parent / "song_data.h").write_text(header(), encoding="utf-8")
print(f"song_data.h: {ORDERS*ROWS} rows, {ORDERS*ROWS*SPR} samples, {ORDERS*ROWS*SPR/SRATE:.9f}s")
for name,a,b,_ in SECTIONS:
print(f"{name:12s} {a:02d}-{b:02d} {(b-a+1)*ROWS*SPR/SRATE:.3f}s")
for name,a,b,_ in SOLO_PHASES:
counts = [sum(n>=0 for n in solo[o]) for o in range(a,b+1)]
print(f"SOLO {name}: {len(counts)} phrases; attacks {counts}")

78
tools/audio_audit.py Normal file
View file

@ -0,0 +1,78 @@
"""Read-only PCM audit; emits JSON, never renders, plays, or rewrites audio.
Usage: python tools/audio_audit.py dump.wav [other.wav ...]
Requires numpy. Optional ffmpeg supplies EBU R128/true-peak measurements.
Row-boundary steps are diagnostics, not proof of audible clicks: chip waves
and intended drum transients also have large first differences.
"""
import argparse
import hashlib
import json
import re
import shutil
import subprocess
import wave
from pathlib import Path
import numpy as np
def db(value):
return float(20 * np.log10(max(float(value), 1e-12)))
def audit(path):
path = Path(path).resolve()
with wave.open(str(path), "rb") as wav:
rate, channels, width, frames = (wav.getframerate(), wav.getnchannels(),
wav.getsampwidth(), wav.getnframes())
if width != 2 or channels != 2 or rate != 44100:
raise ValueError("Expected 44100 Hz stereo 16-bit PCM")
pcm = np.frombuffer(wav.readframes(frames), dtype="<i2").reshape(-1, 2)
x = pcm.astype(np.float64) / 32768.0
if not len(x):
raise ValueError("Empty audio")
step = np.max(np.abs(np.diff(x, axis=0)), axis=1)
boundaries = np.arange(5000, len(x), 5000)
row_steps = step[boundaries - 1]
rms = float(np.sqrt(np.mean(x*x)))
peak = float(np.max(np.abs(x)))
result = dict(path=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
frames=frames, seconds=frames/rate, sample_peak_dbfs=db(peak),
rms_dbfs=db(rms), crest_db=db(peak)-db(rms),
dc_fs=x.mean(axis=0).tolist(),
clipped_samples=int(np.count_nonzero((pcm == -32768) | (pcm == 32767))),
last_sample=pcm[-1].tolist(),
stereo_correlation=float(np.corrcoef(x.T)[0, 1])
if np.all(np.std(x, axis=0) > 0) else None,
final_100ms_rms_dbfs=db(np.sqrt(np.mean(x[-4410:]**2))),
row_step_quantiles_fs=np.quantile(row_steps, [.5, .95, 1]).tolist()
if len(row_steps) else [],
all_step_quantiles_fs=np.quantile(step, [.5, .95, 1]).tolist()
if len(step) else [])
result["worst_row_steps"] = [dict(order=int(boundaries[i]//160000),
row=int(boundaries[i]//5000 % 32), step_fs=float(row_steps[i]))
for i in np.argsort(row_steps)[-12:][::-1]]
result["orders"] = [dict(order=i//160000,
rms_dbfs=db(np.sqrt(np.mean(x[i:i+160000]**2))),
peak_dbfs=db(np.max(np.abs(x[i:i+160000]))))
for i in range(0,len(x),160000)]
if shutil.which("ffmpeg"):
proc = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-nostdin",
"-i", str(path), "-af", "ebur128=peak=true:framelog=verbose",
"-f", "null", "-"], capture_output=True, text=True, check=True)
summary = proc.stderr.rsplit("Summary:", 1)[-1]
for key, pattern in (("integrated_lufs", r"I:\s+(-?[\d.]+) LUFS"),
("lra_lu", r"LRA:\s+([\d.]+) LU"),
("true_peak_dbtp", r"Peak:\s+(-?[\d.]+) dBFS")):
match = re.search(pattern, summary)
if match:
result[key] = float(match[1])
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("wav", nargs="+", type=Path)
args = parser.parse_args()
print(json.dumps([audit(path) for path in args.wav], indent=2, allow_nan=False))

32
tools/export_song.py Normal file
View file

@ -0,0 +1,32 @@
"""Export the current through-composed score without rendering or playback.
This compatibility entry point shares arrange_v11.header(); it must never
silently restore the obsolete v10 score or omit the section/gain/synth lanes.
Use --check for a read-only comparison, or --output to export elsewhere.
"""
import argparse
from pathlib import Path
from arrange_v11 import header
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path,
default=Path(__file__).resolve().parent.parent / "song_data.h")
parser.add_argument("--check", action="store_true")
args = parser.parse_args(argv)
expected = header()
if args.check:
if not args.output.exists() or args.output.read_text(encoding="utf-8") != expected:
print(f"{args.output}: missing or stale; export the current arrangement")
return 1
print(f"{args.output}: current arrangement verified")
return 0
args.output.write_text(expected, encoding="utf-8")
print(f"{args.output}: current arrangement exported")
return 0
if __name__ == "__main__":
raise SystemExit(main())

82
tools/export_video.py Normal file
View file

@ -0,0 +1,82 @@
"""Silent offline export; check BOTH pipeline processes before publishing the MP4."""
import json
import hashlib
import math
import os
from pathlib import Path
import subprocess
import wave
from datetime import datetime
ROOT = Path(__file__).resolve().parents[1]
def main():
exe = ROOT / "gfxvideo.exe"
inputs = [ROOT / name for name in ("gfx.c", "synth.h", "voices.h", "shots.h",
"song_data.h", "cats_mesh.h", "tardis_mesh.h", "c64_font.h", "shaders.h")]
inputs += list((ROOT / "fx").glob("*.hlsl")) + list((ROOT / "fx/out").glob("*.h"))
inputs += list((ROOT / "fx").glob("*.hlsli"))
# Each target rewrites identical FXC headers. A later release build does
# not make the video executable stale; authored shader/include files do.
authored = [p for p in inputs if p.name != "shaders.h" and p.parent.name != "out"]
if any(p.stat().st_mtime_ns > exe.stat().st_mtime_ns for p in authored):
raise RuntimeError("Stale video renderer: run makevideo_gpu.bat to rebuild first")
def fingerprint():
return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in inputs + [exe]}
provenance = fingerprint()
subprocess.run([str(exe)], cwd=ROOT,
env={**os.environ, "CRTK_WAVONLY": "1"}, check=True)
with wave.open(str(ROOT / "dump.wav"), "rb") as wav:
assert (wav.getnchannels(), wav.getsampwidth(), wav.getframerate()) == (2, 2, 44100)
duration = wav.getnframes() / wav.getframerate()
expected = math.ceil(duration * 60)
pending = ROOT / "CRTkafa.pending.mp4"
env = dict(os.environ)
env.pop("CRTK_WAVONLY", None)
render = subprocess.Popen([str(exe)], cwd=ROOT, env=env, stdout=subprocess.PIPE)
try:
encode = subprocess.Popen([
"ffmpeg", "-nostdin", "-y", "-hide_banner", "-loglevel", "warning", "-stats",
"-f", "rawvideo", "-pixel_format", "bgra", "-video_size", "1280x720",
"-framerate", "60", "-i", "pipe:0", "-i", str(ROOT / "dump.wav"),
"-c:v", "libx264", "-preset", "medium", "-crf", "19",
"-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "256k",
"-movflags", "+faststart", str(pending)], stdin=render.stdout, cwd=ROOT)
render.stdout.close()
encoder_status = encode.wait()
renderer_status = render.wait()
if encoder_status or renderer_status:
raise RuntimeError(f"Export failed: renderer={renderer_status}, encoder={encoder_status}")
finally:
if render.poll() is None:
render.terminate()
render.wait()
info = json.loads(subprocess.check_output([
"ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(pending)]))
video = next(s for s in info["streams"] if s["codec_type"] == "video")
audio = next(s for s in info["streams"] if s["codec_type"] == "audio")
if int(video["nb_frames"]) != expected:
raise RuntimeError(f"Incomplete video: expected {expected}, got {video['nb_frames']}")
if abs(float(audio["duration"]) - duration) > 0.05:
raise RuntimeError("Audio duration differs from source WAV")
if fingerprint() != provenance:
raise RuntimeError("Sources or renderer changed during export; not publishing")
published = ROOT / "CRTkafa.mp4"
try:
pending.replace(published)
except PermissionError:
# A player may hold the previous delivery open on Windows. Do not
# close it or destroy that file; publish the verified render separately.
published = ROOT / ("CRTkafa-cracktro-1-" + datetime.now().strftime("%Y%m%d-%H%M%S") + ".mp4")
pending.replace(published)
provenance[published.name] = hashlib.sha256(published.read_bytes()).hexdigest()
provenance["dump.wav"] = hashlib.sha256((ROOT / "dump.wav").read_bytes()).hexdigest()
(ROOT / "export-provenance.json").write_text(json.dumps(provenance, indent=2) + "\n")
print(f"Verified export: {expected} frames, {duration:.3f} s, 1280x720, 60 fps", flush=True)
print(f"Video: {published}", flush=True)
if __name__ == "__main__":
main()

133
tools/motif.py Normal file
View file

@ -0,0 +1,133 @@
"""Written phrases for the 48-order form, in MIDI-minus-12 note numbers.
The call A-F-E remains in the chorus. The solo also develops the natural
minor run and pedal contour of music_render.py V7_SOLO (used by v8), with
new intervallic runs, lyrical lines, displaced accents and upper responses.
No register folding or clipping: pitches are chosen in the score itself.
Each phrase is exactly one 32-row / two-bar order, not a looping cell.
"""
ROWS, X, A4 = 32, -1, 57
MIN_IV = (0,2,3,5,7,8,10)
def deg(d, base=A4):
octave, index = divmod(d,7)
return base + 12*octave + MIN_IV[index]
def scale_step(note, steps):
octave, pc = divmod(note-A4,12)
return deg(octave*7 + MIN_IV.index(pc) + steps)
def lay(pitches, rhythm=None, base=A4):
"""Place explicit attacks; X is no trigger, not sustain or note-off.
Repeated pitches in lyrical passages deliberately refresh the existing
decaying solo envelope. No claim of continuous legato is made.
"""
if rhythm is None: rhythm = range(len(pitches))
assert len(pitches) == len(rhythm), "pitch/rhythm length mismatch"
assert len(set(rhythm)) == len(rhythm), "two attacks in one lane/row"
out = [X]*ROWS
for p,r in zip(pitches,rhythm):
assert 0 <= r < ROWS
if p is not None:
out[r] = deg(p,base)
assert 0 <= out[r] <= 127, "signed-char note overflow"
return out
def lead_chorus(i):
# Four distinct statements in the sole chorus; no octave folding.
phrases = (
((0,5,4,4,2,3,4,6,5,4), (0,4,6,8,12,16,18,20,24,26)),
((2,4,7,6,4,2,0,2,3,4,4), (0,2,4,7,10,12,16,18,20,24,26)),
((5,7,9,7,6,4,2,3,5,4), (0,3,6,8,11,14,16,20,24,26)),
((3,5,4,2,1,0,-1,1,4,4), (0,2,6,10,12,16,18,20,24,26)),
)
pitches, rhythm = phrases[i]
return lay(pitches,rhythm,base=A4)
# Each tuple is (scale degrees, attack rows, base). Dense lines are written
# in full, including rests, so there is no repeated motif-call generator.
SOLO_SCORE = (
# 16-19: spacious pickup, displaced answer, longer arcs entering the band.
((0,5,4,4,2,3,1), (0,6,10,12,18,22,27), 45),
((2,4,6,5,3,2,0,1), (1,5,9,12,17,21,24,28), 57),
((5,4,2,0,2,3,6,4,3), (0,3,7,10,16,19,22,25,28), 57),
((3,4,6,7,7,5,4,2,1,4), (0,4,7,10,12,16,20,24,27,29), 57),
# 20-24: lyrical electric guitar; repeated tones refresh long gestures,
# with short sixteenth flourishes embedded between them.
((0,2,4,7,7,7,6,5,4,2,3,5,4,4),
(0,2,4,6,8,10,13,14,15,18,20,22,25,27), 57),
((3,5,7,9,8,7,5,4,2,0,2,4,4,4,3,1),
(0,2,4,6,7,8,10,12,14,16,18,20,22,24,27,29), 57),
((5,5,7,9,10,9,7,6,4,2,3,5,7,6,4,4,2),
(0,2,5,6,7,8,10,12,14,16,18,20,22,23,24,26,29), 57),
((2,4,6,7,9,7,4,2,0,2,4,6,5,3,2,0,0,1),
(0,1,2,4,6,8,10,12,14,16,17,18,20,22,24,26,28,30), 57),
((3,4,5,7,9,10,9,7,5,3,2,4,6,7,6,4,2,1,0,0),
(0,1,2,3,4,6,8,10,12,14,16,17,18,19,20,22,24,26,28,30), 57),
# 25: v8 natural-minor ascent/descent + broken arpeggio contour retained.
((0,1,2,3,4,5,6,7, 6,5,4,3,2,1,0,-1,
0,2,4,7,9,7,4,2, 0,1,2,4,7,6,4,0), None, 57),
# 26: contrary thirds, a falling sixth, then upward displaced groups.
((3,5,4,6,5,7,6,9, 7,5,3,2,0,2,4,6,
2,4,6,7,4,6,7,9, 6,7,9,10,9,7,4,None), None, 57),
# 27: v8's pedal-point gesture, natural seventh against the shared scale.
((7,4,7,5,7,4,7,3, 7,4,7,2,7,4,7,1,
7,4,7,6,7,4,7,5, 7,4,7,4,7,6,7,8), None, 57),
# 28: cross-string arpeggios and a long cascading answer.
((2,6,9,11,9,6,2,4, 5,9,12,9,5,3,0,3,
7,9,7,6,5,4,3,2, 1,0,-1,1,2,4,6,None), None, 57),
# 29: low-to-high sixteenth sequence with changing group lengths.
((3,2,0,-1,0,2,3,5, 6,3,5,6,7,5,6,7,
9,6,7,9,10,9,7,5, 4,2,1,2,4,6,7,None), None, 57),
# 30: descending sixths become a rising scalar exit; two-row breath.
((5,0,6,1,7,2,9,4, 10,5,9,4,7,2,6,1,
4,5,6,7,9,10,12,10, 9,7,6,4,2,0,None,None), None, 57),
# 31-35: upper answers over moving organ chords; guitar riff is absent.
((0,2,4,2,3,5,3,2), (2,4,6,11,14,18,22,27), 69),
((6,4,4,3,1,0,2,4,2), (1,4,6,10,14,18,22,25,28), 69),
((3,5,7,5,4,2,0,2,4,6), (2,5,8,11,14,18,21,24,27,29), 69),
((5,4,2,3,5,3,1,0,2,4,6,4), (1,3,5,9,12,15,18,21,24,26,28,30), 69),
((3,3,5,6,5,3,2,0,2,4,6,4,3,1), (0,2,5,7,9,11,14,17,20,22,24,26,28,30), 69),
# 36-38: continuous sixteenths, large interval shapes and a higher peak.
((0,4,7,9,7,4,2,5, 3,5,7,10,9,7,5,3,
5,7,9,12,10,9,7,5, 6,7,9,10,12,10,9,7), None, 57),
((9,7,5,2,5,7,9,12, 10,9,7,5,3,5,7,10,
7,6,4,2,4,6,7,11, 9,7,6,4,2,4,6,7), None, 57),
((12,7,11,7,10,6,9,5, 7,9,10,12,14,12,10,9,
7,5,6,7,9,10,12,14, 12,10,9,7,6,4,2,1), None, 57),
# 39: dense first bar, twelve trigger-free rows, four-note rising pickup.
((3,5,7,10,9,7,5,3,5,7,9,12,10,7,4,4,4,6,7,9),
tuple(range(16)) + (28,29,30,31), 57),
)
def extended_solo(i):
pitches, rhythm, base = SOLO_SCORE[i]
return lay(pitches, rhythm, base)
def arrival_phrase(i):
# Six new phrases after the +2 shift, not a repeated chorus. A high
# tonic is refreshed, answered, expanded, and finally brought home.
phrases = (
((14,14,14,12,11,9,7,7), (0,2,4,10,14,18,24,26)),
((5,7,9,12,12,10,9,7,6,4,2,2), (0,2,4,6,8,12,14,16,20,22,26,28)),
((3,5,7,10,9,7,6,5,3,4,6,7,7), (0,3,6,8,10,12,15,18,21,24,26,28,30)),
((2,4,6,9,7,6,5,7,9,12,10,9,7,5,4,4), tuple(range(0,32,2))),
((5,7,9,10,12,10,9,7,6,4,3,5,7,6,4,2,1,0),
(0,1,2,3,4,6,8,10,12,14,16,18,20,22,24,26,28,30)),
((3,5,4,2,1,4,7,7,4,2,0,0), (0,2,4,6,8,10,12,14,18,22,26,28)),
)
return lay(*phrases[i])
def verse_riff(i):
# Four individually paced two-bar riffs. Chord-relative root/fifth/octave
# degrees preserve both key consonance and the guitar's power fifth.
phrases = (
((0,0,4,0,7,4,0,0,4,7,4,0,4,0,0), (0,2,3,6,8,10,12,15,16,18,21,24,26,28,30)),
((0,4,0,7,4,0,0,4,0,7,4,0,0,4,7,0), (0,1,4,6,8,11,12,14,16,19,20,22,24,27,28,31)),
((0,0,7,4,0,4,7,0,4,0,7,4,0,0,4,0,7), (0,2,4,5,8,10,12,14,16,18,20,22,24,25,28,30,31)),
((0,4,7,4,0,0,4,0,7,4,0,4,7,4,0,0,4,0), (0,1,2,4,6,8,10,12,14,16,18,20,22,24,26,28,29,30)),
)
out = [None]*ROWS
for p,r in zip(*phrases[i]): out[r] = p
return out

41
tools/test_bloom.py Normal file
View file

@ -0,0 +1,41 @@
"""Regression checks for native-grid separable bloom kernels (no third-party deps)."""
import math
import unittest
def kernel(center, offsets, weights):
result = {0: center}
for offset, weight in zip(offsets, weights):
lo = math.floor(offset)
fraction = offset - lo
for sign in (-1, 1):
for index, amount in ((lo, 1 - fraction), (lo + 1, fraction)):
at = sign * index
result[at] = result.get(at, 0) + amount * weight
return result
class BloomTests(unittest.TestCase):
def test_native_grid_kernel(self):
vertical = kernel(.2363835, [1.3730788, 3.2295113], [.3171515, .0646567])
horizontal = kernel(.1513151, [1.4415567, 3.3767077, 5.3550101, 7.3868203],
[.2503180, .1212263, .0394885, .0133097])
for profile in (vertical, horizontal):
self.assertAlmostEqual(sum(profile.values()), 1, places=6)
self.assertAlmostEqual(sum(i * w for i, w in profile.items()), 0, places=6)
for i in range(max(profile)):
self.assertGreater(profile[i], profile[i + 1])
self.assertEqual(profile[i], profile[-i])
def test_source_row_parity(self):
# Two adjacent source rows map to the same 2:1 downsample pixel;
# both undergo the same knee and carry precisely half its row energy.
vertical = kernel(.2363835, [1.3730788, 3.2295113], [.3171515, .0646567])
for row in range(12, 20, 2):
even = {row // 2 + k: w * .5 for k, w in vertical.items()}
odd = {(row + 1) // 2 + k: w * .5 for k, w in vertical.items()}
self.assertEqual(even, odd)
if __name__ == "__main__":
unittest.main()

163
tools/test_music_form.py Normal file
View file

@ -0,0 +1,163 @@
"""Score/API regression checks; no build, rendering, or audio playback.
Run: python -m unittest discover -s tools -p test_music_form.py -v
"""
import re
import unittest
import tempfile
from unittest.mock import patch
from pathlib import Path
import arrange_v11 as A
import motif as M
import export_song as E
class MusicFormTests(unittest.TestCase):
def test_exporter_preserves_current_score_and_check_is_read_only(self):
with tempfile.TemporaryDirectory(prefix="crtk-score-test-") as tmp:
output = Path(tmp) / "score.h"
self.assertEqual(E.main(["--output", str(output)]), 0)
self.assertEqual(output.read_text(encoding="utf-8"), A.header())
with patch.object(Path, "write_text", side_effect=AssertionError("check wrote a file")):
self.assertEqual(E.main(["--check", "--output", str(output)]), 0)
self.assertEqual(E.main(["--check", "--output", str(Path(tmp)/"missing.h")]), 1)
output.write_text("obsolete v10 score", encoding="utf-8")
with patch.object(Path, "write_text", side_effect=AssertionError("check wrote a file")):
self.assertEqual(E.main(["--check", "--output", str(output)]), 1)
def test_exact_form_and_clock(self):
self.assertEqual([(n,a,b) for n,a,b,_ in A.SECTIONS], [
("INTRO",0,1), ("SYNTHWAVE",2,7), ("METAL VERSE",8,11),
("CHORUS",12,15), ("SOLO",16,39), ("ARRIVAL",40,45), ("OUTRO",46,47)])
self.assertEqual([o for _,a,b,_ in A.SECTIONS for o in range(a,b+1)], list(range(48)))
source = (A.HERE.parent / "synth.h").read_text()
for name,value in (("SPR",5000),("SRATE",44100),("TPR",6),("ROWS",32),("ORDERS",48)):
self.assertRegex(source, rf"#define\s+{name}\s+{value}\b")
self.assertEqual(sum((t+1)*5000//6 - t*5000//6 for t in range(6)),5000)
self.assertEqual(A.ORDERS*A.ROWS*A.SPR,7680000)
self.assertAlmostEqual(A.ORDERS*A.ROWS*A.SPR/A.SRATE,174.149659864,places=8)
self.assertEqual(A.sect[:2], [0,0])
self.assertEqual(A.sect[46:], [10,10])
self.assertTrue(all(s not in (0,7,10) for s in A.sect[2:46]))
def test_no_duplicate_musical_orders(self):
# Exclude drums, metadata, gain and risers: percussion or a new label
# must not disguise a repeated arrangement. Include voiced harmony.
signatures = {}
for o in range(48):
sig = tuple(tuple(lane[o]) for lane in
(A.lead,A.solo,A.harm,A.bass,A.gtr,A.hold,A.root,A.ctyp))
sig += (A.arpo[o], A.orgm[o], A.syn[o])
self.assertNotIn(sig,signatures, f"duplicate orders {signatures.get(sig)} and {o}")
signatures[sig] = o
for lane,orders in ((A.solo,range(16,40)),(A.solo,range(40,46)),(A.lead,range(12,16))):
phrases = [tuple(lane[o]) for o in orders]
self.assertEqual(len(phrases),len(set(phrases)))
def test_dense_runs_and_lyrical_contrast(self):
counts = [sum(n>=0 for n in A.solo[o]) for o in range(16,40)]
self.assertGreaterEqual(sum(n>=30 for n in counts),9)
self.assertGreaterEqual(len(set(counts)),10)
rhythms = {tuple(r for r,n in enumerate(A.solo[o]) if n>=0) for o in range(16,40)}
self.assertGreaterEqual(len(rhythms),14)
for o in (*range(25,31),36,37,38):
longest = current = 0
for n in A.solo[o]:
current = current+1 if n>=0 else 0
longest = max(longest,current)
self.assertGreaterEqual(longest,28)
self.assertLess(max(counts[:4]),min(counts[4:9]))
# Lyrical figures explicitly refresh selected notes; rests aren't ties.
for o in range(20,25):
pitches = [n for n in A.solo[o] if n>=0]
self.assertTrue(any(a==b for a,b in zip(pitches,pitches[1:])))
self.assertEqual(A.solo[39][16:28],[-1]*12)
self.assertTrue(all(n>=0 for n in A.solo[39][28:32]))
def test_v8_contour_preserved_without_register_clamp(self):
expected = [57,59,60,62,64,65,67,69,67,65,64,62,60,59,57,55,
57,60,64,69,72,69,64,60,57,59,60,64,69,67,64,57]
self.assertEqual(A.solo[25],expected)
self.assertEqual(max(A.solo[38]),81)
self.assertEqual(A.solo[40][0],83)
self.assertEqual(M.deg(0),57) # A4 is MIDI 69 minus 12.
def test_pitch_scale_and_bass_riff_consonance(self):
for o in range(48):
key = 9 + (2 if o>=40 else 0)
scale = {(key+n)%12 for n in M.MIN_IV}
for lane in (A.lead,A.solo,A.harm,A.bass,A.gtr):
self.assertEqual(len(lane[o]),32)
for n in lane[o]:
self.assertTrue(n==-1 or 0<=n<=127)
if n>=0: self.assertIn(n%12,scale)
for ci,rt in enumerate(A.root[o]):
chord = {(rt+n)%12 for n in (0,4 if A.ctyp[o][ci] else 3,7)}
self.assertTrue(chord <= scale)
for r in range(32):
rt = A.root[o][r//8]
if A.bass[o][r]>=0: self.assertEqual(A.bass[o][r]%12,rt)
if A.gtr[o][r]>=0:
self.assertIn((A.gtr[o][r]-rt)%12,(0,7))
self.assertIn(A.gtr[o][r]%12,scale)
self.assertIn((A.gtr[o][r]+7)%12,scale)
self.assertGreaterEqual(A.gtr[o][r],21)
for o,r in ((8,26),(9,27),(10,28),(11,16),(11,20)):
self.assertEqual(A.gtr[o][r]%12,4) # E power chord, not B + F#
def test_drum_codes_preserve_kicks(self):
kick_codes, snare_codes, crash_codes = {1,6,7}, {2,7}, {5,6}
crashes = []
for o in range(48):
self.assertEqual(len(A.drum[o]),32)
for r,code in enumerate(A.drum[o]):
self.assertIn(code,range(8))
if code in crash_codes:
crashes.append((o,r))
self.assertIn(code,kick_codes)
if code==7:
self.assertIn(o,range(2,8))
self.assertIn(r,(4,12,20,28))
if 2<=o<=7:
for r in range(0,32,4):
self.assertIn(A.drum[o][r],kick_codes)
for r in (4,12,20,28):
self.assertIn(A.drum[o][r],snare_codes)
self.assertEqual(crashes,[(o,0) for o in (2,8,12,20,25,36,40)])
def test_one_foreground_owner(self):
for o in range(48):
active = [any(n>=0 for n in lane[o]) for lane in (A.lead,A.solo,A.gtr)]
self.assertLessEqual(sum(active),1)
self.assertEqual(A.arpo[o],-1) # no extra chip arp over synth arp
if A.orgm[o]==2 and active[1]:
self.assertIn(o,range(31,36))
self.assertGreaterEqual(min(n for n in A.solo[o] if n>=0),69)
self.assertFalse(active[0] or active[2])
if A.syn[o]:
self.assertIn(o,range(2,8))
self.assertFalse(any(active))
self.assertEqual(A.orgm[o],0)
def test_generated_header_matches_runtime_api(self):
text = (A.HERE.parent / "song_data.h").read_text(encoding="utf-8")
self.assertEqual(text,A.header())
parsed = {}
for typ,name,body in re.findall(r"static const (signed char|unsigned char|short) (g_sq\w+)\[\] = \{(.*?)\};",text,re.S):
parsed[name] = (typ,list(map(int,re.findall(r"-?\d+",body))))
expected_names = {"g_sqLead","g_sqSolo","g_sqHarm","g_sqBass","g_sqGtr","g_sqHold",
"g_sqDrum","g_sqRoot","g_sqType","g_sqArpOct","g_sqOrgMode",
"g_sqRiser","g_sqGain","g_sqSyn","g_sqSect"}
self.assertEqual(set(parsed),expected_names)
source = (A.HERE.parent / "synth.h").read_text()
self.assertEqual(set(re.findall(r"\bg_sq\w+",source)),expected_names)
for name,(typ,values) in parsed.items():
self.assertEqual((typ,values),(A.TABLES[name][0],A.flatten(A.TABLES[name][1])))
expected_size = 1536 if name in {"g_sqLead","g_sqSolo","g_sqHarm","g_sqBass","g_sqGtr","g_sqHold","g_sqDrum"} else 192 if name in {"g_sqRoot","g_sqType"} else 48
self.assertEqual(len(values),expected_size)
lo,hi = (-128,127) if typ=="signed char" else (0,255) if typ=="unsigned char" else (-32768,32767)
self.assertTrue(all(lo<=v<=hi for v in values))
if __name__ == "__main__":
unittest.main()

69
tools/verify_delivery.py Normal file
View file

@ -0,0 +1,69 @@
"""Verify final offline artifacts and record exact source/artifact hashes."""
from array import array
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import wave
ROOT = Path(__file__).resolve().parents[1]
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def main():
provenance = json.loads((ROOT / "export-provenance.json").read_text())
for name, digest in provenance.items():
assert sha(ROOT / name) == digest, f"Export no longer matches: {name}"
videos = [ROOT / name for name in provenance if name.lower().endswith(".mp4")]
assert len(videos) == 1, "Expected exactly one published video in provenance"
video_path = videos[0]
test = (ROOT / "gputest.txt").read_text()
if "failures: 0" not in test:
raise RuntimeError("Offline renderer tests have not passed")
with wave.open(str(ROOT / "dump.wav"), "rb") as wav:
frames, rate = wav.getnframes(), wav.getframerate()
assert (wav.getnchannels(), wav.getsampwidth(), rate) == (2, 2, 44100)
pcm = array("h", wav.readframes(frames))
if sys.byteorder != "little":
pcm.byteswap()
peak = max(abs(min(pcm)), abs(max(pcm)))
assert 0 < peak < 32767, f"Invalid/clipped PCM peak {peak}"
assert max(map(abs, pcm[-882:])) <= 8, "Final 10 ms must approach silence"
assert max(map(abs, pcm[:882])) <= 8, "Opening 10 ms must approach silence"
info = json.loads(subprocess.check_output([
"ffprobe", "-v", "error", "-show_streams", "-of", "json", str(video_path)]))
video = next(s for s in info["streams"] if s["codec_type"] == "video")
audio = next(s for s in info["streams"] if s["codec_type"] == "audio")
assert int(video["nb_frames"]) == (frames * 60 + rate - 1) // rate
assert (video["width"], video["height"], video["r_frame_rate"]) == (1280, 720, "60/1")
assert abs(float(audio["duration"]) - frames / rate) < .05
subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-xerror", "-i",
str(video_path), "-f", "null", "-"], check=True)
sources = [ROOT / "gfx.c", ROOT / "synth.h", ROOT / "voices.h", ROOT / "song_data.h",
ROOT / "shots.h", ROOT / "cats_mesh.h", ROOT / "tardis_mesh.h", ROOT / "c64_font.h", ROOT / "shaders.h"]
sources += sorted((ROOT / "fx").glob("*.hlsl")) + sorted((ROOT / "fx/out").glob("*.h"))
sources += sorted((ROOT / "fx").glob("*.hlsli"))
artifacts = [ROOT / name for name in ("CRTkafa.exe", "gfxvideo.exe", "gfxoffline.exe")]
artifacts += [video_path, ROOT / "dump.wav"]
# Generated headers are rewritten for every build, so freshness is checked
# against authored source, not the last build's identical generated files.
authored = [p for p in sources if p.name != "shaders.h" and p.parent.name != "out"]
newest = max(p.stat().st_mtime_ns for p in authored)
for p in artifacts[:3]:
assert p.stat().st_mtime_ns >= newest, f"Stale executable: {p.name}"
assert (ROOT / "gputest.txt").stat().st_mtime_ns >= (ROOT / "gfxoffline.exe").stat().st_mtime_ns
record = {"duration_seconds": frames / rate, "video_frames": int(video["nb_frames"]),
"pcm_peak": peak, "offline_failures": 0, "full_video_decode": "passed",
"interactive_gui_tested": False,
"sources": {str(p.relative_to(ROOT)): sha(p) for p in sources},
"artifacts": {p.name: {"bytes": p.stat().st_size, "sha256": sha(p)} for p in artifacts}}
(ROOT / "delivery.json").write_text(json.dumps(record, indent=2) + "\n")
print(json.dumps({k: v for k, v in record.items() if k not in ("sources", "artifacts")}, indent=2))
if __name__ == "__main__":
main()

1830
voices.h Normal file

File diff suppressed because it is too large Load diff