using System; using Annulus; using Azimuth; namespace Konis.Blacklight { /// /// Works out, for each particle, the window of its sprite that lies inside the slabs an emitter clips to, so the /// shader can cut off what pokes out. /// /// /// A sprite is a flat card that stands upright, so a slab's plane crosses it along a straight line. A camera /// looking straight down sees a standing card edge on, so there the card lies flat and faces the camera. That /// makes each slab a strip across the sprite, and slabs facing the same way on the screen share one strip. A /// window is the parallelogram where two strips overlap, cut down further for any strip beyond them. /// public class ParticleClipWindows { /// /// The most slabs an emitter clips to, counting its def's, its own and its world's. /// public const int MaxSlabs = Emitter.MaxClipSlabs; /// /// The window of a sprite that is clipped away entirely. /// public static readonly Parallelogram NothingVisible = new Parallelogram(Vector.Zero, Vector.Zero, Vector.Zero); // A slab's strip is measured along its group's direction, which is the slab's normal as it lands on the screen. // A slab pointing the opposite way on screen is stored turned around, so every member reads the same way. private readonly Vector[] groupDirections = new Vector[MaxSlabs]; private readonly Slab[] memberSlabs = new Slab[MaxSlabs]; private readonly int[] memberGroups = new int[MaxSlabs]; private readonly Scalar[] memberFactors = new Scalar[MaxSlabs]; // An unbounded side takes no arithmetic, since infinities slow the x87 unit that 32-bit .NET Framework uses. private readonly bool[] memberHasMins = new bool[MaxSlabs]; private readonly bool[] memberHasMaxes = new bool[MaxSlabs]; private readonly Slab[] facingSlabs = new Slab[MaxSlabs]; private readonly Scalar[] groupLowests = new Scalar[MaxSlabs]; private readonly Scalar[] groupHighests = new Scalar[MaxSlabs]; private readonly int[] activeGroups = new int[MaxSlabs]; private int groupCount; private int memberCount; private int facingCount; private int capacity; // Scratch columns, one value per particle. Every one is allocated up front so that no frame pays for a first // use. private DenseVector inverseScales; private DenseVector stripScales; private DenseVector smallestSizes; private DenseVector scratch; private DenseVector touched; private DenseVector stripLowests; private DenseVector stripHighests; public ParticleClipWindows() { Allocate(0); } /// /// Gets how many particles the columns have room for. /// public int Capacity { get { return capacity; } } /// /// Gets the column of each particle's position, in the space of the slabs given to Prepare. Each particle has /// three values, one per axis, and one particle follows another. Fill the columns before calling /// CalculateSpriteWindows. /// public DenseVector Positions { get; private set; } /// /// Gets the column of how much each particle's transform scales its sprite by. /// public DenseVector Scales { get; private set; } /// /// Gets the column of how far, in each sprite's own coordinates, a window reaches from the sprite's center on a /// side no slab cuts. That is how far any of the sprite is from its center, plus the width of the fade at a /// window's edge when the batch has one. /// public DenseVector Radii { get; private set; } private void Allocate(int newCapacity) { capacity = newCapacity; Positions = new DenseVector(3 * capacity); Scales = new DenseVector(capacity); Radii = new DenseVector(capacity); inverseScales = new DenseVector(capacity); stripScales = new DenseVector(capacity); smallestSizes = new DenseVector(capacity); scratch = new DenseVector(capacity); touched = new DenseVector(capacity); stripLowests = new DenseVector(capacity); stripHighests = new DenseVector(capacity); } /// /// Makes the columns hold at least particles. Growing them empties them, so call this /// before filling them. /// /// The count is negative. public void EnsureCapacity(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, "A count can't be negative."); } if (count > capacity) { Allocate(Math.Max(count, 2 * capacity)); } } /// /// Gets how many distinct directions the slabs run in on the screen. /// public int DirectionCount { get { return groupCount; } } // Below this a standing card is so close to edge on that its height says nothing about where a slab cuts it. private const double MinimumUprightHeight = 1e-9; // How a slab's distance to the particle changes per unit of screen offset, as a vector on the screen. An // upright card's height is the normal's altitude, stretched to undo the projection's foreshortening of it. private static Vector OnScreenOf(Vector3 normal, ViewProjection projection) { Vector onScreen = projection.Project(normal); if (projection.AltitudeToScreenY < MinimumUprightHeight) { return onScreen; } return new Vector(onScreen.X, normal.Z / projection.AltitudeToScreenY); } /// /// Takes in the slabs, which are in the space of the particle positions given to CalculateSpriteWindow, and /// sorts them by the way they run on the screen. /// /// /// The count is negative or more than . /// public void Prepare(Slab[] slabs, int count, ViewProjection projection) { if (count < 0 || count > MaxSlabs) { throw new ArgumentOutOfRangeException( nameof(count), count, $"There can be at most {MaxSlabs} slabs."); } groupCount = 0; memberCount = 0; facingCount = 0; for (int i = 0; i < count; i++) { Slab slab = slabs[i]; Vector onScreen = OnScreenOf(slab.Normal, projection); // A slab facing the camera cuts every sprite whole, so only the particle's own position decides. if (onScreen.LengthSquared() == 0) { facingSlabs[facingCount] = slab; facingCount++; continue; } Scalar length = onScreen.Length(); Vector direction = onScreen / length; int group = -1; for (int j = 0; j < groupCount && group < 0; j++) { if (Vector.CrossProduct(groupDirections[j], direction) == 0) { group = j; if (Vector.DotProduct(groupDirections[j], direction) < 0) { slab = new Slab(-slab.Normal, -slab.Max, -slab.Min); } } } if (group < 0) { group = groupCount; groupDirections[group] = direction; groupCount++; } memberSlabs[memberCount] = slab; memberGroups[memberCount] = group; memberFactors[memberCount] = 1 / length; memberHasMins[memberCount] = !Scalar.IsNegativeInfinity(slab.Min); memberHasMaxes[memberCount] = !Scalar.IsPositiveInfinity(slab.Max); memberCount++; } } // Where the sprite's own coordinates see a group's direction, as a unit vector. private Vector LocalDirection(int group, in AffineMatrix transform, Scalar inverseScale) { Vector direction = groupDirections[group]; return new Vector( transform.M00 * direction.X + transform.M10 * direction.Y, transform.M01 * direction.X + transform.M11 * direction.Y) * inverseScale; } // Pulls the window in to the strip, skipping an edge that lies past the sprite and so can't cut it. private static Parallelogram? CutToStrip( Parallelogram? window, Vector direction, Scalar lowest, Scalar highest, Scalar radius) { if (window.HasValue && lowest > -radius) { window = window.Value.InscribedInHalfPlane(direction * lowest, direction); } if (window.HasValue && highest < radius) { window = window.Value.InscribedInHalfPlane(direction * highest, -direction); } return window; } // Each pair of strips gives an exact parallelogram, which the other strips then cut down. The largest wins. private Parallelogram? WindowFromManyStrips( int active, in AffineMatrix transform, Scalar inverseScale, Scalar radius) { Parallelogram? best = null; Scalar bestArea = 0; for (int i = 0; i < active; i++) { int first = activeGroups[i]; Vector firstDirection = LocalDirection(first, in transform, inverseScale); for (int j = i + 1; j < active; j++) { int second = activeGroups[j]; Vector secondDirection = LocalDirection(second, in transform, inverseScale); Parallelogram? window = Parallelogram.FromStrips( firstDirection, groupLowests[first], groupHighests[first], secondDirection, groupLowests[second], groupHighests[second]); for (int k = 0; k < active; k++) { int other = activeGroups[k]; if (k != i && k != j) { window = CutToStrip( window, LocalDirection(other, in transform, inverseScale), groupLowests[other], groupHighests[other], radius); } } if (window.HasValue && window.Value.Area > bestArea) { best = window; bestArea = window.Value.Area; } } } return best; } private Vector3 PositionOf(int index) { return new Vector3(Positions[3 * index], Positions[3 * index + 1], Positions[3 * index + 2]); } private bool OutsideFacingSlabs(Vector3 position) { for (int i = 0; i < facingCount; i++) { Scalar along = facingSlabs[i].Along(position); if (!(along >= facingSlabs[i].Min && along <= facingSlabs[i].Max)) { return true; } } return false; } // The commonest window is one strip, and a perpendicular unit direction makes its corners a few products. private Parallelogram OneStripWindow( int group, in AffineMatrix transform, Scalar inverseScale, Scalar lowest, Scalar highest, Scalar radius) { Vector direction = LocalDirection(group, in transform, inverseScale); Vector across = direction.PerpCCW(); return new Parallelogram( direction * lowest - across * radius, direction * (highest - lowest), across * (2 * radius)); } // Works out one sprite's window the long way. The batch only comes here for a sprite it can't answer from the // strips it has already worked out. private Parallelogram? WindowFor(Vector3 position, in AffineMatrix transform, Scalar scale, Scalar radius) { if (OutsideFacingSlabs(position)) { return NothingVisible; } if (groupCount == 0) { return null; } if (scale == 0) { return NothingVisible; } // A strip is measured in screen units along its direction, and the window is in the sprite's units. Scalar inverseScale = 1 / scale; for (int i = 0; i < groupCount; i++) { groupLowests[i] = -radius; groupHighests[i] = radius; } for (int i = 0; i < memberCount; i++) { Slab slab = memberSlabs[i]; Scalar along = slab.Along(position); Scalar toStrip = memberFactors[i] * inverseScale; int group = memberGroups[i]; if (memberHasMins[i]) { groupLowests[group] = Scalar.Max(groupLowests[group], (slab.Min - along) * toStrip); } if (memberHasMaxes[i]) { groupHighests[group] = Scalar.Min(groupHighests[group], (slab.Max - along) * toStrip); } } // Only a strip that reaches into the sprite cuts anything. int active = 0; for (int i = 0; i < groupCount; i++) { if (groupLowests[i] >= groupHighests[i]) { return NothingVisible; } if (groupLowests[i] > -radius || groupHighests[i] < radius) { activeGroups[active] = i; active++; } } if (active == 0) { return null; } if (active == 1) { int only = activeGroups[0]; return OneStripWindow( only, in transform, inverseScale, groupLowests[only], groupHighests[only], radius); } Parallelogram? window; if (active == 2) { int first = activeGroups[0]; int second = activeGroups[1]; window = Parallelogram.FromStrips( LocalDirection(first, in transform, inverseScale), groupLowests[first], groupHighests[first], LocalDirection(second, in transform, inverseScale), groupLowests[second], groupHighests[second]); } else { window = WindowFromManyStrips(active, in transform, inverseScale, radius); } if (!window.HasValue) { return NothingVisible; } return window; } // Answers what WindowFor would, from the strip FindTouched left in the columns. That strip is the only one // there is when every slab runs the same way on the screen. private Parallelogram? WindowFromColumns(int index, in AffineMatrix transform) { if (facingCount > 0 && OutsideFacingSlabs(PositionOf(index))) { return NothingVisible; } Scalar lowest = stripLowests[index]; Scalar highest = stripHighests[index]; Scalar radius = Radii[index]; if (lowest >= highest) { return NothingVisible; } if (!(lowest > -radius || highest < radius)) { return null; } return OneStripWindow(0, in transform, inverseScales[index], lowest, highest, radius); } // A particle no slab reaches ends up with a touched of exactly zero, since its strips never leave where they // start. The strips use WindowFor's arithmetic, so both agree on which particles those are. // // Every column holds one value per particle, so each equation below is for one particle. For the slab in hand, // along is (normal . position) and factor is 1 over the length of its normal on the screen. Wherever along is // subtracted, the code takes the dot product with the negated normal and adds. private void FindTouched(int count) { // inverseScales = 1 / Scales, smallestSizes = min(Scales, Radii), touched = 0 inverseScales.AssignmentInverse(Scales, subLength: count); smallestSizes.Assignment(Scales, subLength: count); smallestSizes.Min(Radii, subLength: count); touched.Flush(0, subLength: count); // A slab facing the camera keeps a sprite whole or drops it, by where the particle itself is. The distance // outside the slab goes into touched. // // touched += max(0, min - along) + max(0, along - max) for (int i = 0; i < facingCount; i++) { Slab slab = facingSlabs[i]; if (!Scalar.IsNegativeInfinity(slab.Min)) { scratch.AssignmentDot3(Positions, -slab.Normal, subLength: count); scratch.Add(slab.Min, subLength: count); scratch.Max(0, subLength: count); touched.Add(scratch, subLength: count); } if (!Scalar.IsPositiveInfinity(slab.Max)) { scratch.AssignmentDot3(Positions, slab.Normal, subLength: count); scratch.Add(-slab.Max, subLength: count); scratch.Max(0, subLength: count); touched.Add(scratch, subLength: count); } } // One direction at a time, so two columns of strip edges serve every direction. A strip starts as the // whole sprite, and each slab in its direction narrows it. An unbounded side is skipped, so no infinity // goes through the arithmetic. // // lowest = -Radii, then lowest = max(lowest, (min - along) * factor / Scales) // // highest = Radii, then highest = min(highest, (max - along) * factor / Scales) // // The strip's narrowing is how far it has moved from the whole sprite, which is zero until a slab reaches // the sprite. // // touched += (lowest + Radii) + (Radii - highest) for (int i = 0; i < groupCount; i++) { stripLowests.AssignmentScale(Radii, -1, subLength: count); stripHighests.Assignment(Radii, subLength: count); for (int j = 0; j < memberCount; j++) { if (memberGroups[j] == i && (memberHasMins[j] || memberHasMaxes[j])) { Slab slab = memberSlabs[j]; stripScales.AssignmentScale(inverseScales, memberFactors[j], subLength: count); if (memberHasMins[j]) { scratch.AssignmentDot3(Positions, -slab.Normal, subLength: count); scratch.Add(slab.Min, subLength: count); scratch.Multiply(stripScales, subLength: count); stripLowests.Max(scratch, subLength: count); } if (memberHasMaxes[j]) { scratch.AssignmentDot3(Positions, -slab.Normal, subLength: count); scratch.Add(slab.Max, subLength: count); scratch.Multiply(stripScales, subLength: count); stripHighests.Min(scratch, subLength: count); } } } scratch.AssignmentAdd(stripLowests, Radii, subLength: count); touched.Add(scratch, subLength: count); scratch.AssignmentSub(Radii, stripHighests, subLength: count); touched.Add(scratch, subLength: count); } } /// /// Works out, for the first particles in the columns, the window of its sprite, in the /// sprite's own coordinates, that keeps the part inside every slab. A window is null when the sprite is inside /// them all, and NothingVisible when none of it is. /// /// /// The window can fall short of everything inside the slabs where three directions meet, but it never reaches /// outside them. /// /// Turns each sprite's coordinates into the screen's, by a turn and a scale. /// How many particles there are. /// Receives each particle's window. /// The count is negative or more than the capacity. /// An array is shorter than the count. public void CalculateSpriteWindows(AffineMatrix[] transforms, int count, Parallelogram?[] windows) { if (transforms == null) { throw new ArgumentNullException(nameof(transforms)); } if (windows == null) { throw new ArgumentNullException(nameof(windows)); } if (count < 0 || count > capacity) { throw new ArgumentOutOfRangeException( nameof(count), count, $"There is room for {capacity} particles."); } if (transforms.Length < count) { throw new ArgumentException($"There are {transforms.Length} transforms for {count} particles."); } if (windows.Length < count) { throw new ArgumentException($"There is room for {windows.Length} windows for {count} particles."); } if (groupCount == 0 && facingCount == 0) { for (int i = 0; i < count; i++) { windows[i] = null; } return; } FindTouched(count); bool oneStrip = groupCount == 1; for (int i = 0; i < count; i++) { // A size too small to draw is answered the long way, however far the slabs are. if (smallestSizes[i] <= 0) { windows[i] = WindowFor(PositionOf(i), in transforms[i], Scales[i], Radii[i]); } else { // Exactly zero, not within a tolerance, since any strip that moved at all has cut the sprite. A // NaN is neither zero nor positive, so it goes the long way too. double touchedAmount = touched[i].Value; if (touchedAmount == 0) { windows[i] = null; } else if (oneStrip && touchedAmount > 0) { windows[i] = WindowFromColumns(i, in transforms[i]); } else { windows[i] = WindowFor(PositionOf(i), in transforms[i], Scales[i], Radii[i]); } } } } } }