Skip to content

Chapter 05 - Trail Drawing, Self-Intersection, and Fuse Pressure ​

Where this chapter fits: the player can leave the wall. A trail is recorded while they are in the open, a loop or a reconnection ends it, and standing still starts the fuse. Nothing is captured yet; that is chapter 06.

Time: [TODO Simon: time estimate for chapter 05]

Chapter 05: a yellow trail leaves the left wall, turns, and ends at the player in the open arena

Drawing in the chapter 05 build. The trail is anchored to the wall where the player left it, and every accepted move appends a point.

Prerequisites ​

Chapters 01-04, especially the playable wall path: a trail starts on it, ends on it, and is meaningless without it.

Learning objectives ​

By the end of this chapter you should be able to:

  1. implement a trail as a polyline with accumulated length and lifecycle state,
  2. describe the trail lifecycle (start, advance, complete by reconnection or loop, cancel) and which method owns each transition,
  3. enforce the no-backtrack rule that stops the player reversing onto their own trail,
  4. detect self-intersection with finite-segment (not infinite-line) tests,
  5. drive a fuse along the trail by arc length, keyed to actual player displacement,
  6. pass the chapter's 23 tests, including the backtrack regression test.

Code anchors ​

  • Source/Entities/Trail.cs
  • Source/Systems/TrailSystem.cs
  • Source/Systems/FuseSystem.cs
  • Source/Rendering/TrailRenderer.cs
  • Source/Game/LastPerimeterApp.cs (chapter 05 staged version)
  • Tests/Systems/TrailTests.cs, TrailSystemTests.cs, TrailLoopTests.cs, FuseSystemTests.cs

Trail as temporary geometry ​

Treat the trail as a polyline, which is a chain of connected line segments. It has a start point snapped to the safe wall, interior points added as the player moves, and a completion or cancellation state. It is temporary geometry made by the player, not level geometry.

A trail is a polyline: segment lengths accumulate into TotalLength, and GetPointAtDistance walks the segments to find the point a given distance along

The entity is small. AddPoint ignores points closer than half a pixel to the last one, so a stationary frame does not add a zero-length segment. It also accumulates the total length. GetPointAtDistance is the arc-length parameterisation the fuse needs:

csharp
public sealed class Trail
{
    private readonly List<Vector2> _points = new(capacity: 256);

    public IReadOnlyList<Vector2> Points => _points;
    public TrailState State { get; set; } = TrailState.InProgress;
    public bool IsSlowDraw { get; set; }   // latched at TryStart; chapter 08 uses it for scoring and fill colour
    public float TotalLength { get; private set; }

    public void AddPoint(Vector2 point)
    {
        if (_points.Count > 0)
        {
            float distance = Vector2.Distance(_points[^1], point);
            if (distance <= 0.5f)
            {
                return;
            }

            TotalLength += distance;
        }

        _points.Add(point);
    }

    public Vector2 GetPointAtDistance(float distance)
    {
        if (_points.Count == 0)
        {
            return Vector2.Zero;
        }

        if (_points.Count == 1 || distance <= 0f)
        {
            return _points[0];
        }

        float remaining = distance;
        for (int index = 0; index < _points.Count - 1; index++)
        {
            Vector2 start = _points[index];
            Vector2 end = _points[index + 1];
            float segmentLength = Vector2.Distance(start, end);
            if (remaining <= segmentLength)
            {
                float t = segmentLength <= float.Epsilon ? 0f : remaining / segmentLength;
                return Vector2.Lerp(start, end, t);
            }

            remaining -= segmentLength;
        }

        return _points[^1];
    }
    // ContainsPoint: point-to-segment distance test, used by collision in chapter 07
}

Every new point contributes TotalLength += distance(previousPoint, newPoint). That total supports the minimum-length check, fuse travel, interpolation along the trail, and completion logic.

The trail lifecycle ​

TrailSystem owns exactly one active trail and every transition it can make:

MethodJob
TryStart(wallAnchor, firstInteriorPoint, slowDraw = false)creates the trail with its first two points and latches IsSlowDraw; refuses if one is already active
AppendPoint(point)records an accepted move
UpdateSlowDraw(slowDrawHeld)demotes the active trail to fast draw permanently once the input is released (chapter 08)
CanAdvance(intended, arena, direction, lastDirection)the no-backtrack rule, then "is the target tile unclaimed?"
TryGetSelfIntersection(nextPoint, out intersection)does the newest step cross an earlier segment?
CanCompleteOnPath(position, path)is the trail at least MinimumTrailLength (20 px) long, and is the position on the wall path?
Complete(snappedEndPoint)appends the end point, marks Completed, hands the trail back, clears the active slot
Cancel()marks Cancelled and clears the active slot

The no-backtrack rule ​

The player drew Right; Left is the opposite of the last accepted direction and is refused, while Up, Down, and Right are allowed

A trail move must pass TrailSystem.CanAdvance, and the first thing it rejects is reversal. Re-tracing the line you just drew can never enclose area. Worse, the reversed segment lies exactly on the trail, which confuses self-intersection checks:

csharp
public bool CanAdvance(Vector2 intendedPosition, ArenaSystem arenaSystem, Direction direction = Direction.None, Direction lastDirection = Direction.None)
{
    if (ActiveTrail is null)
    {
        return false;
    }

    // The player cannot back up along their own active trail; reversing
    // re-traces the drawn line without enclosing anything.
    if (direction != Direction.None && lastDirection != Direction.None && direction == lastDirection.Opposite())
    {
        return false;
    }

    if (!arenaSystem.IsUnclaimedWorld(intendedPosition))
    {
        return false;
    }

    return true;
}

There is a subtle pairing rule in the chapter app. Player.CurrentDirection is only updated when a move is accepted. A blocked reversal therefore cannot turn itself into a new "last direction" and defeat the check on the next frame. CanAdvance_BlocksReversal_OntoActiveTrail in TrailSystemTests pins this behaviour down. It also asserts the nearby acceptances, so the rule cannot silently become "block everything".

Self-intersection ​

Two panels: infinite lines that cross outside the segments do not count; a crossing inside both finite segments closes the loop at X

The trail system checks whether the newest segment (from the last recorded point to the intended position) intersects any earlier segment except the one it continues from:

csharp
public bool TryGetSelfIntersection(Vector2 nextPoint, out Vector2 intersectionPoint)
{
    intersectionPoint = Vector2.Zero;
    if (ActiveTrail is null || ActiveTrail.Points.Count < 4)
    {
        return false;
    }

    Vector2 segmentStart = ActiveTrail.Points[^1];
    for (int index = 0; index < ActiveTrail.Points.Count - 2; index++)
    {
        if (TryGetSegmentIntersection(ActiveTrail.Points[index], ActiveTrail.Points[index + 1], segmentStart, nextPoint, out intersectionPoint))
        {
            return true;
        }
    }

    return false;
}

TryGetSegmentIntersection introduces useful geometry. It solves the two line equations with a determinant and rejects near-parallel pairs, where the denominator is close to zero. It then confirms the candidate point lies inside both finite segments with a half-pixel tolerance (PointOnSegment). Intersecting infinite lines is not enough. SelfIntersection_IsDetected_AtLoopClosure in TrailLoopTests draws a small square and asserts the closure point.

Fuse as spatial pressure ​

The fuse is more than a countdown. It is visible pressure moving along the exact danger path the player created.

The fuse timeline: one second of stillness triggers the warning, two seconds ignite the spark at the anchor, then it burns along the trail at 60 px/s; moving before ignition restarts the stopped timer, moving after ignition only pauses the spark in place

Its behaviour is:

  1. the player stops,
  2. after FuseWarningDelaySeconds (1.0 s) IsWarning becomes true (the HUD and audio use this from chapter 08),
  3. after FuseTriggerDelaySeconds (2.0 s) the fuse activates at the trail anchor,
  4. the spark advances along the trail at FuseBurnSpeed (60 px/s),
  5. if the player moves again, the spark pauses in place and resumes on the next stop; only the trail ending (completion, cancellation, death) extinguishes it via Reset(),
  6. if it consumes the whole trail, the trail is lost.

FuseSystem.Update returns true when the fuse has consumed the trail. Read the ordering: movement zeroes the stopped timer but leaves a lit spark where it is; stillness accumulates toward activation; then the burn advances by arc length:

csharp
public bool Update(Trail? activeTrail, bool isPlayerMoving, float deltaTime)
{
    if (activeTrail is null || activeTrail.State != TrailState.InProgress)
    {
        Reset();
        return false;
    }

    if (isPlayerMoving)
    {
        _stoppedSeconds = 0f;
        return false;
    }

    _stoppedSeconds += deltaTime;
    if (!IsActive && _stoppedSeconds >= _triggerDelaySeconds)
    {
        IsActive = true;
        _burnDistance = 0f;
        Position = activeTrail.Points[0];
    }

    if (!IsActive)
    {
        return false;
    }

    _burnDistance += _burnSpeed * deltaTime;
    Position = activeTrail.GetPointAtDistance(_burnDistance);
    return _burnDistance >= Math.Max(0f, activeTrail.TotalLength - 1f);
}

The maths is the course's second equation: burnDistance += burnSpeed * deltaTime, then fusePosition = trail.GetPointAtDistance(burnDistance). The trail behaves like a path parameterised by travelled distance rather than by segment index.

Crucially, isPlayerMoving is actual displacement, not input. The chapter app measures it by comparing positions across frames. Holding a blocked direction, such as a forbidden reversal, therefore counts as standing still. The stopped timer keeps counting and a lit spark keeps burning:

csharp
// The fuse reacts to actual displacement, not input: holding a blocked
// direction leaves the player stationary and the fuse keeps burning.
bool playerMoved = Vector2.DistanceSquared(_gameSession.Player.Position, _lastPlayerPosition) > 0.0001f;
_lastPlayerPosition = _gameSession.Player.Position;

NOTE

In this chapter's build the fuse does not kill the player yet. A fuse that burns the full trail simply cancels it. The work is lost, the player returns to the wall anchor where the trail began, and play continues. Death, lives and respawn arrive in chapter 07, where the fuse outcome is upgraded to HandlePlayerDeath.

Fuse just ignited: the spark sits near the wall anchorFuse burning: the spark has travelled along the horizontal part of the trailTrail consumed: the trail is gone and the player is back on the wall at the anchor
2.6 s after stopping: ignited at the anchor5.6 s: the spark is well along the trailafter the burn: cancelled, player back at the anchor

Build it step by step ​

This chapter is copy-along. Step 1 copies the chapter's files from the snapshot, and the steps after it walk through what changed and why. The listings in this chapter show the parts worth studying, not every line.

Step 1 - Copy the chapter files ​

From your LastPerimeter folder, copy the Source and Tests folders from this chapter's snapshot over your own. The command creates any folders you do not have yet and overwrites the files that changed. Replace <course-repo> with the path to your copy of the course repository (the course index explains how to get it).

In PowerShell:

powershell
Copy-Item -Recurse -Force "<course-repo>/DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure/Source", "<course-repo>/DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure/Tests" .

In bash:

bash
cp -R "<course-repo>/DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure/Source" "<course-repo>/DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure/Tests" .

That copy brings in these files:

New files:

  • Source/Entities/Trail.cs
  • Source/Rendering/TrailRenderer.cs
  • Source/Systems/FuseSystem.cs
  • Source/Systems/TrailSystem.cs
  • Tests/Systems/FuseSystemTests.cs
  • Tests/Systems/TrailLoopTests.cs
  • Tests/Systems/TrailSystemTests.cs
  • Tests/Systems/TrailTests.cs

Replaced files (the copy overwrites your versions):

  • Source/Entities/Player.cs
  • Source/Game/LastPerimeterApp.cs

NOTE

Every step after this one describes code that is already in the files you just copied. Open the file each step names and read along. You type nothing unless a step says so.

Step 2 - Read the trail, the fuse and the player ​

Open Source/Entities/Trail.cs, Source/Systems/TrailSystem.cs, Source/Systems/FuseSystem.cs, and Source/Rendering/TrailRenderer.cs, and match them against the listings above. Then open Source/Entities/Player.cs. The full Player replaces the chapter 01 version and carries public Trail? CurrentTrail { get; set; }.

