Isoline renderer: tile-binned compute rasterizer for the IsoSegment buffer (parked)

Six kernels (Args, Clear, Bin, Scan, Scatter, Shade) with exact-count tile lists,
union-distance prefiltered ink and glow, closed-form line density and depth-signed
flowing dashes. IsolineRenderer owns one view's extractor and tile buffers; nothing
in the frame calls it yet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-29 22:39:13 +01:00
commit eaa8f9e030
4 changed files with 655 additions and 0 deletions

View file

@ -0,0 +1,265 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
using static IsolineExtractor;
/// <summary>
/// The look of an isoline view (campaign aetheria-release, cut isoline-renderer): per family and shared values, in pixels
/// and world units, so a view's look does not change with its zoom except through Period and the width values the caller
/// chooses. Defaults reproduce the minimap's Minimap Gravity Lines.mat at the default minimap zoom (Settings.asset,
/// MinimapZoomLevels [250 500 1000 2000 4000], DefaultMinimapZoom 3 = 2000 u over 128 texels, so 31.25 u per texel).
/// </summary>
[Serializable]
public struct IsolineLook
{
[Serializable]
public struct Family
{
public Color Base; // hue at zero slope, linear HDR
public float W; // line width, pixels
public float Sigma; // prefilter sigma, pixels
public float G; // glow peak
public float SigmaG; // glow sigma, pixels
public float Period; // dash period along s, world units; 0 is solid
public float Duty; // share of the period that is ink
public float Speed; // periods per second, toward greater depth
public float Bloom; // brightness added per unit of line density above one
public float SigmaD; // density kernel sigma, pixels
}
public Family Contour, Ray;
public Color Danger;
public float DangerSteepness; // smoothstep upper edge of the danger blend
public float DangerSlope; // slope (depth per world unit) at which the danger blend reaches 1: _Scale 10 / 31.25 u per texel
public float RaySlope; // slope at which a ray reaches full brightness
public float Exposure;
/// <summary>The binning dilation R in pixels: the farthest any family's ink, glow or density reaches.</summary>
public float Dilation => Mathf.Max(Reach(Contour), Reach(Ray));
static float Reach(Family f) => Mathf.Max(0.5f * f.W + 3f * f.Sigma, Mathf.Max(3f * f.SigmaG, 3f * f.SigmaD));
// Values of Minimap Gravity Lines.mat: _Color (0, .4, .6), _AngleColor (1.498, 0, 1.2706) at alpha .5 (so rgb x .5),
// _DangerColor (2.670, .2237, 0), _DangerSteepness 1.5. The material's widths are in field texels (_LineWidth .15 to
// _LineWidth * _LineFade = .75 for contours); at the minimap's 2 px per texel that is a core about 0.6 px wide fading out
// by 3 px, which W 1.5 px with sigma 0.75 px matches. Its ray width is an angle (.05 of pi), so its pixel width grew
// with the radius: here a ray is as wide as a contour. Glow, bloom, the dash values and the density sigma are new.
public static IsolineLook Default => new IsolineLook
{
Contour = new Family
{
Base = new Color(0f, .4f, .6f), W = 1.5f, Sigma = .75f, G = .25f, SigmaG = 2.5f,
Period = 0f, Duty = 1f, Speed = 0f, Bloom = .5f, SigmaD = 3f
},
Ray = new Family
{
Base = new Color(.749f, 0f, .635f), W = 1.5f, Sigma = .75f, G = .2f, SigmaG = 2.5f,
Period = 160f, Duty = .5f, Speed = .35f, Bloom = .25f, SigmaD = 3f
},
Danger = new Color(2.670157f, .22367807f, 0f),
DangerSteepness = 1.5f,
DangerSlope = 10f / 31.25f,
RaySlope = 10f / 31.25f,
Exposure = 1f
};
}
/// <summary>
/// One view's isoline pass: the one owner of its IsolineExtractor and of the tile buffers. Record puts the extraction and
/// the six kernels of Assets/Shaders/IsolineRender.compute onto the caller's command buffer; nothing is read back and
/// nothing on the CPU draws, bins or edits a line. Nothing in the frame calls it yet.
/// </summary>
public sealed class IsolineRenderer
{
/// <summary>Words after the pool's capacity, left for a check that the scatter guard holds.</summary>
public const int PoolGuardWords = 16;
/// <summary>The plane in front of the eye, in clip w (the game cameras' near clip), that segments are clipped to.
/// Nearer, the pixel coordinates of a clipped end reach 1e6 and float precision costs a third of a pixel.</summary>
public const float NearW = 0.3f;
/// <summary>Most kernels Draw records: Args Clear Bin Scan Scatter Shade.</summary>
public const int KernelCount = 6;
static readonly int SegmentsId = Shader.PropertyToID("_Segments");
static readonly int CountId = Shader.PropertyToID("_Count");
static readonly int ArgsId = Shader.PropertyToID("_Args");
static readonly int ScreenId = Shader.PropertyToID("_Screen");
static readonly int TileCountId = Shader.PropertyToID("_TileCount");
static readonly int TileOffsetId = Shader.PropertyToID("_TileOffset");
static readonly int TileCursorId = Shader.PropertyToID("_TileCursor");
static readonly int PoolId = Shader.PropertyToID("_Pool");
static readonly int ScreenInId = Shader.PropertyToID("_ScreenIn");
static readonly int TileCountInId = Shader.PropertyToID("_TileCountIn");
static readonly int TileOffsetInId = Shader.PropertyToID("_TileOffsetIn");
static readonly int PoolInId = Shader.PropertyToID("_PoolIn");
static readonly int StatsId = Shader.PropertyToID("_Stats");
static readonly int TargetId = Shader.PropertyToID("_Target");
readonly ComputeShader _shader;
readonly IsolineExtractor _extractor;
readonly int _args, _clear, _bin, _scan, _scatter, _shade;
readonly LocalKeyword _raw;
readonly int _poolCapacity;
readonly GraphicsBuffer _screen, _argsBuffer;
GraphicsBuffer _tileCount, _tileOffset, _tileCursor;
int _tiles;
/// <summary>uint[6]: tile entries requested, entries written, truncated entries, segments drawn, extraction Count[0]
/// (written), extraction Count[1] (requested). Overflow of the extractor shows here without a readback in the
/// renderer: written below requested means the drawn subset is arbitrary, so capacity must never bind.</summary>
public GraphicsBuffer Stats { get; }
/// <summary>The tile lists' pool, poolCapacity entries and PoolGuardWords after them.</summary>
public GraphicsBuffer Pool { get; }
/// <summary>This renderer's extractor, the owner of the segments it draws from Record.</summary>
public IsolineExtractor Extractor => _extractor;
/// <summary>Smoke-only: a dilation in pixels used in place of the look's, or negative for the look's.</summary>
public float DilationOverride = -1f;
public IsolineRenderer(ComputeShader extract, ComputeShader render, int segmentCapacity, int poolCapacity)
{
_shader = render;
_poolCapacity = poolCapacity;
_extractor = new IsolineExtractor(extract, segmentCapacity);
_args = render.FindKernel("Args");
_clear = render.FindKernel("Clear");
_bin = render.FindKernel("Bin");
_scan = render.FindKernel("Scan");
_scatter = render.FindKernel("Scatter");
_shade = render.FindKernel("Shade");
_raw = new LocalKeyword(render, "ISOLINE_RAW");
_screen = new GraphicsBuffer(GraphicsBuffer.Target.Structured, segmentCapacity, 8 * sizeof(float));
_argsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments, 3, sizeof(uint));
Pool = new GraphicsBuffer(GraphicsBuffer.Target.Structured, poolCapacity + PoolGuardWords, sizeof(uint));
Stats = new GraphicsBuffer(GraphicsBuffer.Target.Structured, 6, sizeof(uint));
}
/// <summary>
/// Records the extraction of the field and the drawing of its segments. viewProjection is
/// GL.GetGPUProjectionMatrix(camera.projectionMatrix, true) * camera.worldToCameraMatrix; target is an ARGBHalf
/// enableRandomWrite texture in linear colour. Camera-general: orthographic or perspective.
/// </summary>
public void Record(CommandBuffer cmd, RenderTexture field, Vector2 worldOrigin, Vector2 worldPerTexel, IsolineLevels levels,
Matrix4x4 viewProjection, RenderTexture target, in IsolineLook look, float time)
{
_extractor.Extract(cmd, field, worldOrigin, worldPerTexel, levels);
Draw(cmd, _extractor.Segments, _extractor.Count, levels, viewProjection, target, look, time);
}
/// <summary>
/// Records the six kernels over a segment buffer and its Count (Count[0] drawn); Record calls it after Extract. Public
/// because the Editor assembly's smoke calls it with hand-made buffers. levels carries the contour depth range
/// the fades read. raw writes float4(D, h, s, dir) of rawFamily in place of the composite (smoke only: needs a float
/// target). stopAfter records only the first kernels (cost probes).
/// </summary>
public void Draw(CommandBuffer cmd, GraphicsBuffer segments, GraphicsBuffer count, IsolineLevels levels,
Matrix4x4 viewProjection, RenderTexture target, in IsolineLook look, float time, bool raw = false, int rawFamily = 0,
int stopAfter = KernelCount)
{
var tilesX = (target.width + 7) / 8;
var tilesY = (target.height + 7) / 8;
EnsureTiles(tilesX * tilesY);
var r = DilationOverride >= 0f ? DilationOverride : look.Dilation;
cmd.SetKeyword(_shader, _raw, raw);
cmd.SetComputeIntParams(_shader, "_Size", target.width, target.height);
cmd.SetComputeIntParams(_shader, "_Tiles", tilesX, tilesY);
cmd.SetComputeMatrixParam(_shader, "_ViewProj", viewProjection);
cmd.SetComputeFloatParam(_shader, "_YSign", SystemInfo.graphicsUVStartsAtTop ? -1f : 1f);
cmd.SetComputeFloatParam(_shader, "_NearW", NearW);
cmd.SetComputeIntParam(_shader, "_PoolCapacity", _poolCapacity);
cmd.SetComputeFloatParam(_shader, "_R", r);
cmd.SetComputeFloatParam(_shader, "_Time", time);
cmd.SetComputeIntParam(_shader, "_RawFamily", rawFamily);
cmd.SetComputeVectorArrayParam(_shader, "_Fam", new[]
{
Pack(look.Contour.Base, look.Contour.SigmaD), new Vector4(look.Contour.W, look.Contour.Sigma, look.Contour.G, look.Contour.SigmaG),
new Vector4(look.Contour.Period, look.Contour.Duty, look.Contour.Speed, look.Contour.Bloom),
Pack(look.Ray.Base, look.Ray.SigmaD), new Vector4(look.Ray.W, look.Ray.Sigma, look.Ray.G, look.Ray.SigmaG),
new Vector4(look.Ray.Period, look.Ray.Duty, look.Ray.Speed, look.Ray.Bloom)
});
cmd.SetComputeVectorParam(_shader, "_Shared", new Vector4(look.DangerSteepness, look.DangerSlope, look.RaySlope, look.Exposure));
cmd.SetComputeVectorParam(_shader, "_Danger", look.Danger);
cmd.SetComputeVectorParam(_shader, "_Levels", new Vector4(levels.Start, levels.Range, 0f, 0f));
var recorded = 0;
bool More() => ++recorded <= stopAfter;
if (More())
{
cmd.SetComputeBufferParam(_shader, _args, CountId, count);
cmd.SetComputeBufferParam(_shader, _args, ArgsId, _argsBuffer);
cmd.SetComputeBufferParam(_shader, _args, StatsId, Stats);
cmd.DispatchCompute(_shader, _args, 1, 1, 1);
}
if (More())
{
cmd.SetComputeBufferParam(_shader, _clear, TileCountId, _tileCount);
cmd.SetComputeBufferParam(_shader, _clear, TileCursorId, _tileCursor);
cmd.SetComputeBufferParam(_shader, _clear, StatsId, Stats);
cmd.DispatchCompute(_shader, _clear, (_tiles + 63) / 64, 1, 1);
}
if (More())
{
cmd.SetComputeBufferParam(_shader, _bin, SegmentsId, segments);
cmd.SetComputeBufferParam(_shader, _bin, CountId, count);
cmd.SetComputeBufferParam(_shader, _bin, ScreenId, _screen);
cmd.SetComputeBufferParam(_shader, _bin, TileCountId, _tileCount);
cmd.DispatchCompute(_shader, _bin, _argsBuffer, 0);
}
if (More())
{
cmd.SetComputeBufferParam(_shader, _scan, TileCountId, _tileCount);
cmd.SetComputeBufferParam(_shader, _scan, TileOffsetId, _tileOffset);
cmd.SetComputeBufferParam(_shader, _scan, StatsId, Stats);
cmd.DispatchCompute(_shader, _scan, 1, 1, 1);
}
if (More())
{
cmd.SetComputeBufferParam(_shader, _scatter, CountId, count);
cmd.SetComputeBufferParam(_shader, _scatter, ScreenId, _screen);
cmd.SetComputeBufferParam(_shader, _scatter, TileOffsetId, _tileOffset);
cmd.SetComputeBufferParam(_shader, _scatter, TileCursorId, _tileCursor);
cmd.SetComputeBufferParam(_shader, _scatter, PoolId, Pool);
cmd.SetComputeBufferParam(_shader, _scatter, StatsId, Stats);
cmd.DispatchCompute(_shader, _scatter, _argsBuffer, 0);
}
if (More())
{
cmd.SetComputeBufferParam(_shader, _shade, SegmentsId, segments);
cmd.SetComputeBufferParam(_shader, _shade, ScreenInId, _screen);
cmd.SetComputeBufferParam(_shader, _shade, TileCountInId, _tileCount);
cmd.SetComputeBufferParam(_shader, _shade, TileOffsetInId, _tileOffset);
cmd.SetComputeBufferParam(_shader, _shade, PoolInId, Pool);
cmd.SetComputeTextureParam(_shader, _shade, TargetId, target);
cmd.DispatchCompute(_shader, _shade, tilesX, tilesY, 1);
}
}
public void Release()
{
_extractor.Release();
_screen.Release();
_argsBuffer.Release();
Pool.Release();
Stats.Release();
_tileCount?.Release();
_tileOffset?.Release();
_tileCursor?.Release();
}
static Vector4 Pack(Color colour, float w) => new Vector4(colour.r, colour.g, colour.b, w);
void EnsureTiles(int tiles)
{
if (_tileCount != null && _tiles == tiles) return;
_tileCount?.Release();
_tileOffset?.Release();
_tileCursor?.Release();
_tiles = tiles;
_tileCount = new GraphicsBuffer(GraphicsBuffer.Target.Structured, tiles, sizeof(uint));
_tileOffset = new GraphicsBuffer(GraphicsBuffer.Target.Structured, tiles, sizeof(uint));
_tileCursor = new GraphicsBuffer(GraphicsBuffer.Target.Structured, tiles, sizeof(uint));
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 570454486c9d63c4c89abf148e24ff91

View file

@ -0,0 +1,381 @@
// The isoline renderer (campaign aetheria-release, cut isoline-renderer): draws one view's IsoSegment buffer
// (IsolineExtract.compute's output, IsolineSegment.hlsl) into a target texture. A tile-binned compute rasterizer:
//
// Args one thread: indirect dispatch args ceil(Count[0] / 64); Count[0] and Count[1] into Stats.
// Clear tile counts, cursors and the entry stats to zero.
// Bin per segment: project, clip to the near plane, store the ScreenSegment, count one entry per tile it reaches.
// Scan one 1024-thread group: exclusive prefix of the tile counts into offsets, the total into Stats.
// Scatter per segment: the same tile walk, writes the segment index at offset + cursor, guarded by the pool capacity.
// Shade one 8 x 8 group per 8 x 8-pixel tile, one thread per pixel, the tile's list read in groupshared chunks of 64.
//
// Allocation is exact (count, scan, scatter): there is no per-tile cap and no overflow look. Only Dispatch is used.
// Every pixel's ink is the family's union distance h (the minimum over the listed segments, never a sum), Gaussian-prefiltered
// into coverage; glow is a Gaussian of the same h; density is the closed-form Gaussian line integral, additive over a
// polyline's pieces, so a line counts one however many segments it is cut into.
//
// Screen convention: pixel (x, y) of the target, row 0 at the bottom of the image (Unity's uv.y = 0), pixel centres at +0.5.
// _YSign is -1 where the GPU projection matrix is flipped for render textures (UV starts at the top) and 1 elsewhere.
#pragma kernel Args
#pragma kernel Clear
#pragma kernel Bin
#pragma kernel Scan
#pragma kernel Scatter
#pragma kernel Shade
#pragma multi_compile_local _ ISOLINE_RAW
#include "IsolineSegment.hlsl"
struct ScreenSegment
{
float2 a, b; // pixel endpoints of the clipped segment
float wA, wB; // clip w at those endpoints (perspective-correct interpolation)
float t0, t1; // the clipped range of the world parameter; t0 > t1 marks a segment with nothing in front of the eye
};
#define TILE 8
#define NO_HIT 1e9
int2 _Size; // target size in pixels
int2 _Tiles; // tiles per axis
float4x4 _ViewProj;
float _YSign;
float _NearW; // the plane in front of the eye, in clip w, that segments are clipped to
uint _PoolCapacity;
float _R; // binning dilation in pixels
float _Time;
int _RawFamily;
// per family f: _Fam[3f] = (Base rgb, sigmaD); _Fam[3f+1] = (W, sigma, G, sigmaG); _Fam[3f+2] = (Period, Duty, Speed, Bloom)
float4 _Fam[6];
float4 _Shared; // DangerSteepness, DangerSlope, RaySlope, Exposure
float4 _Danger;
float2 _Levels; // Start, Range of the contour depth window
StructuredBuffer<IsoSegment> _Segments;
StructuredBuffer<uint> _Count;
RWByteAddressBuffer _Args;
RWStructuredBuffer<ScreenSegment> _Screen;
RWStructuredBuffer<uint> _TileCount;
RWStructuredBuffer<uint> _TileOffset;
RWStructuredBuffer<uint> _TileCursor;
RWStructuredBuffer<uint> _Pool;
RWStructuredBuffer<uint> _Stats; // 0 entries requested, 1 entries written, 2 truncated entries, 3 segments drawn, 4 and 5 the extraction's Count
// Shade reads the tile lists and screen segments as shader resource views, the buffers the earlier kernels wrote as unordered ones.
StructuredBuffer<uint> _TileCountIn;
StructuredBuffer<uint> _TileOffsetIn;
StructuredBuffer<uint> _PoolIn;
StructuredBuffer<ScreenSegment> _ScreenIn;
RWTexture2D<float4> _Target;
// ---- Args and Clear ---------------------------------------------------------------------------------------------------
[numthreads(1, 1, 1)]
void Args(uint3 id : SV_DispatchThreadID)
{
uint n = _Count[0];
_Args.Store3(0, uint3((n + 63u) / 64u, 1u, 1u));
_Stats[3] = n;
_Stats[4] = n;
_Stats[5] = _Count[1];
}
[numthreads(64, 1, 1)]
void Clear(uint3 id : SV_DispatchThreadID)
{
uint tiles = (uint)(_Tiles.x * _Tiles.y);
if (id.x < tiles)
{
_TileCount[id.x] = 0u;
_TileCursor[id.x] = 0u;
}
if (id.x < 3u) _Stats[id.x] = 0u;
}
// ---- projection and tile walk -----------------------------------------------------------------------------------------
float2 ToPixel(float4 c)
{
float2 ndc = c.xy / c.w;
return float2(ndc.x * 0.5 + 0.5, ndc.y * _YSign * 0.5 + 0.5) * (float2)_Size;
}
ScreenSegment Project(IsoSegment s)
{
ScreenSegment q;
float4 cA = mul(_ViewProj, float4(s.a.x, 0.0, s.a.y, 1.0));
float4 cB = mul(_ViewProj, float4(s.b.x, 0.0, s.b.y, 1.0));
float dA = cA.w - _NearW;
float dB = cB.w - _NearW;
float t0 = 0.0, t1 = 1.0;
if (dA < 0.0 && dB < 0.0) { t0 = 1.0; t1 = 0.0; }
else if (dA < 0.0) t0 = dA / (dA - dB);
else if (dB < 0.0) t1 = dA / (dA - dB);
float4 c0 = lerp(cA, cB, t0);
float4 c1 = lerp(cA, cB, t1);
q.t0 = t0;
q.t1 = t1;
q.wA = max(c0.w, _NearW);
q.wB = max(c1.w, _NearW);
q.a = ToPixel(float4(c0.xy, 0.0, q.wA));
q.b = ToPixel(float4(c1.xy, 0.0, q.wB));
return q;
}
// Distance from p to the segment a-b.
float SegDistance(float2 p, float2 a, float2 b)
{
float2 d = b - a;
float l2 = dot(d, d);
float u = l2 > 1e-12 ? saturate(dot(p - a, d) / l2) : 0.0;
return length(p - (a + d * u));
}
// Tile range a segment can reach: its pixel box dilated by R and a tile's half-diagonal. Empty when min > max.
int4 TileBox(ScreenSegment q)
{
float reach = _R + 6.0;
float2 lo = min(q.a, q.b) - reach;
float2 hi = max(q.a, q.b) + reach;
if (hi.x < 0.0 || hi.y < 0.0 || lo.x > _Size.x || lo.y > _Size.y) return int4(1, 1, 0, 0);
int2 tlo = (int2)clamp(floor(lo / TILE), 0.0, (float2)(_Tiles - 1));
int2 thi = (int2)clamp(floor(hi / TILE), 0.0, (float2)(_Tiles - 1));
return int4(tlo, thi);
}
// A tile is entered only if its centre lies within the tile's half-diagonal plus R of the pixel segment.
bool TileHit(ScreenSegment q, int2 tile)
{
float2 centre = (float2)tile * TILE + TILE * 0.5;
return SegDistance(centre, q.a, q.b) <= TILE * 0.70711 + _R;
}
[numthreads(64, 1, 1)]
void Bin(uint3 id : SV_DispatchThreadID)
{
if (id.x >= _Count[0]) return;
ScreenSegment q = Project(_Segments[id.x]);
_Screen[id.x] = q;
if (q.t0 > q.t1) return;
int4 box = TileBox(q);
for (int ty = box.y; ty <= box.w; ty++)
for (int tx = box.x; tx <= box.z; tx++)
if (TileHit(q, int2(tx, ty)))
InterlockedAdd(_TileCount[ty * _Tiles.x + tx], 1u);
}
groupshared uint gScan[1024];
[numthreads(1024, 1, 1)]
void Scan(uint3 tid : SV_GroupThreadID)
{
uint tiles = (uint)(_Tiles.x * _Tiles.y);
uint per = (tiles + 1023u) / 1024u;
uint first = min(tid.x * per, tiles);
uint last = min(first + per, tiles);
uint sum = 0u;
for (uint i = first; i < last; i++) sum += _TileCount[i];
gScan[tid.x] = sum;
GroupMemoryBarrierWithGroupSync();
// Hillis-Steele inclusive scan of the 1024 partial sums
for (uint stride = 1u; stride < 1024u; stride <<= 1u)
{
uint add = tid.x >= stride ? gScan[tid.x - stride] : 0u;
GroupMemoryBarrierWithGroupSync();
gScan[tid.x] += add;
GroupMemoryBarrierWithGroupSync();
}
uint running = gScan[tid.x] - sum;
for (uint j = first; j < last; j++)
{
_TileOffset[j] = running;
running += _TileCount[j];
}
if (tid.x == 1023u) _Stats[0] = gScan[1023];
}
[numthreads(64, 1, 1)]
void Scatter(uint3 id : SV_DispatchThreadID)
{
if (id.x >= _Count[0]) return;
ScreenSegment q = _Screen[id.x];
if (q.t0 > q.t1) return;
int4 box = TileBox(q);
uint written = 0u, truncated = 0u;
for (int ty = box.y; ty <= box.w; ty++)
for (int tx = box.x; tx <= box.z; tx++)
if (TileHit(q, int2(tx, ty)))
{
uint tile = (uint)(ty * _Tiles.x + tx);
uint slot = _TileOffset[tile];
uint taken;
InterlockedAdd(_TileCursor[tile], 1u, taken);
slot += taken;
if (slot < _PoolCapacity) { _Pool[slot] = id.x; written++; }
else truncated++;
}
if (written > 0u) InterlockedAdd(_Stats[1], written);
if (truncated > 0u) InterlockedAdd(_Stats[2], truncated);
}
// ---- Shade ------------------------------------------------------------------------------------------------------------
// Abramowitz and Stegun 7.1.26, |error| < 1.5e-7.
float Erf(float x)
{
float s = x < 0.0 ? -1.0 : 1.0;
x = abs(x);
float t = 1.0 / (1.0 + 0.3275911 * x);
float y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-x * x);
return s * y;
}
// Integral of a square wave of the given duty (period 1, on from 0 to duty) from 0 to x.
float SquareIntegral(float x, float duty)
{
float whole = floor(x);
return whole * duty + min(x - whole, duty);
}
// The square wave averaged over a box of width w centred on x: antialiased exactly.
float Dash(float x, float w, float duty)
{
w = max(w, 1e-4);
return (SquareIntegral(x + 0.5 * w, duty) - SquareIntegral(x - 0.5 * w, duty)) / w;
}
struct Hit
{
float s, slope, depth, dir, dsdp;
};
// The argmin segment's attributes at the nearest point, perspective-correct: u is the pixel-space fraction along the clipped
// segment, tau the matching fraction of the clipped world range (1/w is linear in u).
Hit Resolve(uint index, float u)
{
IsoSegment g = _Segments[index];
ScreenSegment q = _ScreenIn[index];
float denominator = u * q.wA + (1.0 - u) * q.wB;
float tau = u * q.wA / denominator;
float t = lerp(q.t0, q.t1, tau);
Hit r;
r.s = lerp(g.sA, g.sB, t);
r.slope = lerp(g.slopeA, g.slopeB, t);
r.depth = lerp(g.depthA, g.depthB, t);
// motion toward greater depth: the sign of the depth change along +s (isoline-flow-direction-from-depth)
r.dir = sign((g.sB - g.sA) * (g.depthB - g.depthA));
float length_ = max(length(q.b - q.a), 1e-3);
float dtauDu = q.wA * q.wB / (denominator * denominator);
r.dsdp = abs(g.sB - g.sA) * (q.t1 - q.t0) * dtauDu / length_;
return r;
}
groupshared float4 gGeom[64];
groupshared uint gFamily[64];
groupshared uint gIndex[64];
// One family's share of a pixel's light: its argmin segment's ink, glow and the density bloom. Writes the smoke-only raw
// reading when asked.
float3 FamilyLight(uint f, float h, float u, uint index, float density)
{
Hit hit = Resolve(index, u);
float4 baseColour = _Fam[f * 3u];
float4 shape = _Fam[f * 3u + 1u];
float4 dash = _Fam[f * 3u + 2u];
float sigma = max(shape.y, 1e-3);
float sigmaG = max(shape.w, 1e-3);
float coverage = 0.5 * (Erf((h + 0.5 * shape.x) / (sigma * 1.41421356)) - Erf((h - 0.5 * shape.x) / (sigma * 1.41421356)));
float glow = shape.z * exp(-h * h / (2.0 * sigmaG * sigmaG));
float pattern = 1.0;
if (dash.x > 0.0)
pattern = Dash(hit.s / dash.x - hit.dir * dash.z * _Time, hit.dsdp / dash.x, dash.y);
float danger = smoothstep(0.0, _Shared.x, pow(hit.slope / _Shared.y, 2.0));
float3 hue = lerp(baseColour.rgb, _Danger.rgb, danger);
float fade = smoothstep(_Levels.x, _Levels.x + _Levels.y / 32.0, hit.depth);
if (f == ISO_FAMILY_RAY)
fade *= (1.0 - smoothstep(_Levels.x, _Levels.x + _Levels.y, hit.depth)) * hit.slope / _Shared.z;
return hue * fade * (coverage * pattern + glow + dash.w * max(density - 1.0, 0.0));
}
[numthreads(8, 8, 1)]
void Shade(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID, uint3 id : SV_DispatchThreadID)
{
uint tile = gid.y * (uint)_Tiles.x + gid.x;
uint lane = tid.y * 8u + tid.x;
uint start = _TileOffsetIn[tile];
uint count = min(_TileCountIn[tile], _PoolCapacity > start ? _PoolCapacity - start : 0u);
float2 p = (float2)id.xy + 0.5;
// per family (contour, ray): nearest distance, its fraction along the segment, its index, and the density sum
float h0 = NO_HIT, h1 = NO_HIT;
float u0 = 0.0, u1 = 0.0;
uint i0 = 0u, i1 = 0u;
float d0 = 0.0, d1 = 0.0;
for (uint chunk = 0u; chunk < count; chunk += 64u)
{
uint e = chunk + lane;
if (e < count)
{
uint si = _PoolIn[start + e];
ScreenSegment q = _ScreenIn[si];
gGeom[lane] = float4(q.a, q.b);
gFamily[lane] = IsoFamily(_Segments[si].key);
gIndex[lane] = si;
}
GroupMemoryBarrierWithGroupSync();
uint n = min(64u, count - chunk);
for (uint k = 0u; k < n; k++)
{
float2 a = gGeom[k].xy;
float2 b = gGeom[k].zw;
float2 d = b - a;
float len = length(d);
float2 dn = len > 1e-6 ? d / len : float2(1.0, 0.0);
float v = dot(p - a, dn);
float vc = clamp(v, 0.0, len);
float h = length(p - (a + dn * vc));
float uu = len > 1e-6 ? vc / len : 0.0;
// Gaussian line integral: the perpendicular distance's kernel times the share of the line's mass within the ends
float perp = dn.x * (p.y - a.y) - dn.y * (p.x - a.x);
if (gFamily[k] == 0u)
{
float sigmaD = max(_Fam[0].w, 1e-3);
float k2 = 1.0 / (sigmaD * 1.41421356);
d0 += exp(-perp * perp / (2.0 * sigmaD * sigmaD)) * 0.5 * (Erf((len - v) * k2) - Erf(-v * k2));
if (h < h0) { h0 = h; u0 = uu; i0 = gIndex[k]; }
}
else
{
float sigmaD = max(_Fam[3].w, 1e-3);
float k2 = 1.0 / (sigmaD * 1.41421356);
d1 += exp(-perp * perp / (2.0 * sigmaD * sigmaD)) * 0.5 * (Erf((len - v) * k2) - Erf(-v * k2));
if (h < h1) { h1 = h; u1 = uu; i1 = gIndex[k]; }
}
}
GroupMemoryBarrierWithGroupSync();
}
if (id.x >= (uint)_Size.x || id.y >= (uint)_Size.y) return;
#ifdef ISOLINE_RAW
// float4(D, h, s at the nearest point, dir of the nearest segment) of the family the smoke names
bool ray = _RawFamily != 0;
float h = ray ? h1 : h0;
float4 raw = float4(ray ? d1 : d0, h, 0.0, 0.0);
if (h < NO_HIT)
{
Hit hit = Resolve(ray ? i1 : i0, ray ? u1 : u0);
raw.z = hit.s;
raw.w = hit.dir;
}
_Target[id.xy] = raw;
#else
float3 light = 0.0;
if (h0 < NO_HIT) light += FamilyLight(0u, h0, u0, i0, d0);
if (h1 < NO_HIT) light += FamilyLight(1u, h1, u1, i1, d1);
float3 toned = 1.0 - exp(-_Shared.w * light);
float alpha = max(toned.r, max(toned.g, toned.b));
_Target[id.xy] = alpha > 0.0 ? float4(toned / alpha, alpha) : 0.0;
#endif
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2ee6aee2e7c44b04596a297e59623668
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: