SlimePlatformer/Effects/pixel_stream.gd
SnekInAScarf 32d82b4bd1 Rework manual tubes: steerable goo with a leader indicator
Manual tubes (TubeSteer):
- The slime is pulled fully into the tube on entry; tubes too short for it
  squash it to fit, with a few pixels poking out of each mouth.
- A leader slides quickly through the goo without moving it, and drags the
  goo at normal speed once past an end. At covered junctions it can turn into
  another arm, or pull into an empty branch, draining the goo from all sides.
- Only coloured pixels go in; a black outline is drawn around the goo, with
  rounded ends in the tube.
- The leader is a pulsing circle; colour, border colour and radius are set
  under "Tube Indicator" on the Player.

Tiles and level:
- Plain tube tiles are now manual, green ones automatic. Test level tubes
  repainted plain so they stay manual.

Also included (earlier work): goo tube prototype (TubeGoo, purple tiles) and a
max length for the automatic pixel stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:36:36 -08:00

200 lines
7.9 KiB
GDScript
Executable file

class_name PixelStream
extends Node2D
# Takes a sprite's current frame apart into its pixels and pours them along a
# path as a stream, then puts them back together as a chosen frame somewhere
# else. Used for the slime squeezing through tubes.
# Every pixel sets off at once: they're drawn into the entry mouth nearest-first,
# flow along the path a few abreast, and fly out of the exit mouth so that they
# all land at the same moment.
# Pixels keep their colours on the way, and blend into the colour of the spot
# they land on, so the sprite reforms exactly.
# Watch isFinished to know when every pixel is back in place.
const SPEED = 240.0 # How fast pixels flow along the path, in px/s.
const ROW_SPACING = 1.0 # Gap between rows of pixels in the stream, unless that would make it too long.
const GATHER_TIME = 0.12 # How long the nearest pixels take to reach the entry mouth.
const LAND_TIME = 0.15 # How long the last pixels out take to reach their spot.
var isFinished := false
var _startColors := PackedColorArray()
var _endColors := PackedColorArray()
var _starts := PackedVector2Array() # Where each pixel was in the sprite we took apart.
var _ends := PackedVector2Array() # Where it goes in the sprite we're putting back together.
var _lanes := PackedFloat32Array() # How far left of the path's middle it flows.
var _rows := PackedInt32Array() # Its place in the stream: row 0 goes in first.
var _rowCount := 0
var _rowSpacing := ROW_SPACING # Closer if needed to keep the stream within maxLength.
var _path := PackedVector2Array()
var _pathDistances := PackedFloat32Array() # How far along the path each point is.
var _time := 0.0
# path: global points from the entry mouth to the exit mouth.
# width: how wide the tube is. The stream is this many pixels across.
# maxLength: the longest the stream can be. Rows bunch up (overlapping) to fit.
# endTransform: the sprite's global transform once it's back together.
# endFrame: the frame it reforms as, so it matches what the sprite shows next.
func start(sprite: Sprite2D, path: PackedVector2Array, width: float, maxLength: float,
endTransform: Transform2D, endFrame: int) -> void:
top_level = true
global_position = Vector2.ZERO
z_index = sprite.z_index + 1
_path = path
_pathDistances.append(0.0)
for i in range(1, path.size()):
_pathDistances.append(_pathDistances[i - 1] + path[i - 1].distance_to(path[i]))
# Where the sprite is drawn now: snapped to whole pixels like the renderer does.
var startTransform := sprite.get_global_transform()
startTransform.origin = startTransform.origin.round()
var from := get_frame_pixels(sprite, sprite.frame, startTransform)
var to := get_frame_pixels(sprite, endFrame, endTransform)
if from.colors.is_empty() or to.colors.is_empty():
isFinished = true
return
_pair_pixels(from, to, maxi(int(width), 1))
_rowSpacing = minf(ROW_SPACING, maxLength / _rowCount)
# The frame's opaque pixels (black ones too: they're the eyes) as .positions
# (global, through `spriteTransform`) and .colors. TubeSteer uses this too.
static func get_frame_pixels(sprite: Sprite2D, frame: int, spriteTransform: Transform2D) -> Dictionary:
var positions := PackedVector2Array()
var colors := PackedColorArray()
var image := _get_frame_image(sprite, frame)
if image != null:
image.convert(Image.FORMAT_RGBA8)
var size := image.get_size()
for y in size.y:
for x in size.x:
var color := image.get_pixel(x, y)
if color.a < 0.5:
continue
# Pixel centre in the sprite's local space (it's centered).
var local := Vector2(x, y) + Vector2.ONE * 0.5 - Vector2(size) / 2.0
if sprite.flip_h:
local.x = -local.x
if sprite.flip_v:
local.y = -local.y
positions.append(spriteTransform * (local + sprite.offset))
colors.append(color)
return {positions = positions, colors = colors}
# The pixels of one cell of the sprite's hframes x vframes sheet.
static func _get_frame_image(sprite: Sprite2D, frame: int) -> Image:
var image := sprite.texture.get_image()
if image == null:
return null
if image.is_compressed():
image.decompress()
var frameSize := image.get_size() / Vector2i(sprite.hframes, sprite.vframes)
var frameCoords := Vector2i(frame % sprite.hframes, floori(float(frame) / sprite.hframes))
return image.get_region(Rect2i(frameCoords * frameSize, frameSize))
# Gives each pixel a place in the stream and a spot in the reformed sprite. The
# pixels nearest the entry go in first, and the first ones out land furthest
# from the exit, so pixels don't cross paths much.
# If one frame has more pixels, some of the other's are doubled up so none go
# missing from either.
func _pair_pixels(from: Dictionary, to: Dictionary, laneCount: int) -> void:
var fromOrder := _sorted_by_distance(from.positions, _path[0], false)
var toOrder := _sorted_by_distance(to.positions, _path[_path.size() - 1], true)
var fromCount := fromOrder.size()
var toCount := toOrder.size()
var count := maxi(fromCount, toCount)
for k in count:
var i: int = fromOrder[int(float(k) * fromCount / count)]
var j: int = toOrder[int(float(k) * toCount / count)]
_starts.append(from.positions[i])
_startColors.append(from.colors[i])
_ends.append(to.positions[j])
_endColors.append(to.colors[j])
_lanes.append((k % laneCount) - (laneCount - 1) / 2.0)
_rows.append(floori(float(k) / laneCount))
_rowCount = _rows[count - 1] + 1
# Indices of `points`, nearest to `target` first (or furthest first).
func _sorted_by_distance(points: PackedVector2Array, target: Vector2, furthestFirst: bool) -> Array:
var order := range(points.size())
order.sort_custom(func(a: int, b: int) -> bool:
var aDistance := points[a].distance_squared_to(target)
var bDistance := points[b].distance_squared_to(target)
if furthestFirst:
return aDistance > bDistance
return aDistance < bDistance)
return order
func _process(delta: float) -> void:
if isFinished:
return
_time += delta
if _time >= _duration():
isFinished = true
queue_redraw()
# ---- Timing ----
# When a row reaches the entry mouth. Each row is _rowSpacing behind the last.
func _enter_time(row: int) -> float:
return GATHER_TIME + row * _rowSpacing / SPEED
# When a row leaves the exit mouth.
func _exit_time(row: int) -> float:
return _enter_time(row) + _tube_length() / SPEED
# When every pixel is back in place.
func _duration() -> float:
return _exit_time(_rowCount - 1) + LAND_TIME
func _draw() -> void:
var tubeLength := _tube_length()
var duration := _duration()
for i in _starts.size():
var row := _rows[i]
var enterTime := _enter_time(row)
var exitTime := _exit_time(row)
var spot: Vector2
var color := _startColors[i]
if _time < enterTime:
# Drawn in, speeding up towards the mouth.
var progress := _time / enterTime
spot = _starts[i].lerp(_point_on_path(0.0, _lanes[i]), progress * progress)
elif _time < exitTime:
spot = _point_on_path((_time - enterTime) * SPEED, _lanes[i])
else:
# Out to its spot, slowing down to land with everyone else.
var progress := minf((_time - exitTime) / (duration - exitTime), 1.0)
var eased := 1.0 - (1.0 - progress) * (1.0 - progress)
spot = _point_on_path(tubeLength, _lanes[i]).lerp(_ends[i], eased)
color = _startColors[i].lerp(_endColors[i], eased)
draw_rect(Rect2(spot.floor(), Vector2.ONE), color)
# The point `distance` along the path, moved `lane` to the left of travel.
func _point_on_path(distance: float, lane: float) -> Vector2:
var segment := 0
while segment < _path.size() - 2 and distance > _pathDistances[segment + 1]:
segment += 1
var from := _path[segment]
var to := _path[segment + 1]
var segmentLength := _pathDistances[segment + 1] - _pathDistances[segment]
var progress := 0.0
if segmentLength > 0.0:
progress = clampf((distance - _pathDistances[segment]) / segmentLength, 0.0, 1.0)
var left := (to - from).normalized().orthogonal() # Left of travel, with y down.
return from.lerp(to, progress) + left * lane
func _tube_length() -> float:
return _pathDistances[_pathDistances.size() - 1]