Step 3 - The game class: Update as a decision tree ​

Open Source/Game/LastPerimeterApp.cs. Initialize constructs the two new systems from config: new TrailSystem(_config.MinimumTrailLength) and new FuseSystem(_config.FuseWarningDelaySeconds, _config.FuseTriggerDelaySeconds, _config.FuseBurnSpeed). LoadContent adds a TrailRenderer.

Update becomes a decision tree. This is the most important listing of the chapter, because the order of the branches is the design:

csharp
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
InputState input = _inputManager.GetCurrentInput();
Direction direction = _movementSystem.DetermineDirection(input);

bool playerMoved = Vector2.DistanceSquared(_gameSession.Player.Position, _lastPlayerPosition) > 0.0001f;
_lastPlayerPosition = _gameSession.Player.Position;

if (_trailSystem.HasActiveTrail)
{
    if (_fuseSystem.Update(_trailSystem.ActiveTrail, playerMoved, deltaTime))
    {
        // The fuse consumed the trail. Lives arrive in chapter 07, so for
        // now the work is simply lost: return the player to the wall
        // anchor where the trail began and discard the trail.
        _gameSession.Player.Position = _trailSystem.ActiveTrail?.Points[0] ?? _gameSession.Player.Position;
        _trailSystem.Cancel();
        _gameSession.Player.CurrentTrail = null;
        _fuseSystem.Reset();
        base.Update(gameTime);
        return;
    }

    if (direction == Direction.None)
    {
        base.Update(gameTime);
        return;
    }

    Vector2 intendedPosition = _movementSystem.CalculateNextPosition(_gameSession.Player.Position, direction, _gameSession.Player.Speed, deltaTime);
    if (_trailSystem.CanCompleteOnPath(intendedPosition, _gameSession.PlayableWallPath))
    {
        _gameSession.Player.Position = _gameSession.PlayableWallPath.Snap(intendedPosition);
        _trailSystem.Complete(_gameSession.Player.Position);
        _gameSession.Player.CurrentTrail = null;
        _fuseSystem.Reset();
    }
    else if (_trailSystem.TryGetSelfIntersection(intendedPosition, out Vector2 loopIntersection))
    {
        // A loop closes the trail. Capture arrives in chapter 06; for now
        // the loop simply ends the trail and the player returns to the
        // wall anchor where it began.
        Trail completedLoop = _trailSystem.Complete(loopIntersection);
        _gameSession.Player.Position = completedLoop.Points[0];
        _gameSession.Player.CurrentTrail = null;
        _fuseSystem.Reset();
    }
    else if (_trailSystem.CanAdvance(intendedPosition, _arenaSystem, direction, _gameSession.Player.CurrentDirection))
    {
        _gameSession.Player.Position = intendedPosition;
        _trailSystem.AppendPoint(_gameSession.Player.Position);
        _gameSession.Player.CurrentTrail = _trailSystem.ActiveTrail;

        // Only record the heading for accepted moves so a blocked
        // reversal cannot defeat the no-backtrack check next frame.
        _gameSession.Player.CurrentDirection = direction;
    }

    base.Update(gameTime);
    return;
}

_fuseSystem.Reset();
if (direction == Direction.None)
{
    base.Update(gameTime);
    return;
}

if (_movementSystem.TryMoveAlongPath(_gameSession.PlayableWallPath, _gameSession.Player.Position, direction, _gameSession.Player.Speed, deltaTime, out Vector2 nextOnPath))
{
    _gameSession.Player.Position = nextOnPath;
    _gameSession.Player.CurrentDirection = direction;
    base.Update(gameTime);
    return;
}

Vector2 candidate = _movementSystem.CalculateNextPosition(_gameSession.Player.Position, direction, _gameSession.Player.Speed, deltaTime);
if (_arenaSystem.IsUnclaimedWorld(candidate) && _trailSystem.TryStart(_gameSession.PlayableWallPath.Snap(_gameSession.Player.Position), candidate))
{
    _gameSession.Player.Position = candidate;
    _gameSession.Player.CurrentTrail = _trailSystem.ActiveTrail;
    _gameSession.Player.CurrentDirection = direction;
}

Read the bottom first. On the wall, a move along the path wins. A trail starts only when the path refuses the move and the candidate is unclaimed, and it is anchored to the snapped wall position. Read the top second. With a trail active, the fuse is checked before anything else, then completion (reconnect, then loop), then plain advance.

Step 4 - Draw the trail and the spark ​

Open Source/Game/LastPerimeterApp.cs again and find Draw. It draws the trail after the arena and before the player, and draws the spark when the fuse is active:

csharp
_arenaRenderer.Draw(_spriteBatch, _pixel, _arenaSystem.Bounds, _gameSession.PlayableWallPath);
_trailRenderer.Draw(_spriteBatch, _pixel, _gameSession.Player.CurrentTrail, _config.TrailColor);
if (_fuseSystem.IsActive)
{
    PrimitiveDrawing.DrawFilledCircle(_spriteBatch, _pixel, _fuseSystem.Position, 4f, Color.OrangeRed);
}

_playerRenderer.Draw(_spriteBatch, _pixel, _gameSession.Player, _config.PlayerColor);

TrailRenderer is a loop of DrawLine calls over consecutive points.

Step 5 - Build, test, run ​

Run these commands from the LastPerimeter folder:

bash
dotnet build
dotnet test
dotnet run --project Platforms/DesktopVK

dotnet test reports 23 passing tests. On Windows you can also run dotnet run --project Platforms/WindowsDX12.

Chapter snapshot ​

The matching buildable project is DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure; build and test it standalone with dotnet build and dotnet test. This chapter stages TrailTests, TrailSystemTests, TrailLoopTests, and FuseSystemTests on top of chapter 04's suite, bringing it to 23 passing tests. The full Player entity (with its trail reference) also replaces the trail-less chapter 01 staged version here.

Checkpoint ​

  1. In your LastPerimeter folder, run dotnet test: 23 tests pass, including CanAdvance_BlocksReversal_OntoActiveTrail, FusePausesWhenPlayerMoves_AndResumesOnStop, and Fuse_WarnsBeforeIgnition_AndIsExtinguishedWhenTheTrailEnds. If yours differ, compare your files with the snapshot in DOCUMENTATION/LastPerimeter-Source/05-Trail-Drawing-Self-Intersection-And-Fuse-Pressure.
  2. Run dotnet run --project Platforms/DesktopVK. Hold Down to slide part-way down the left wall, then hold Right to leave the wall and draw a yellow trail. Release the keys. Nothing shows at the one-second warning in this build, because the HUD and audio that use it arrive in chapter 08. After two seconds an orange-red spark appears at the trail anchor and crawls toward you (the three screenshots above). Hold Right again and the spark freezes where it is. Release and it resumes.
  3. Let the fuse reach you and confirm the trail is cancelled and you are back on the wall at the anchor. You do not die, because that is chapter 07.
  4. Draw to the right again, then press Left. The player does not back up along the trail.
  5. Draw a small square that crosses itself: hold Right, then Down, then Left for a shorter distance, then Up until you cross the first leg. The trail ends at the crossing and you return to the anchor. In chapter 06 that same loop will capture the square. Press Escape to close the game.

What you should have now ​

You now have:

  • trail start from the wall,
  • trail growth through unclaimed space,
  • reconnect completion,
  • loop completion through self-intersection,
  • fuse warning and fuse burn,
  • the no-backtrack rule.

Common mistakes ​

  • pausing the fuse from input state instead of displacement (holding a blocked key would freeze it),
  • testing infinite lines instead of finite segments for self-intersection,
  • comparing the newest segment with the segment it continues from (they always touch),
  • forgetting the minimum trail length, so a one-pixel wobble off the wall "completes" instantly,
  • updating CurrentDirection on refused moves.

Questions to think about ​

Ask yourself: Why is a visible fuse more effective than a simple timer in the HUD? The best answer is that it turns time pressure into spatial drama. Compare it with the plain countdown you would otherwise show.