Skip to content

Instantly share code, notes, and snippets.

@digitalWestie
Created September 2, 2026 12:26
Show Gist options
  • Select an option

  • Save digitalWestie/0d45b80daa17ada2dc6bcd7cf0db0640 to your computer and use it in GitHub Desktop.

Select an option

Save digitalWestie/0d45b80daa17ada2dc6bcd7cf0db0640 to your computer and use it in GitHub Desktop.
Spinel 2.5d rendering test
module SDL
ffi_lib "SDL2" # cat
ffi_const :INIT_VIDEO, 0x00000020
ffi_const :WINDOWPOS_CENTERED, 0x2FFF0000
ffi_const :QUIT, 0x100
ffi_const :MOUSEBUTTONDOWN, 0x401
ffi_const :MOUSEMOTION, 0x400
ffi_const :KEYDOWN, 0x300
ffi_const :KEYUP, 0x301
ffi_func :SDL_Init, [:uint32], :int
ffi_func :SDL_CreateWindow, [:str, :int, :int, :int, :int, :uint32], :ptr
ffi_func :SDL_CreateRenderer, [:ptr, :int, :uint32], :ptr
ffi_func :SDL_SetRenderDrawColor, [:ptr, :uint8, :uint8, :uint8, :uint8], :int
ffi_func :SDL_RenderClear, [:ptr], :int
ffi_func :SDL_RenderDrawPoint, [:ptr, :int, :int], :int
ffi_func :SDL_RenderPresent, [:ptr], :int
ffi_func :SDL_RenderSetLogicalSize, [:ptr, :int, :int], :int
ffi_func :SDL_RenderSetIntegerScale, [:ptr, :int], :int
ffi_func :SDL_PollEvent, [:ptr], :int
ffi_func :SDL_GetTicks, [], :uint32
ffi_func :SDL_Quit, [], :void
# ffi_buffer allocates a byte blob for SDL_Event; ffi_read_* defines helpers
# that pull typed values out at known byte offsets (see SDL_events.h).
ffi_buffer :event, 56
ffi_read_u32 :event_type, 0 # e.type
ffi_read_i32 :event_x, 20 # e.button.x
ffi_read_i32 :event_y, 24 # e.button.y
ffi_read_i32 :event_key, 20 # e.key.keysym.sym
end
# Keycodes from SDL_keycode.h — Ruby-only; not exported from libSDL2.
KEY_W = 'w'.ord
KEY_A = 'a'.ord
KEY_S = 's'.ord
KEY_D = 'd'.ord
KEY_LEFT = 0x40000050 # SDL_SCANCODE_LEFT (80)
KEY_RIGHT = 0x4000004F # SDL_SCANCODE_RIGHT (79)
KEY_UP = 0x40000052 # SDL_SCANCODE_UP (82)
KEY_DOWN = 0x40000051 # SDL_SCANCODE_DOWN (81)
SDL.SDL_Init(SDL::INIT_VIDEO)
GAME_WIDTH = 320
GAME_HEIGHT = 240
SCALE = 3
WINDOW_WIDTH = GAME_WIDTH * SCALE
WINDOW_HEIGHT = GAME_HEIGHT * SCALE
HALF_SW = GAME_WIDTH / 2
HALF_SH = GAME_HEIGHT / 2
BACKGROUND_COLOR = [0, 0, 60, 255] # dark blue
WALL_COLOR = [255, 255, 0, 255] # bright yellow
WALL_COLOR_2 = [0, 255, 255, 255] # bright green
DEBUG_LOG = false
NEAR = 1.0 # minimum camera depth before perspective divide
# One-sided wall linedef in map space (start → end). Front is on the right
# when walking start to end: for this vertical wall, front = east (x > 40).
WALL_X = 40
WALL_Y1 = 10
WALL_Y2 = 290
window = SDL.SDL_CreateWindow(
"draw",
SDL::WINDOWPOS_CENTERED, SDL::WINDOWPOS_CENTERED,
WINDOW_WIDTH, WINDOW_HEIGHT, 0
)
renderer = SDL.SDL_CreateRenderer(window, -1, 0)
SDL.SDL_RenderSetLogicalSize(renderer, GAME_WIDTH, GAME_HEIGHT)
SDL.SDL_RenderSetIntegerScale(renderer, 1)
keys = { w: 0, s: 0, a: 0, d: 0, sl: 0, sr: 0, pu: 0, pd: 0 }
player = { x: 70, y: -110, z: 20, a: 0, l: 0 } # x/y/z position; a = facing (degrees); l = pitch
# sin/cos lookup tables indexed by degrees (player[:a] is in degrees, not radians)
COS_TABLE = []
SIN_TABLE = []
for i in 0..360
COS_TABLE[i] = Math.cos(i * Math::PI / 180)
SIN_TABLE[i] = Math.sin(i * Math::PI / 180)
end
def draw_at_point(r, x, y, color = [0, 0, 0, 255])
SDL.SDL_SetRenderDrawColor(r, color[0], color[1], color[2], color[3])
SDL.SDL_RenderDrawPoint(r, x, y)
end
def debug_log(msg)
puts msg if DEBUG_LOG
end
def fmt_f(v)
format("%.1f", v)
end
def log_player(action, player)
debug_log(
"#{action}: pos=(#{fmt_f(player[:x])},#{fmt_f(player[:y])}) a=#{player[:a]} l=#{player[:l]} z=#{player[:z]}"
)
end
def set_key(keys, key, pressed)
value = 0
if pressed
value = 1
end
case key
when KEY_W then keys[:w] = value
when KEY_S then keys[:s] = value
when KEY_A then keys[:a] = value
when KEY_D then keys[:d] = value
when KEY_LEFT then keys[:sl] = value
when KEY_RIGHT then keys[:sr] = value
when KEY_UP then keys[:pu] = value
when KEY_DOWN then keys[:pd] = value
end
end
def move_player(player, keys)
turn_speed = 4
if keys[:sl] == 1
player[:a] = player[:a] - turn_speed
player[:a] = player[:a] + 360 if player[:a] < 0
end
if keys[:sr] == 1
player[:a] = player[:a] + turn_speed
player[:a] -= 360 if player[:a] > 360
end
pitch_speed = 4
pitch_min = -32
pitch_max = 32
if keys[:pu] == 1
player[:l] = player[:l] + pitch_speed
player[:l] = pitch_max if player[:l] > pitch_max
end
if keys[:pd] == 1
player[:l] = player[:l] - pitch_speed
player[:l] = pitch_min if player[:l] < pitch_min
end
# a=0 faces map +Y; W moves along (sin(a), cos(a))
move_speed = 5
dx = SIN_TABLE[player[:a]] * move_speed
dy = COS_TABLE[player[:a]] * move_speed
if keys[:w] == 1
player[:x] += dx
player[:y] += dy
end
if keys[:s] == 1
player[:x] -= dx
player[:y] -= dy
end
strafe_speed = 5
if keys[:d] == 1
player[:x] += COS_TABLE[player[:a]] * strafe_speed
player[:y] -= SIN_TABLE[player[:a]] * strafe_speed
end
if keys[:a] == 1
player[:x] -= COS_TABLE[player[:a]] * strafe_speed
player[:y] += SIN_TABLE[player[:a]] * strafe_speed
end
end
def clear_background(r)
SDL.SDL_SetRenderDrawColor(r, BACKGROUND_COLOR[0], BACKGROUND_COLOR[1], BACKGROUND_COLOR[2], BACKGROUND_COLOR[3])
SDL.SDL_RenderClear(r)
end
# DOOM-style one-sided wall test: is the player on the front of the linedef?
# Cross product sign - vertex order matters. > 0 front, <= 0 back (skip draw).
def player_on_front_of_line?(px, py, lx1, ly1, lx2, ly2)
side = (px - lx1) * (ly2 - ly1) - (py - ly1) * (lx2 - lx1)
side > 0
end
def draw_wall(r, x1, x2, b1, b2, x3, x4, t1, t2)
# Clip because we never want to draw below 0 or beyond the screen's width
x1 = 1 if x1 < 1
x2 = 1 if x2 < 1
x1 = GAME_WIDTH-1 if x1 > GAME_WIDTH-1
x2 = GAME_WIDTH-1 if x2 > GAME_WIDTH-1
dyb = b2 - b1 # y distance of bottom line
dyt = t2 - t1 # y distance of top line
dx = x2 - x1
dx = 1 if dx == 0 # min distance of 1 pixel - prevents division by zero
xs = x1 # hold initial x coordinate
# draw x verticle lines
range = x1.to_i..(x2-1).to_i
range.each do |x|
y1 = dyb * (x - xs) / dx + b1
y2 = dyt * (x - xs) / dx + t1
# Y clipping - we don't want to draw below 0 or beyond the screen's height
y1 = 1 if y1 < 1
y2 = 1 if y2 < 1
y1 = GAME_HEIGHT-1 if y1 > GAME_HEIGHT-1
y2 = GAME_HEIGHT-1 if y2 > GAME_HEIGHT-1
for y in y1..(y2-1) do
if x % 2 == 0 && y % 2 == 0
draw_at_point(r, x, y, WALL_COLOR)
else
draw_at_point(r, x, y, WALL_COLOR_2)
end
end
end
end
# Slide a corner that is at/before the near plane along the edge to wy = NEAR.
# y_* is camera depth (wy). Returns nil if the whole edge is at or behind NEAR.
def clip_to_near_plane(x_near, y_near, z_near, x_far, y_far, z_far)
return x_near, y_near, z_near if y_near > NEAR
return nil if y_far <= NEAR
t = (NEAR - y_near) / (y_far - y_near)
x_near = x_near + t * (x_far - x_near)
y_near = NEAR
z_near = z_near + t * (z_far - z_near)
return x_near, y_near, z_near
end
def draw_3d(r, player)
# World space → Player-relative → Camera space → Screen space
# (fixed map) (subtract pos) (rotate) (perspective)
# Remember to think of player in 2d space @ X,Y where A is angle of rotation
# 1. One-sided wall: skip if player is on the back of the linedef.
# Later: loop over many walls, each with lx1/ly1/lx2/ly2 and a one_sided flag.
if player_on_front_of_line?(player[:x], player[:y], WALL_X, WALL_Y1, WALL_X, WALL_Y2) == false
return
end
# Working arrays — hold camera-space values after rotation, then screen coords
wx = [0, 0, 0, 0]
wy = [0, 0, 0, 0]
wz = [0, 0, 0, 0]
# Player-relative: where is each wall corner relative to the player on flat map?
x1 = WALL_X - player[:x]
y1 = WALL_Y1 - player[:y]
x2 = WALL_X - player[:x]
y2 = WALL_Y2 - player[:y]
# We are still thinking in map space, not yet projection, but now we need to rotate.
# Before rotation: position in map-aligned coords (x1, y1)
# After rotation: position in you-aligned coords (wx, wy)
# wx is how far left or right of centre view
# wy is how far in front
wx[0] = x1 * COS_TABLE[player[:a]] - y1 * SIN_TABLE[player[:a]]
wx[1] = x2 * COS_TABLE[player[:a]] - y2 * SIN_TABLE[player[:a]]
wx[2] = wx[0]
wx[3] = wx[1]
wy[0] = y1 * COS_TABLE[player[:a]] + x1 * SIN_TABLE[player[:a]]
wy[1] = y2 * COS_TABLE[player[:a]] + x2 * SIN_TABLE[player[:a]]
wy[2] = wy[0]
wy[3] = wy[1]
# wz is the vertical axis. Now thinking more 3d than 2d.
# We figure out relative position of wall points to player eye height (z)
# Height relative to the player's eye; pitch (l) tilts the view
# wx controls horizontal distance from centre of view (screen X)
# wy controls is how far forward / back (depth as divider only)
# wz is vertical distance (screen Y)
wz[0] = 0 - player[:z] + ((player[:l] * wy[0]) / 32.0)
wz[1] = 0 - player[:z] + ((player[:l] * wy[1]) / 32.0)
wz[2] = wz[0] + 40
wz[3] = wz[1] + 40 # top line has different z value
# Perspective projection divides by depth (wy). Clip corners at/before NEAR;
# skip if the whole wall edge is behind the camera.
if wy[0] <= 0 && wy[1] <= 0
debug_log("draw_3d skip: wall behind player depth=[#{fmt_f(wy[0])},#{fmt_f(wy[1])}]")
return
end
if wy[0] <= NEAR
if wy[1] <= NEAR
debug_log("draw_3d skip: bottom edge at/before near plane depth=[#{fmt_f(wy[0])},#{fmt_f(wy[1])}]")
return
end
bottom = clip_to_near_plane(wx[0], wy[0], wz[0], wx[1], wy[1], wz[1])
wx[0] = bottom[0]
wy[0] = bottom[1]
wz[0] = bottom[2]
top = clip_to_near_plane(wx[2], wy[2], wz[2], wx[3], wy[3], wz[3])
wx[2] = top[0]
wy[2] = top[1]
wz[2] = top[2]
end
if wy[1] <= NEAR
if wy[0] <= NEAR
debug_log("draw_3d skip: bottom edge at/before near plane depth=[#{fmt_f(wy[0])},#{fmt_f(wy[1])}]")
return
end
bottom = clip_to_near_plane(wx[1], wy[1], wz[1], wx[0], wy[0], wz[0])
wx[1] = bottom[0]
wy[1] = bottom[1]
wz[1] = bottom[2]
top = clip_to_near_plane(wx[3], wy[3], wz[3], wx[2], wy[2], wz[2])
wx[3] = top[0]
wy[3] = top[1]
wz[3] = top[2]
end
depth_const = 200
# bottom line
sx0 = wx[0] * depth_const / wy[0] + HALF_SW
sy0 = wz[0] * depth_const / wy[0] + HALF_SH
sx1 = wx[1] * depth_const / wy[1] + HALF_SW
sy1 = wz[1] * depth_const / wy[1] + HALF_SH
# top line
sx2 = wx[2] * depth_const / wy[2] + HALF_SW
sy2 = wz[2] * depth_const / wy[2] + HALF_SH
sx3 = wx[3] * depth_const / wy[3] + HALF_SW
sy3 = wz[3] * depth_const / wy[3] + HALF_SH
draw_wall(r, sx0, sx1, sy0, sy1, sx2, sx3, sy2, sy3)
end
# Frame-limited loop (3DSage style): only run update + draw when enough
# milliseconds have elapsed (~20 FPS at 50 ms). Diverges from the original
# DOOM engine, which advances simulation in fixed 35 Hz "tics" (I_GetTime),
# may run several tics per loop to catch up when behind, and renders after
# sim — simulation rate and draw rate are decoupled.
frame_ms = 100 # 50ms = 20fps
current_frame_ms = 0
previous_frame_ms = 0
running = true
while running
while SDL.SDL_PollEvent(SDL.event) != 0
type = SDL.event_type(SDL.event)
if type == SDL::QUIT
running = false
break
end
if type == SDL::KEYDOWN
set_key(keys, SDL.event_key(SDL.event), true)
end
if type == SDL::KEYUP
set_key(keys, SDL.event_key(SDL.event), false)
end
# In order to draw the corner points of a square,
# we need to define mid point, size and offset from there
# a function that we can then call to draw the square
# then, a way of modifying the square
# a way of clearing the window and re-rendering
end
current_frame_ms = SDL.SDL_GetTicks() # How many ms have passed since the start of the program
if current_frame_ms - previous_frame_ms >= frame_ms
clear_background(renderer)
move_player(player, keys)
draw_3d(renderer, player)
SDL.SDL_RenderPresent(renderer)
previous_frame_ms = current_frame_ms
end
end
SDL.SDL_Quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment