コミットを比較

17 コミット
作成者 SHA1 メッセージ 日付
routersys aec9eb73cc バージョンをv1.0.1へ上げる
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.0.1 のコミットから作成しました
2026-10-25 11:17:05 +09:00
routersys bb341dc4bd 格子への振り分けの長い引数を行ごとに分ける 2026-10-25 11:09:21 +09:00
routersys 4c2fb33b3c 最初の有効な角を選ぶ処理を関数にまとめる 2026-10-25 11:05:40 +09:00
routersys bc64831464 格子への振り分けの関数と変数の名前を改める 2026-10-25 11:04:11 +09:00
routersys 3c480fd289 格子への振り分けをCrystalScatterから分ける 2026-10-25 11:01:20 +09:00
routersys b9c3e3ac97 断面ごとの光線の追跡をCrystalScatterから分ける 2026-10-25 10:56:41 +09:00
routersys dd70dc5245 結晶の向きの分布をCrystalScatterから分ける 2026-10-25 10:53:04 +09:00
routersys 44ee168572 回転の周期を側面の数から導く 2026-10-25 10:49:13 +09:00
routersys fb1b7178bc 側面の角度を側面の数から導く 2026-10-25 10:46:15 +09:00
routersys 1aad2c3ff7 面と出口の番号を側面の数から導く 2026-10-25 10:44:27 +09:00
routersys 755172b324 散乱の表の全ての行の試験を追加する 2026-10-25 09:54:30 +09:00
routersys 0946630a61 太陽が天頂と水平線にある場合のケースと基準値を加える 2026-10-24 16:32:01 +09:00
routersys d80f20a9c4 格子の合計の試験を追加する 2026-10-24 16:27:33 +09:00
routersys 9f10f7f88c 作業ごとの格子の合計を並列に求める
・太陽の高度などを動かしたときの幻日とタンジェントアークの計算を高速化-M
2026-10-24 16:27:32 +09:00
routersys ff989e0488 光の振り分けで繰り返し使う値を先に求める
・幻日とタンジェントアークの計算を高速化-M
2026-10-24 16:24:44 +09:00
routersys 5fd0ecbcd5 プリズムの断面ごとに角の合成を一度だけ行う
・幻日の計算を高速化-M
2026-10-24 16:22:59 +09:00
routersys 59bf986f99 散乱の表の合成を行ごとに並列化する
・視直径や彩度などを動かしたときの幻日とタンジェントアークの準備を高速化-M
2026-10-24 16:11:39 +09:00
15個のファイルの変更、464行の追加、328行の削除

検索条件に一致するファイルはありません

+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
========================================
ハロ for YMM4 v1.0.0
ハロ for YMM4 v1.0.1
========================================
YukkuriMovieMaker4上で動作する、
太陽の高度とカメラの向きから、空に浮かぶ六角柱の氷晶を光が通る経路を求め、
+4
ファイルの表示
@@ -31,6 +31,10 @@ internal static class HarnessCases
yield return ("column-arcs-0", Create(effect => effect.ColumnArcs.Values[0].Value = 0), [0]);
yield return ("plate-halos-only", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 100; }), [0]);
yield return ("column-arcs-only", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 100; }), [0]);
yield return ("plate-halos-only-zenith", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 100; effect.SunElevation.Values[0].Value = 90; effect.CameraPitch.Values[0].Value = 90; }), [0]);
yield return ("column-arcs-only-zenith", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 100; effect.SunElevation.Values[0].Value = 90; effect.CameraPitch.Values[0].Value = 90; }), [0]);
yield return ("plate-halos-only-horizon", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 100; effect.SunElevation.Values[0].Value = 0; effect.CameraPitch.Values[0].Value = 0; }), [0]);
yield return ("column-arcs-only-horizon", Create(effect => { effect.RandomHalos.Values[0].Value = 0; effect.PlateHalos.Values[0].Value = 0; effect.ColumnArcs.Values[0].Value = 100; effect.SunElevation.Values[0].Value = 0; effect.CameraPitch.Values[0].Value = 0; }), [0]);
yield return ("plate-thickness-0.05", Create(effect => effect.PlateThickness.Values[0].Value = 0.05), [0]);
yield return ("plate-thickness-1", Create(effect => effect.PlateThickness.Values[0].Value = 1), [0]);
yield return ("column-length-1", Create(effect => effect.ColumnLength.Values[0].Value = 1), [0]);
+28
ファイルの表示
@@ -174,6 +174,34 @@
],
"hash": "AC82CBF713F74760931D8D0771B4DF89E735B5DF12167993D17E95B016B01B8B"
},
{
"name": "plate-halos-only-zenith",
"frames": [
0
],
"hash": "708C73B53F9DB54D5A588CAFA16285943B7C7F05914019F9D46998D590BE161A"
},
{
"name": "column-arcs-only-zenith",
"frames": [
0
],
"hash": "0C93191EFEDF8E72370DBA648A62884FD42B1350F45D31EECC78B67ADEAF5FD7"
},
{
"name": "plate-halos-only-horizon",
"frames": [
0
],
"hash": "A0BBDAEFA9D6E034E24FC609328D3FEF35AF16181EBE72DC5111FC4FF044D1A7"
},
{
"name": "column-arcs-only-horizon",
"frames": [
0
],
"hash": "A18FCC2F7E56A361AA5DE1BE51CAD961968792DAF6518D18FDDE26CD048E89B7"
},
{
"name": "plate-thickness-0.05",
"frames": [
+14
ファイルの表示
@@ -344,6 +344,20 @@ public sealed class HaloTableTests
Assert.Equal(middle, Value(texels, 100 * ScatterGrid.Width + 300, 1), middle * 0.01f);
}
[Theory]
[InlineData(0.0)]
[InlineData(2.0)]
public void EveryRowOfTheScatterTableIsComposed(double diameter)
{
const int margin = 30;
var texels = HaloTable.ComposeScatter(Filled(0.01), Empty(), 1.0, 0.0, 20.0, diameter, 1.0);
var middle = Value(texels, 133 * ScatterGrid.Width + 300, 1);
Assert.True(middle > 0f);
Assert.All(Enumerable.Range(margin * ScatterGrid.Width, (ScatterGrid.Height - 2 * margin) * ScatterGrid.Width), texel =>
Assert.Equal(middle, Value(texels, texel, 1), middle * 0.01f));
}
[Fact]
public void ALightOnTheAzimuthEdgeIsReflectedIntoTheNeighbouringTexel()
{
+23
ファイルの表示
@@ -61,6 +61,29 @@ public sealed class ScatterGridTests
Assert.Equal(0.0, Total(grid));
}
[Fact]
public void TheSumOfGridsAddsEveryCellOfEveryGrid()
{
var first = new ScatterGrid();
var second = new ScatterGrid();
for (var row = 0; row < ScatterGrid.Height; row++)
{
for (var column = 0; column < ScatterGrid.Width; column++)
{
var azimuth = (column + 0.5) * HaloSettings.ScatterTexelDegrees;
var elevation = -HaloSettings.ScatterElevationHalfSpanDegrees + (row + 0.5) * HaloSettings.ScatterTexelDegrees;
first.Splat(azimuth, elevation, Unit);
second.Splat(azimuth + 0.1, elevation + 0.1, new Tristimulus(2.0, 0.5, 3.0));
}
}
var total = ScatterGrid.Sum([first, second, new ScatterGrid()]);
var expected = first.Cells.Zip(second.Cells, (left, right) => left + right).ToArray();
Assert.Contains(expected, cell => cell != 0);
Assert.True(total.Cells.AsSpan().SequenceEqual(expected));
}
[Fact]
public void AnAzimuthPastHalfATurnFoldsBackIntoTheTable()
{
+43
ファイルの表示
@@ -0,0 +1,43 @@
namespace Halo;
internal readonly record struct TiltLayer(double Tilt, double Weight);
internal readonly record struct StripChunk(TiltLayer Layer, int FirstStrip, int StripCount);
internal static class CrystalOrientations
{
public static StripChunk[] BuildChunks(TiltLayer[] layers, int azimuthSteps)
{
var chunks = new List<StripChunk>();
foreach (var layer in layers)
{
for (var strip = 0; strip < azimuthSteps; strip += HaloSettings.StripsPerTask)
chunks.Add(new StripChunk(layer, strip, Math.Min(HaloSettings.StripsPerTask, azimuthSteps - strip)));
}
return [.. chunks];
}
public static TiltLayer[] PlateLayers(double tiltDegrees)
{
var nodes = HaloSettings.PlateTiltRadialNodes;
var tilt = tiltDegrees * HaloSettings.RadiansPerDegree;
var layers = new TiltLayer[nodes];
for (var node = 0; node < nodes; node++)
layers[node] = new TiltLayer(tilt * HaloSettings.GetPlateTiltQuantile(node), 1.0 / nodes);
return layers;
}
public static TiltLayer[] ColumnLayers(double tiltDegrees)
{
var quantiles = HaloSettings.ColumnTiltQuantiles;
var tilt = tiltDegrees * HaloSettings.RadiansPerDegree;
return [.. quantiles.Select(quantile => new TiltLayer(tilt * quantile, 1.0 / quantiles.Length))];
}
public static Vec3 PlateAxis(double tilt, double azimuth)
=> new(Math.Sin(tilt) * Math.Cos(azimuth), Math.Sin(tilt) * Math.Sin(azimuth), Math.Cos(tilt));
public static Vec3 ColumnAxis(double tilt, double azimuth)
=> new(Math.Cos(tilt) * Math.Cos(azimuth), Math.Cos(tilt) * Math.Sin(azimuth), Math.Sin(tilt));
}
+11 -306
ファイルの表示
@@ -1,5 +1,3 @@
using System.Runtime.CompilerServices;
namespace Halo;
internal enum CrystalFamily
@@ -10,68 +8,10 @@ internal enum CrystalFamily
internal static class CrystalScatter
{
private const double SpinPeriodRadians = Math.PI / 3.0;
private const double HalfTurnDegrees = 180.0;
private const double FullTurnDegrees = 360.0;
private const double MergeSpreadDegrees = 0.075;
private readonly record struct Layer(double Tilt, double Weight);
private readonly record struct Chunk(Layer Layer, int FirstStrip, int StripCount);
private struct Sample
{
public double Azimuth;
public double Elevation;
public double Weight;
public bool Valid;
}
private struct Corner
{
public bool Valid;
public double Azimuth;
public double Elevation;
public double Spread;
public Tristimulus Weight;
}
private sealed class SliceData(int nodeCount, SpectralBand[] bands)
{
public SpectralBand[] Bands { get; } = bands;
public int WavelengthCount { get; } = bands.Length;
public PrismPath[][] Paths { get; } = Enumerable.Range(0, nodeCount).Select(_ => new PrismPath[PrismGeometry.MaximumPathCount]).ToArray();
public int[] PathCounts { get; } = new int[nodeCount];
public Vec3[] Incoming { get; } = new Vec3[nodeCount];
public Vec3[] FirstAxes { get; } = new Vec3[nodeCount];
public Vec3[] SecondAxes { get; } = new Vec3[nodeCount];
public Sample[] Samples { get; } = new Sample[PrismGeometry.LabelCount * nodeCount * bands.Length];
public bool[] Used { get; } = new bool[PrismGeometry.LabelCount];
private int NodeCount { get; } = nodeCount;
public int Slot(int label, int node, int wavelength)
=> (label * NodeCount + node) * WavelengthCount + wavelength;
public void Reset()
{
for (var label = 0; label < Used.Length; label++)
{
if (!Used[label])
continue;
Array.Clear(Samples, label * NodeCount * WavelengthCount, NodeCount * WavelengthCount);
Used[label] = false;
}
}
public ReadOnlySpan<Sample> Wavelengths(int label, int node)
=> Samples.AsSpan((label * NodeCount + node) * WavelengthCount, WavelengthCount);
}
private sealed class Workspace(int nodeCount, SpectralBand[] bands)
{
public ScatterGrid Grid { get; } = new();
public SliceData[] Slices { get; } = [new(nodeCount, bands), new(nodeCount, bands)];
public StripSlice[] Slices { get; } = [new(nodeCount, bands), new(nodeCount, bands)];
}
public static float[] Integrate(CrystalFamily family, double sunElevationDegrees, double lengthRatio, double tiltDegrees)
@@ -83,10 +23,10 @@ internal static class CrystalScatter
var length = 2.0 * lengthRatio;
var elevation = sunElevationDegrees * HaloSettings.RadiansPerDegree;
var incoming = new Vec3(-Math.Cos(elevation), 0.0, -Math.Sin(elevation));
var layers = plate ? PlateLayers(tiltDegrees) : ColumnLayers(tiltDegrees);
var chunks = BuildChunks(layers, azimuthSteps);
var layers = plate ? CrystalOrientations.PlateLayers(tiltDegrees) : CrystalOrientations.ColumnLayers(tiltDegrees);
var chunks = CrystalOrientations.BuildChunks(layers, azimuthSteps);
var bands = SolarSpectrum.Bands(plate ? 1 : HaloSettings.ColumnWavelengthStride);
var total = new ScatterGrid();
var grids = new System.Collections.Concurrent.ConcurrentBag<ScatterGrid>();
Parallel.For(
0,
chunks.Length,
@@ -99,258 +39,23 @@ internal static class CrystalScatter
{
var current = workspace.Slices[strip & 1];
var azimuth = (chunk.FirstStrip + strip) * Math.PI / azimuthSteps;
var axis = plate ? PlateAxis(chunk.Layer.Tilt, azimuth) : ColumnAxis(chunk.Layer.Tilt, azimuth);
FillSlice(current, axis, incoming, length, spinSteps, kinds, sunElevationDegrees);
var axis = plate ? CrystalOrientations.PlateAxis(chunk.Layer.Tilt, azimuth) : CrystalOrientations.ColumnAxis(chunk.Layer.Tilt, azimuth);
current.Fill(axis, incoming, length, kinds, sunElevationDegrees);
if (strip > 0)
SplatStrip(workspace.Grid, workspace.Slices[(strip - 1) & 1], current, spinSteps, quadWeight);
ScatterSplat.Strip(workspace.Grid, workspace.Slices[(strip - 1) & 1], current, quadWeight);
}
return workspace;
},
workspace =>
{
lock (total)
total.Add(workspace.Grid);
});
return ToRadiance(total, sunElevationDegrees);
workspace => grids.Add(workspace.Grid));
return ToRadiance(ScatterGrid.Sum([.. grids]), sunElevationDegrees);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void FillSlice(SliceData data, Vec3 axis, Vec3 incoming, double length, int spinSteps, PathKinds kinds, double sunElevationDegrees)
{
var referenceIndex = IceOptics.RefractiveIndex(HaloSettings.ReferenceWavelengthNanometers);
var helper = Math.Abs(axis.Z) < 0.9 ? new Vec3(0.0, 0.0, 1.0) : new Vec3(1.0, 0.0, 0.0);
var firstBase = helper.Cross(axis).Normalized();
var secondBase = axis.Cross(firstBase);
for (var node = 0; node <= spinSteps; node++)
{
var (sine, cosine) = Math.SinCos(node * SpinPeriodRadians / spinSteps);
var first = (cosine * firstBase) + (sine * secondBase);
var second = (-sine * firstBase) + (cosine * secondBase);
data.FirstAxes[node] = first;
data.SecondAxes[node] = second;
var local = new Vec3(incoming.Dot(first), incoming.Dot(second), incoming.Dot(axis));
data.Incoming[node] = local;
data.PathCounts[node] = PrismGeometry.Enumerate(local, length, referenceIndex, kinds, data.Paths[node]);
}
data.Reset();
for (var wavelength = 0; wavelength < data.WavelengthCount; wavelength++)
{
var index = IceOptics.RefractiveIndex(data.Bands[wavelength].Wavelength);
for (var node = 0; node <= spinSteps; node++)
{
var paths = data.Paths[node];
for (var path = 0; path < data.PathCounts[node]; path++)
{
var current = paths[path];
Vec3 exit;
double factor;
var found = current.Exit == PrismGeometry.ReflectionExit
? PrismGeometry.TryReflect(data.Incoming[node], current, index, out exit, out factor)
: PrismGeometry.TryRefract(data.Incoming[node], current, index, out exit, out factor);
if (!found)
continue;
var sky = -((exit.X * data.FirstAxes[node]) + (exit.Y * data.SecondAxes[node]) + (exit.Z * axis));
data.Samples[data.Slot(current.Label, node, wavelength)] = new Sample
{
Azimuth = Math.Atan2(sky.Y, sky.X) / HaloSettings.RadiansPerDegree,
Elevation = Math.Asin(Math.Clamp(sky.Z, -1.0, 1.0)) / HaloSettings.RadiansPerDegree - sunElevationDegrees,
Weight = current.Geometry * factor,
Valid = true,
};
data.Used[current.Label] = true;
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void SplatStrip(ScatterGrid grid, SliceData previous, SliceData current, int spinSteps, double quadWeight)
{
for (var label = 0; label < PrismGeometry.LabelCount; label++)
{
if (!previous.Used[label] && !current.Used[label])
continue;
for (var node = 0; node < spinSteps; node++)
{
SplatQuad(
grid,
previous.Bands,
previous.Wavelengths(label, node),
previous.Wavelengths(label, node + 1),
current.Wavelengths(label, node),
current.Wavelengths(label, node + 1),
quadWeight);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void SplatQuad(ScatterGrid grid, SpectralBand[] bands, ReadOnlySpan<Sample> first, ReadOnlySpan<Sample> second, ReadOnlySpan<Sample> third, ReadOnlySpan<Sample> fourth, double quadWeight)
{
var c00 = Combine(first, bands);
var c01 = Combine(second, bands);
var c10 = Combine(third, bands);
var c11 = Combine(fourth, bands);
var anchor = c00.Valid ? c00 : c01.Valid ? c01 : c10.Valid ? c10 : c11;
if (!anchor.Valid)
return;
if (c00.Spread <= MergeSpreadDegrees && c01.Spread <= MergeSpreadDegrees && c10.Spread <= MergeSpreadDegrees && c11.Spread <= MergeSpreadDegrees)
{
SplatPatch(grid, Complete(c00, anchor), Complete(c01, anchor), Complete(c10, anchor), Complete(c11, anchor), quadWeight);
return;
}
for (var wavelength = 0; wavelength < bands.Length; wavelength++)
{
var spectrum = bands[wavelength].Weight;
var single00 = Single(first[wavelength], spectrum);
var single01 = Single(second[wavelength], spectrum);
var single10 = Single(third[wavelength], spectrum);
var single11 = Single(fourth[wavelength], spectrum);
var single = single00.Valid ? single00 : single01.Valid ? single01 : single10.Valid ? single10 : single11;
if (single.Valid)
SplatPatch(grid, Complete(single00, single), Complete(single01, single), Complete(single10, single), Complete(single11, single), quadWeight);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static Corner Combine(ReadOnlySpan<Sample> samples, SpectralBand[] bands)
{
var total = new Tristimulus();
var luminance = 0.0;
var azimuth = 0.0;
var elevation = 0.0;
var reference = double.NaN;
for (var wavelength = 0; wavelength < samples.Length; wavelength++)
{
var sample = samples[wavelength];
if (!sample.Valid)
continue;
if (double.IsNaN(reference))
reference = sample.Azimuth;
var weight = sample.Weight * bands[wavelength].Weight.Y;
total += sample.Weight * bands[wavelength].Weight;
luminance += weight;
azimuth += weight * Unwrap(sample.Azimuth, reference);
elevation += weight * sample.Elevation;
}
if (double.IsNaN(reference))
return default;
if (luminance <= 0.0)
return new Corner { Valid = true, Azimuth = reference };
var center = new Corner { Valid = true, Azimuth = azimuth / luminance, Elevation = elevation / luminance, Weight = total };
var spread = 0.0;
for (var wavelength = 0; wavelength < samples.Length; wavelength++)
{
if (!samples[wavelength].Valid)
continue;
var offset = Math.Max(Math.Abs(Unwrap(samples[wavelength].Azimuth, reference) - center.Azimuth), Math.Abs(samples[wavelength].Elevation - center.Elevation));
spread = Math.Max(spread, offset);
}
center.Spread = spread;
return center;
}
private static Corner Single(Sample sample, Tristimulus spectrum)
=> sample.Valid ? new Corner { Valid = true, Azimuth = sample.Azimuth, Elevation = sample.Elevation, Weight = sample.Weight * spectrum } : default;
private static Corner Complete(Corner corner, Corner anchor)
{
if (!corner.Valid)
return new Corner { Valid = true, Azimuth = anchor.Azimuth, Elevation = anchor.Elevation };
corner.Azimuth = Unwrap(corner.Azimuth, anchor.Azimuth);
return corner;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void SplatPatch(ScatterGrid grid, Corner c00, Corner c01, Corner c10, Corner c11, double quadWeight)
{
var along = Math.Max(Distance(c00, c10), Distance(c01, c11));
var across = Math.Max(Distance(c00, c01), Distance(c10, c11));
var stepDegrees = HaloSettings.SubStepTexels * HaloSettings.ScatterTexelDegrees;
var alongSteps = Math.Clamp((int)Math.Ceiling(along / stepDegrees), 1, HaloSettings.MaximumSubSteps);
var acrossSteps = Math.Clamp((int)Math.Ceiling(across / stepDegrees), 1, HaloSettings.MaximumSubSteps);
var unit = quadWeight / (alongSteps * acrossSteps);
for (var first = 0; first < alongSteps; first++)
{
var s = (first + 0.5) / alongSteps;
for (var second = 0; second < acrossSteps; second++)
{
var t = (second + 0.5) / acrossSteps;
var w00 = (1.0 - s) * (1.0 - t);
var w01 = (1.0 - s) * t;
var w10 = s * (1.0 - t);
var w11 = s * t;
var weight = (w00 * c00.Weight) + (w01 * c01.Weight) + (w10 * c10.Weight) + (w11 * c11.Weight);
grid.Splat(
w00 * c00.Azimuth + w01 * c01.Azimuth + w10 * c10.Azimuth + w11 * c11.Azimuth,
w00 * c00.Elevation + w01 * c01.Elevation + w10 * c10.Elevation + w11 * c11.Elevation,
unit * weight);
}
}
}
private static double Unwrap(double azimuth, double reference)
{
if (azimuth - reference > HalfTurnDegrees)
return azimuth - FullTurnDegrees;
return reference - azimuth > HalfTurnDegrees ? azimuth + FullTurnDegrees : azimuth;
}
private static double Distance(Corner first, Corner second)
=> Math.Max(Math.Abs(first.Azimuth - second.Azimuth), Math.Abs(first.Elevation - second.Elevation));
private static Chunk[] BuildChunks(Layer[] layers, int azimuthSteps)
{
var chunks = new List<Chunk>();
foreach (var layer in layers)
{
for (var strip = 0; strip < azimuthSteps; strip += HaloSettings.StripsPerTask)
chunks.Add(new Chunk(layer, strip, Math.Min(HaloSettings.StripsPerTask, azimuthSteps - strip)));
}
return [.. chunks];
}
private static Layer[] PlateLayers(double tiltDegrees)
{
var nodes = HaloSettings.PlateTiltRadialNodes;
var tilt = tiltDegrees * HaloSettings.RadiansPerDegree;
var layers = new Layer[nodes];
for (var node = 0; node < nodes; node++)
layers[node] = new Layer(tilt * HaloSettings.GetPlateTiltQuantile(node), 1.0 / nodes);
return layers;
}
private static Layer[] ColumnLayers(double tiltDegrees)
{
var quantiles = HaloSettings.ColumnTiltQuantiles;
var tilt = tiltDegrees * HaloSettings.RadiansPerDegree;
return [.. quantiles.Select(quantile => new Layer(tilt * quantile, 1.0 / quantiles.Length))];
}
private static Vec3 PlateAxis(double tilt, double azimuth)
=> new(Math.Sin(tilt) * Math.Cos(azimuth), Math.Sin(tilt) * Math.Sin(azimuth), Math.Cos(tilt));
private static Vec3 ColumnAxis(double tilt, double azimuth)
=> new(Math.Cos(tilt) * Math.Cos(azimuth), Math.Cos(tilt) * Math.Sin(azimuth), Math.Sin(tilt));
private static float[] ToRadiance(ScatterGrid grid, double sunElevationDegrees)
{
var texel = HaloSettings.ScatterTexelDegrees * HaloSettings.RadiansPerDegree;
var radiance = new float[grid.Cells.Length];
for (var row = 0; row < ScatterGrid.Height; row++)
Parallel.For(0, ScatterGrid.Height, row =>
{
var elevation = Math.Min(Math.Abs(HaloSettings.GetScatterElevationDegrees(row, sunElevationDegrees)), 90.0) * HaloSettings.RadiansPerDegree;
var solidAngle = Math.Max(Math.Cos(elevation), HaloSettings.ScatterMinimumCosine) * texel * texel;
@@ -358,7 +63,7 @@ internal static class CrystalScatter
var start = row * ScatterGrid.Width * HaloSettings.ColorChannels;
for (var index = start; index < start + ScatterGrid.Width * HaloSettings.ColorChannels; index++)
radiance[index] = (float)(grid.Cells[index] * scale);
}
});
return radiance;
}
+1 -1
ファイルの表示
@@ -5,7 +5,7 @@
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.0</Version>
<Version>1.0.1</Version>
<Platforms>AnyCPU;x64</Platforms>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<ShaderDirPath>..\Release\</ShaderDirPath>
+2
ファイルの表示
@@ -8,6 +8,8 @@ internal static class HaloSettings
public const int TexelChannels = 4;
public const int TexelBytes = TexelChannels * sizeof(ushort);
public const double RadiansPerDegree = Math.PI / 180.0;
public const double HalfTurnDegrees = 180.0;
public const double FullTurnDegrees = 360.0;
public const int RingTableWidth = 1024;
public const double RingStartDegrees = 10.0;
+7 -7
ファイルの表示
@@ -40,7 +40,7 @@ internal static class HaloTable
var (whiteRed, whiteGreen, whiteBlue) = SolarSpectrum.ToLinearSrgb(SolarSpectrum.White);
var texels = new Half[width * height * HaloSettings.TexelChannels];
var scale = Scale.Value;
for (var row = 0; row < height; row++)
Parallel.For(0, height, row =>
{
var offset = HaloSettings.GetScatterElevationDegrees(row, sunElevationDegrees) - sunElevationDegrees;
var taper = SmoothStep(-HaloSettings.ScatterElevationHalfSpanDegrees, -HaloSettings.ScatterElevationHalfSpanDegrees + HaloSettings.ScatterElevationTaperDegrees, offset)
@@ -51,7 +51,7 @@ internal static class HaloTable
var (red, green, blue) = SolarSpectrum.ToLinearSrgb(new Tristimulus(blurred[source], blurred[source + 1], blurred[source + 2]));
Write(texels, row * width + column0, red / whiteRed * scale * taper, green / whiteGreen * scale * taper, blue / whiteBlue * scale * taper, saturation);
}
}
});
return texels;
}
@@ -129,7 +129,7 @@ internal static class HaloTable
var texel = HaloSettings.ScatterTexelDegrees;
var extent = width + 2 * MaximumBlurTexels;
var prefix = new double[height * channels * (extent + 1)];
for (var row = 0; row < height; row++)
Parallel.For(0, height, row =>
{
for (var channel = 0; channel < channels; channel++)
{
@@ -140,11 +140,11 @@ internal static class HaloTable
prefix[start + index + 1] = prefix[start + index] + values[(row * width + column) * channels + channel];
}
}
}
});
var verticalRadius = (int)Math.Floor(radiusDegrees / texel);
var result = new double[values.Length];
for (var row = 0; row < height; row++)
Parallel.For(0, height, row =>
{
var elevation = Math.Min(Math.Abs(HaloSettings.GetScatterElevationDegrees(row, sunElevationDegrees)), 90.0) * HaloSettings.RadiansPerDegree;
var horizontalScale = 1.0 / (texel * Math.Max(Math.Cos(elevation), HaloSettings.ScatterMinimumCosine));
@@ -161,7 +161,7 @@ internal static class HaloTable
if (area <= 0.0)
{
Array.Copy(values, row * width * channels, result, row * width * channels, width * channels);
continue;
return;
}
for (var column = 0; column < width; column++)
@@ -180,7 +180,7 @@ internal static class HaloTable
result[(row * width + column) * channels + channel] = sum / area;
}
}
}
});
return result;
}
+9 -7
ファイルの表示
@@ -20,18 +20,20 @@ internal readonly record struct PrismPath(int Entry, int Exit, double Geometry)
internal static class PrismGeometry
{
public const int SideFaceCount = 6;
public const int UpperEnd = 6;
public const int LowerEnd = 7;
public const int ReflectionExit = 8;
public const int EntryKindCount = 8;
public const int ExitKindCount = 9;
public const int UpperEnd = SideFaceCount;
public const int LowerEnd = UpperEnd + 1;
public const int ReflectionExit = LowerEnd + 1;
public const int EntryKindCount = LowerEnd + 1;
public const int ExitKindCount = ReflectionExit + 1;
public const int LabelCount = EntryKindCount * ExitKindCount;
public const int MaximumPathCount = LabelCount;
public const double SpinPeriodRadians = 2.0 * Math.PI / SideFaceCount;
public const double SpinSectorRadians = Math.PI / SideFaceCount;
private const double MinimumCosine = 1e-9;
private const double MinimumProjection = 1e-12;
private const double FirstSideAngleDegrees = 30.0;
private const double SideAngleStepDegrees = 60.0;
private const double SideAngleStepDegrees = HaloSettings.FullTurnDegrees / SideFaceCount;
private const double FirstSideAngleDegrees = SideAngleStepDegrees / 2.0;
public static readonly double Apothem = Math.Sqrt(3.0) / 2.0;
public static readonly double EndFaceArea = 1.5 * Math.Sqrt(3.0);
+2 -2
ファイルの表示
@@ -16,7 +16,7 @@ internal static class RingProfile
var azimuths = HaloSettings.RandomAzimuthSteps;
var length = 2.0 * HaloSettings.RandomCrystalLengthRatio;
var inclinationStep = Math.PI / 2.0 / inclinations;
var azimuthStep = Math.PI / 6.0 / azimuths;
var azimuthStep = PrismGeometry.SpinSectorRadians / azimuths;
var step = HaloSettings.GetRingStepDegrees();
var weights = SolarSpectrum.Weights;
var referenceIndex = IceOptics.RefractiveIndex(HaloSettings.ReferenceWavelengthNanometers);
@@ -33,7 +33,7 @@ internal static class RingProfile
for (var column = 0; column < azimuths; column++)
{
var azimuth = (column + 0.5) * azimuthStep;
var orientation = Math.Cos(inclination) * inclinationStep * azimuthStep * 6.0 / Math.PI;
var orientation = Math.Cos(inclination) * inclinationStep * azimuthStep * PrismGeometry.SideFaceCount / Math.PI;
var incoming = new Vec3(-Math.Cos(inclination) * Math.Cos(azimuth), -Math.Cos(inclination) * Math.Sin(azimuth), -Math.Sin(inclination));
var count = PrismGeometry.Enumerate(incoming, length, referenceIndex, PathKinds.SideToSide | PathKinds.SideToEnd | PathKinds.EndToSide, paths);
for (var path = 0; path < count; path++)
+18 -4
ファイルの表示
@@ -10,6 +10,7 @@ internal sealed class ScatterGrid
private const double TexelsPerDegree = 1.0 / HaloSettings.ScatterTexelDegrees;
private const int Channels = HaloSettings.ColorChannels;
private const int SumBlock = 8192;
public ScatterGrid()
{
@@ -18,7 +19,7 @@ internal sealed class ScatterGrid
public long[] Cells { get; }
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Splat(double azimuthDegrees, double elevationOffsetDegrees, Tristimulus weight)
{
var x = Math.Abs(azimuthDegrees) * TexelsPerDegree - 0.5;
@@ -44,12 +45,24 @@ internal sealed class ScatterGrid
}
}
public void Add(ScatterGrid other)
public static ScatterGrid Sum(IReadOnlyList<ScatterGrid> grids)
{
for (var index = 0; index < Cells.Length; index++)
Cells[index] += other.Cells[index];
var total = new ScatterGrid();
var cells = total.Cells;
Parallel.For(0, (cells.Length + SumBlock - 1) / SumBlock, block =>
{
var end = Math.Min((block + 1) * SumBlock, cells.Length);
foreach (var grid in grids)
{
var other = grid.Cells;
for (var index = block * SumBlock; index < end; index++)
cells[index] += other[index];
}
});
return total;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void Add(long* line, int left, int right, double leftScale, double rightScale, double wx, double wy, double wz)
{
line[left] += (long)(leftScale * wx + 0.5);
@@ -60,6 +73,7 @@ internal sealed class ScatterGrid
line[right + 2] += (long)(rightScale * wz + 0.5);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Reflect(int column)
{
if (column < 0)
+127
ファイルの表示
@@ -0,0 +1,127 @@
using System.Runtime.CompilerServices;
namespace Halo;
internal static class ScatterSplat
{
private const double MergeSpreadDegrees = 0.075;
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void Strip(ScatterGrid grid, StripSlice previous, StripSlice current, double quadWeight)
{
for (var label = 0; label < PrismGeometry.LabelCount; label++)
{
if (!previous.Used[label] && !current.Used[label])
continue;
for (var node = 0; node < current.SpinSteps; node++)
{
Quad(
grid,
previous.Bands,
previous.Wavelengths(label, node),
previous.Wavelengths(label, node + 1),
current.Wavelengths(label, node),
current.Wavelengths(label, node + 1),
previous.CornerAt(label, node),
previous.CornerAt(label, node + 1),
current.CornerAt(label, node),
current.CornerAt(label, node + 1),
quadWeight);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void Quad(
ScatterGrid grid,
SpectralBand[] bands,
ReadOnlySpan<ExitSample> samples00,
ReadOnlySpan<ExitSample> samples01,
ReadOnlySpan<ExitSample> samples10,
ReadOnlySpan<ExitSample> samples11,
in Corner c00,
in Corner c01,
in Corner c10,
in Corner c11,
double quadWeight)
{
var reference = FirstValid(c00, c01, c10, c11);
if (!reference.Valid)
return;
if (c00.Spread <= MergeSpreadDegrees && c01.Spread <= MergeSpreadDegrees && c10.Spread <= MergeSpreadDegrees && c11.Spread <= MergeSpreadDegrees)
{
Patch(grid, AlignTo(c00, reference), AlignTo(c01, reference), AlignTo(c10, reference), AlignTo(c11, reference), quadWeight);
return;
}
for (var wavelength = 0; wavelength < bands.Length; wavelength++)
{
var bandWeight = bands[wavelength].Weight;
var band00 = BandCorner(samples00[wavelength], bandWeight);
var band01 = BandCorner(samples01[wavelength], bandWeight);
var band10 = BandCorner(samples10[wavelength], bandWeight);
var band11 = BandCorner(samples11[wavelength], bandWeight);
var bandReference = FirstValid(band00, band01, band10, band11);
if (bandReference.Valid)
Patch(grid, AlignTo(band00, bandReference), AlignTo(band01, bandReference), AlignTo(band10, bandReference), AlignTo(band11, bandReference), quadWeight);
}
}
private static Corner FirstValid(in Corner first, in Corner second, in Corner third, in Corner fourth)
=> first.Valid ? first : second.Valid ? second : third.Valid ? third : fourth;
private static Corner BandCorner(ExitSample sample, Tristimulus bandWeight)
=> sample.Valid ? new Corner { Valid = true, Azimuth = sample.Azimuth, Elevation = sample.Elevation, Weight = sample.Weight * bandWeight } : default;
private static Corner AlignTo(Corner corner, Corner reference)
{
if (!corner.Valid)
return new Corner { Valid = true, Azimuth = reference.Azimuth, Elevation = reference.Elevation };
corner.Azimuth = Corner.Unwrap(corner.Azimuth, reference.Azimuth);
return corner;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static unsafe void Patch(ScatterGrid grid, in Corner c00, in Corner c01, in Corner c10, in Corner c11, double quadWeight)
{
var along = Math.Max(Distance(c00, c10), Distance(c01, c11));
var across = Math.Max(Distance(c00, c01), Distance(c10, c11));
var stepDegrees = HaloSettings.SubStepTexels * HaloSettings.ScatterTexelDegrees;
var alongSteps = Math.Clamp((int)Math.Ceiling(along / stepDegrees), 1, HaloSettings.MaximumSubSteps);
var acrossSteps = Math.Clamp((int)Math.Ceiling(across / stepDegrees), 1, HaloSettings.MaximumSubSteps);
var unit = quadWeight / (alongSteps * acrossSteps);
var ts = stackalloc double[HaloSettings.MaximumSubSteps];
var complements = stackalloc double[HaloSettings.MaximumSubSteps];
for (var second = 0; second < acrossSteps; second++)
{
var t = (second + 0.5) / acrossSteps;
ts[second] = t;
complements[second] = 1.0 - t;
}
for (var first = 0; first < alongSteps; first++)
{
var s = (first + 0.5) / alongSteps;
var complement = 1.0 - s;
for (var second = 0; second < acrossSteps; second++)
{
var t = ts[second];
var w00 = complement * complements[second];
var w01 = complement * t;
var w10 = s * complements[second];
var w11 = s * t;
var weight = (w00 * c00.Weight) + (w01 * c01.Weight) + (w10 * c10.Weight) + (w11 * c11.Weight);
grid.Splat(
w00 * c00.Azimuth + w01 * c01.Azimuth + w10 * c10.Azimuth + w11 * c11.Azimuth,
w00 * c00.Elevation + w01 * c01.Elevation + w10 * c10.Elevation + w11 * c11.Elevation,
unit * weight);
}
}
}
private static double Distance(in Corner first, in Corner second)
=> Math.Max(Math.Abs(first.Azimuth - second.Azimuth), Math.Abs(first.Elevation - second.Elevation));
}
+174
ファイルの表示
@@ -0,0 +1,174 @@
using System.Runtime.CompilerServices;
namespace Halo;
internal struct ExitSample
{
public double Azimuth;
public double Elevation;
public double Weight;
public bool Valid;
}
internal struct Corner
{
public bool Valid;
public double Azimuth;
public double Elevation;
public double Spread;
public Tristimulus Weight;
public static double Unwrap(double azimuth, double reference)
{
if (azimuth - reference > HaloSettings.HalfTurnDegrees)
return azimuth - HaloSettings.FullTurnDegrees;
return reference - azimuth > HaloSettings.HalfTurnDegrees ? azimuth + HaloSettings.FullTurnDegrees : azimuth;
}
}
internal sealed class StripSlice(int nodeCount, SpectralBand[] bands)
{
private PrismPath[][] Paths { get; } = Enumerable.Range(0, nodeCount).Select(_ => new PrismPath[PrismGeometry.MaximumPathCount]).ToArray();
private int[] PathCounts { get; } = new int[nodeCount];
private Vec3[] Incoming { get; } = new Vec3[nodeCount];
private Vec3[] FirstAxes { get; } = new Vec3[nodeCount];
private Vec3[] SecondAxes { get; } = new Vec3[nodeCount];
private ExitSample[] Samples { get; } = new ExitSample[PrismGeometry.LabelCount * nodeCount * bands.Length];
private Corner[] Corners { get; } = new Corner[PrismGeometry.LabelCount * nodeCount];
private int NodeCount { get; } = nodeCount;
private int WavelengthCount { get; } = bands.Length;
public SpectralBand[] Bands { get; } = bands;
public bool[] Used { get; } = new bool[PrismGeometry.LabelCount];
public int SpinSteps => NodeCount - 1;
public ref readonly Corner CornerAt(int label, int node)
=> ref Corners[label * NodeCount + node];
public ReadOnlySpan<ExitSample> Wavelengths(int label, int node)
=> Samples.AsSpan((label * NodeCount + node) * WavelengthCount, WavelengthCount);
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public void Fill(Vec3 axis, Vec3 incoming, double length, PathKinds kinds, double sunElevationDegrees)
{
var referenceIndex = IceOptics.RefractiveIndex(HaloSettings.ReferenceWavelengthNanometers);
var helper = Math.Abs(axis.Z) < 0.9 ? new Vec3(0.0, 0.0, 1.0) : new Vec3(1.0, 0.0, 0.0);
var firstBase = helper.Cross(axis).Normalized();
var secondBase = axis.Cross(firstBase);
for (var node = 0; node < NodeCount; node++)
{
var (sine, cosine) = Math.SinCos(node * PrismGeometry.SpinPeriodRadians / SpinSteps);
var first = (cosine * firstBase) + (sine * secondBase);
var second = (-sine * firstBase) + (cosine * secondBase);
FirstAxes[node] = first;
SecondAxes[node] = second;
var local = new Vec3(incoming.Dot(first), incoming.Dot(second), incoming.Dot(axis));
Incoming[node] = local;
PathCounts[node] = PrismGeometry.Enumerate(local, length, referenceIndex, kinds, Paths[node]);
}
Reset();
for (var wavelength = 0; wavelength < WavelengthCount; wavelength++)
{
var index = IceOptics.RefractiveIndex(Bands[wavelength].Wavelength);
for (var node = 0; node < NodeCount; node++)
{
var paths = Paths[node];
for (var path = 0; path < PathCounts[node]; path++)
{
var current = paths[path];
Vec3 exit;
double factor;
var found = current.Exit == PrismGeometry.ReflectionExit
? PrismGeometry.TryReflect(Incoming[node], current, index, out exit, out factor)
: PrismGeometry.TryRefract(Incoming[node], current, index, out exit, out factor);
if (!found)
continue;
var sky = -((exit.X * FirstAxes[node]) + (exit.Y * SecondAxes[node]) + (exit.Z * axis));
Samples[Slot(current.Label, node, wavelength)] = new ExitSample
{
Azimuth = Math.Atan2(sky.Y, sky.X) / HaloSettings.RadiansPerDegree,
Elevation = Math.Asin(Math.Clamp(sky.Z, -1.0, 1.0)) / HaloSettings.RadiansPerDegree - sunElevationDegrees,
Weight = current.Geometry * factor,
Valid = true,
};
Used[current.Label] = true;
}
}
}
MergeCorners();
}
private int Slot(int label, int node, int wavelength)
=> (label * NodeCount + node) * WavelengthCount + wavelength;
private void Reset()
{
for (var label = 0; label < Used.Length; label++)
{
if (!Used[label])
continue;
Array.Clear(Samples, label * NodeCount * WavelengthCount, NodeCount * WavelengthCount);
Array.Clear(Corners, label * NodeCount, NodeCount);
Used[label] = false;
}
}
private void MergeCorners()
{
for (var label = 0; label < Used.Length; label++)
{
if (!Used[label])
continue;
for (var node = 0; node < NodeCount; node++)
Corners[label * NodeCount + node] = MergeBands(Wavelengths(label, node), Bands);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static Corner MergeBands(ReadOnlySpan<ExitSample> samples, SpectralBand[] bands)
{
var total = new Tristimulus();
var luminance = 0.0;
var azimuth = 0.0;
var elevation = 0.0;
var reference = double.NaN;
for (var wavelength = 0; wavelength < samples.Length; wavelength++)
{
var sample = samples[wavelength];
if (!sample.Valid)
continue;
if (double.IsNaN(reference))
reference = sample.Azimuth;
var weight = sample.Weight * bands[wavelength].Weight.Y;
total += sample.Weight * bands[wavelength].Weight;
luminance += weight;
azimuth += weight * Corner.Unwrap(sample.Azimuth, reference);
elevation += weight * sample.Elevation;
}
if (double.IsNaN(reference))
return default;
if (luminance <= 0.0)
return new Corner { Valid = true, Azimuth = reference };
var center = new Corner { Valid = true, Azimuth = azimuth / luminance, Elevation = elevation / luminance, Weight = total };
var spread = 0.0;
for (var wavelength = 0; wavelength < samples.Length; wavelength++)
{
if (!samples[wavelength].Valid)
continue;
var offset = Math.Max(Math.Abs(Corner.Unwrap(samples[wavelength].Azimuth, reference) - center.Azimuth), Math.Abs(samples[wavelength].Elevation - center.Elevation));
spread = Math.Max(spread, offset);
}
center.Spread = spread;
return center;
}
}