2D Swift Sprite Engine
Pure-Swift, prefix-free 2D rendering for Linux, macOS, and iOS. See ARCHITECTURE.md for the full design and roadmap.
| Module | Description |
|---|---|
SpriteCore |
2D math (Matrix3x3, Transform2D, Rect, Color), Texture, TextureAtlas, WarpGeometryGrid, SpriteBatcher, and the SpriteRenderBackend protocol. No platform dependencies. |
SpriteGraph |
Scene tree: Scene (scale modes, Duration-driven update loop, physicsWorld), Node (@Node2DBuilder, physicsBody), Sprite (9-patch centerRect), Label (bitmap / SDF BitmapFont), Camera, CropNode (geometric masking), ShapeNode (filled and stroked Paths), ParticleEmitter (structure-of-arrays simulation, keyframe sequences), TileMap / TileSet (editable grids with cached quad chunks), LightNodes for lit sprites, composable value-type Actions, Constraints on position, distance, orientation and rotation, AudioNodes, VideoNodes, FieldNodes, and EffectNodes that flatten their children. |
SpritePhysics |
Swift API over Box2D v3: PhysicsWorld, PhysicsBody, PhysicsShape (including bodies traced from an image's alpha), PhysicsCategory masks, contact/sensor notifications, ray casts, pin (with angle limits) / fixed / distance / spring / sliding joints, and force fields. |
SpriteFormats |
PNG decoding via swift-png with conversion of color-tagged images to sRGB, SpriteKit .atlas / .atlasc, libGDX / Spine .atlas, Aseprite JSON sprite sheets with tag animations and 9-patch slices, finite orthogonal Tiled .tmx / .tsx maps, and an initial SpriteKit .sks scene archive reader using Foundation. |
SpriteText |
TrueType / OpenType label fonts: RasterizedFont draws a face's glyphs into a BitmapFont atlas with swift-freetype and shapes text with swift-harfbuzz, and FontCatalog finds faces by PostScript or family name in font folders. |
SpriteSDL |
SDL3 window, input events, and batch rendering through PureSwift/SDL's SDL3Swift product (3.3.0+), with lit sprites drawn by a fragment shader on SDL's GPU renderer, and custom shaders and lighting on its OpenGL renderer. |
SpriteAudio |
Sound playback through SDL_mixer: AudioPlayer decodes WAV, AIFF, MP3, Ogg Vorbis and FLAC files and mixes overlapping plays, and SceneAudioPlayer plays a scene's audio nodes. |
SpriteVideo |
Video decoding with FFmpeg: VideoDecoder reads a video file's frames in RGBA, VideoSoundDecoder its sound, and SceneVideoPlayer shows a scene's video nodes in textures of a render backend and plays their sound through SpriteAudio. |
sprite-viewer |
SDL3 demo and inspector for scenes and the batch renderer. |
- Swift 6.4, macOS 15 / iOS 18 or Linux (the primary target)
- zlib for PNG decoding (swift-png's default
SystemZlibtrait;apt install zlib1g-devon Linux) - Box2D 3.x for
SpritePhysics(andSpriteGraph)- macOS:
brew install box2d - Linux: build Box2D 3.x from source (distribution packages are still 2.4)
- macOS:
- FreeType for
SpriteTextandsprite-viewer- macOS:
brew install freetype - Linux:
apt install libfreetype6-dev
- macOS:
- HarfBuzz for
SpriteTextandsprite-viewer- macOS:
brew install harfbuzz - Linux:
apt install libharfbuzz-dev
- macOS:
- SDL 3.4 or later for
SpriteSDLandsprite-viewer- macOS:
brew install sdl3 - Linux: build SDL 3.4 from source with CMake where the distribution ships an older SDL3 (Debian 13 and current Ubuntu ship 3.2)
- macOS:
- SDL3_mixer for
SpriteAudio,SpriteVideoandsprite-viewer - FFmpeg 7 or later for
SpriteVideoandsprite-viewer- macOS:
brew install ffmpeg - Linux:
apt install libavformat-dev libavcodec-dev libswscale-dev libswresample-dev libavutil-dev
- macOS:
import SpriteGraph
import SpriteSDL
let window = try SDLWindow(title: "Demo", width: 800, height: 600)
let backend = SDLRenderBackend(window: window)
let font = try BitmapFont.debug(backend: backend)
let scene = Scene(size: [800, 600])
scene.scaleMode = .aspectFit
scene.addChildren {
Label(text: "HELLO", font: font, fontSize: 40)
Sprite(color: .red, size: [64, 64])
}
scene.children[1].run(.repeatForever(.sequence([
.move(by: [200, 0], duration: .seconds(1)),
.move(by: [-200, 0], duration: .seconds(1)),
]).timingMode(.easeInEaseOut)))
try scene.present(on: backend, deltaTime: .milliseconds(16))SpriteText rasterizes TrueType and OpenType fonts (including .ttc collections) into
BitmapFont atlases for Label. Rasterize at the size labels draw at: fontSize scales
the atlas, so larger sizes magnify it.
import SpriteText
let catalog = try FontCatalog(directories: FontCatalog.systemDirectories)
if let face = catalog.face(named: "HelveticaNeue-Bold") {
let font = try BitmapFont.rasterized(path: face.path, faceIndex: face.index, pixelSize: 48, backend: backend)
scene.addChild(Label(text: "Score: 0", font: font, fontSize: 48))
}Glyphs are drawn without hinting and placed with unrounded advances, as Core Text lays out
text. Labels are shaped with HarfBuzz: OpenType kerning (GPOS as well as the legacy kern
table), ligatures and contextual forms apply, marks sit over their bases, and right-to-left
scripts run in visual order. The atlas holds each character's glyph, printable ASCII and
Latin-1 by default, plus every glyph the font's substitutions can turn them into, so shaping
never needs a glyph it lacks. Pass features (such as Feature("-liga")) to change what
shaping applies, or shapes: false to place a glyph per character with kern table kerning.
A BitmapFont takes any TextShaper; fonts without one, such as BMFont atlases, place a glyph
per character. FontCatalog looks up PostScript names first, then family names (preferring
the regular face), ignoring case, spaces and hyphens.
The tutorial scenes' fonts (Helvetica Neue, Chalkduster and Avenir Next) kern through their
kern tables, so shaping draws them as before; fonts that kern only in GPOS, such as Inter,
now kern.
A label's alignsToGlyphBounds lays text out as SKLabelNode does, as measured. On one
line (numberOfLines of 1) it aligns the drawn glyphs instead of advances and line metrics:
they start or end a pixel from the origin or are centered on it, the same applies vertically
for center, top and bottom alignment, newlines are dropped and nothing wraps. With more lines
the text is a block two points wider than its widest line and two points taller than its
lines, each its font's rounded ascent, descent and line gap tall with its baseline its descent
above its bottom; the alignment modes place the block, baseline alignment as bottom alignment
does, and explicit lines aren't limited. Scene archive labels use it.
attributedText draws runs of text (Label.TextRun) in their own fonts, sizes, colors and
kerning, multiplied by the label's color. Runs share a baseline, and a line is as tall as its
tallest run, counting the newline that ends it. A run's paragraph alignment places its lines
within a block of several lines, and its lineSpacing goes below them.
scene.physicsBody = PhysicsBody(edgeLoopFrom: Rect(x: 0, y: 0, width: 800, height: 600))
let crate = Sprite(texture: crateTexture)
crate.physicsBody = PhysicsBody(rectangleOf: crate.size)
crate.physicsBody?.contactTestBitMask = .all
scene.addChild(crate)
scene.physicsWorld.onContactBegin = { contact in
let sparks = ParticleEmitter()
sparks.position = contact.contactPoint
sparks.particleTexture = sparkTexture
sparks.particleBirthRate = 1000
sparks.numParticlesToEmit = 20
sparks.emissionAngleRange = 2 * .pi
sparks.particleSpeed = 200
sparks.particleAlphaSequence = KeyframeSequence([(0, 1), (1, 0)])
scene.addChild(sparks)
}A body can follow a sprite's outline, like SKPhysicsBody(texture:alphaThreshold:size:):
let rock = Sprite(texture: rockTexture)
rock.physicsBody = PhysicsBody(outlineOf: rockPixels, alphaThreshold: 0.5, size: rock.size)PhysicsShape(outlineOf:alphaThreshold:size:tolerance:) traces the image's largest region
with alpha above the threshold through the centers of its edge pixels, fills its holes,
simplifies the outline to within a pixel and splits it into convex polygons Box2D accepts,
as SpriteKit does. Of 40 tutorial sprites, 35 trace within 3% of SpriteKit's area and 38
within 5%. The other two are a 57x10 sprite and an image whose SpriteKit pieces overlap, adding
up to more than the image's area. Tracing a 2048x1536 image takes under a second.
A FieldNode pushes physics bodies around it, like SKFieldNode:
let well = FieldNode.radialGravity()
well.strength = 3
well.region = .circle(radius: 200)
well.position = [400, 300]
scene.addChild(well)
let wind = FieldNode.linearGravity(vector: [2, 0])
wind.categoryBitMask = PhysicsCategory(bit: 1)
scene.addChild(wind)
leaf.physicsBody?.fieldBitMask = PhysicsCategory(bit: 1)The kinds match SpriteKit's fields:
- linear gravity, radial gravity and velocity
- drag, vortex, noise and turbulence
- spring, electric and magnetic, which act on a body's
charge - custom fields, which compute their own force
Every kind's strength is in SpriteKit's units, so archived fields push bodies as they do in SpriteKit. The laws below were measured from SpriteKit, which counts 150 points as a meter:
- Linear and radial gravity accelerate every mass alike.
- Drag is a force of the strength times the square of the speed.
- A vortex's force is the strength divided by the body's mass.
- A spring's force grows with distance, since its default falloff is −1.
- A velocity field sets a body's velocity and ignores strength and falloff.
Every kind divides its force by the distance in meters raised to the falloff, and never
counts a distance below minimumRadius.
Each field acts where its region contains a body's center, in the node's own coordinates.
Turning or scaling the node turns or scales its field. A body is moved by fields whose
categoryBitMask shares a bit with the body's fieldBitMask. A body inside an exclusive
field's region is moved by that field alone. Static bodies don't move, and paused or hidden
field nodes still act, as in SpriteKit.
How closely this matches SpriteKit:
- Each kind's first frame matches SpriteKit's change in velocity to within 2%.
- In a fixture with one body per field, the bodies are within 1.5 points of SpriteKit's after a second. The spring and magnetic bodies are the exceptions, within 7 points, because they swing around and the two engines' integrators drift apart.
- Noise and turbulence use this engine's own smooth noise, at the strength measured from SpriteKit, so they can't match its exact pushes.
- SpriteKit's vortex does nothing below a mass-dependent strength; this engine always pushes.
- Fields don't act on particles.
A LightNode lights sprites whose lightingBitMask shares a bit with its categoryBitMask, like
SKLightNode, and a sprite's normalTexture gives its surface the bumps the light picks out:
let lamp = LightNode()
lamp.position = player.position
lamp.falloff = 1
lamp.ambientColor = Color(red: 0.15, green: 0.15, blue: 0.15, alpha: 1)
scene.addChild(lamp)
wall.lightingBitMask = 1
wall.normalTexture = try backend.makeTexture(wallNormals, filtering: .linear)A lit pixel is its color times the ambient light plus each light's color, scaled by how
squarely the light faces the surface, plus a white highlight where the light reflects toward
the viewer. As in SpriteKit, lighting distances follow the render target rather than the
scene: lights shine from 0.255 of its shorter side above the sprites, and a falloff of f
keeps a light at full strength out to 0.495 / f of that side, beyond which it fades with the
square of the distance. These constants, the highlight's strength and sharpness, and the
behavior of sprites no enabled light reaches (they draw unlit) were measured from SpriteKit;
a fixture with falloff, ambient light, normal maps, a rotated sprite and several lights matches
it to a mean channel difference of 0.70. Up to 8 lights reach a sprite.
Sprites whose shadowCastBitMask shares a bit with a light's categoryBitMask cast its
shadows. As measured from SpriteKit, a pixel is in shadow when an opaque pixel of a caster lies
between it and the light, however far, and is mixed with the light's shadowColor by its alpha
(half-transparent black by default). Shadows from one light don't darken twice where they
overlap, while each light's shadows darken again. They shade everything at a z position of 0
or below, background included, and nothing above, wherever the casters are; a sprite's
shadowedBitMask doesn't change this, as in SpriteKit. Casters inside effect nodes don't cast
shadows. Each light's casters are drawn opaque into an offscreen layer, and a fragment shader on
the GPU or OpenGL renderer walks from each pixel toward the light through the casters' bounds;
other renderers draw no shadows. A fixture with two lights, one with a colored shadow, square,
concave and untextured casters, and lit, unlit and raised sprites matches SpriteKit to a mean
channel difference of 1.47 on macOS and 1.39 on Linux; SpriteKit's shadow edges sit up to a few
pixels from the exact ones, far from their casters, and so differ along the edges. Inside a
translucent caster, SpriteKit shades from part way across it, which isn't reproduced.
Inside an effect node, SpriteKit lights sprites in the image the node draws, which covers just its children: a light keeps its place as a fraction of the screen and shines at that fraction of the image, from a height, and with a falloff, scaled to the image's shorter side. It also measures distances by the shape of the last effect node drawn in the frame, counting parents before children and skipping hidden ones, even one with nothing lit: after a square effect node on a 3:2 screen, horizontal distances count two thirds as much everywhere. Both are reproduced; a fixture with lit sprites on screen and in three effect nodes, one with a normal map and one widened by another child, matches SpriteKit to a mean channel difference of 0.45 on the GPU and OpenGL renderers.
Lighting needs a fragment shader, which SDL runs on its GPU renderer from SDL 3.4; the shader
ships for Metal and Vulkan (SPIR-V), so Direct3D 12 draws lit sprites unlit. SDLRenderBackend windows use that renderer when SDL offers it,
unless SDL_RENDER_DRIVER chooses another or the window prefers another with
preferredRenderDriver. SDL's OpenGL renderer lights sprites too, with the same shader in
GLSL 1.20 (see Custom shaders), and matches SpriteKit as closely; elsewhere,
as with the software renderer, lit sprites draw unlit. On macOS the tutorial scenes compare with SpriteKit on the GPU renderer as
they did on SDL's Metal renderer, within 0.13 of each scene's mean difference. The lighting and shadow shaders' sources are in Shaders/, in GLSL for SPIR-V, in Metal
and in GLSL for OpenGL; Scripts/compile-shaders.sh compiles and embeds them (it needs
glslangValidator, brew install glslang).
A sprite's shader replaces its default shading with a fragment shader in SpriteKit's dialect
of GLSL, like SKShader:
let ripple = Shader(source: """
void main() {
vec2 uv = v_tex_coord + vec2(sin(v_tex_coord.y * 30.0 + u_time * 4.0) * u_amount, 0.0);
gl_FragColor = texture2D(u_texture, uv) * v_color_mix * a_strength;
}
""", uniforms: [ShaderUniform(name: "u_amount", value: .float(0.01))],
attributes: [ShaderProgram.Declaration(name: "a_strength", type: .float)])
water.shader = ripple
water.setValue(.float(0.8), forAttribute: "a_strength")
ripple.uniform(named: "u_amount")?.value = .float(0.02)The source reads SpriteKit's inputs, measured from SpriteKit: u_texture, the sprite's texture
with premultiplied color; v_tex_coord, its texture coordinate (within an atlas, the atlas's)
with y running up; v_color_mix, the sprite's color mixed by its color blend factor, times its
alpha, premultiplied; u_time, the scene's elapsedTime in seconds; and SKDefaultShading(),
the color SpriteKit would draw. Uniforms (floats, vectors, matrices and textures) and
per-sprite attributes are used by name without declaring them. gl_FragColor is premultiplied
and blends with the sprite's blend mode as SpriteKit blends shader output. As in SpriteKit, a
shader that doesn't compile, including one with a precision statement, draws the sprite with
its default shading, and the compile error is printed. Sprites with the same shader and values
batch together.
Custom shaders run on SDL's OpenGL renderer, which sprites draw through around SDL's own
drawing: SDL draws what it has queued and forgets its OpenGL state, the batch draws with its
program, and SDL sets its state again. Windows choose it with
SDLWindow(..., preferredRenderDriver: "opengl"); sprite-viewer does when an archive has
shaders. Other renderers draw shaded sprites with their default shading. A fixture with
textured and untextured sprites, float and matrix uniforms, a texture uniform, attributes,
additive blending and a shader that fails to compile matches SpriteKit to a mean channel
difference of 0.08 on macOS and on Linux. SKRenderer, which the comparison renders with,
always gives u_time as zero; in an SKView it counts seconds from when the scene is
presented.
Emitters, effect nodes and scenes take a shader too, with setValue(_:forAttribute:).
Particles read it as sprites do. An effect node's shader draws its flattened image:
u_texture is the image, premultiplied, v_tex_coord runs from 0 to 1 across it with y up,
and v_color_mix is the node's alpha in every channel. A scene's shader, used when its
shouldEnableEffects is set as in SpriteKit, draws the whole rendered scene, background
included, with v_tex_coord across the screen. The OpenGL renderer copies the part of the
offscreen image the shader reads into a texture of its own. Fixtures with an effect node
shader and a scene shader match SpriteKit to 0.05 and 0.08 on macOS and Linux. SKRenderer
emits no particles unless an emitter is advanced in code, so emitter shaders were checked by
probing SpriteKit's inputs to them rather than by comparing fixtures. Shape node shaders aren't
supported, and scene archives don't keep them.
An effect node's filter stands in for the Core Image filter of the same name on an
SKEffectNode:
let glow = EffectNode()
glow.filter = .gaussianBlur(radius: 12)
glow.addChild(lamp)The filters are:
gaussianBlurcolorControlscolorInvertexposureAdjustgammaAdjustcolorMatrix
Each was measured from SpriteKit. SpriteKit runs Core Image on the image's sRGB values without color management:
- A blur's standard deviation is half its radius, in pixels, and the image grows by three deviations each way.
- Color filters work on unpremultiplied color and clamp the result.
- Color controls apply saturation, then contrast, then brightness.
A fixture with an effect node for each filter matches SpriteKit to a mean channel difference of 0.09 on SDL's GPU and OpenGL renderers. SDL's software renderer draws images unfiltered, and an effect node with both a filter and a shader draws with its shader. Other Core Image filters aren't supported; sepia, hue adjust, monochrome, box blur and pixellate didn't follow a law that could be measured. Scene archives keep supported filters with their inputs.
A WarpGeometryGrid distorts a sprite or an effect node's image, like SKWarpGeometryGrid:
each grid point takes the image at its source position to its destination position.
Positions are fractions of the image with y running up, listed row by row from the bottom.
var points = WarpGeometryGrid(columns: 2, rows: 2).destinationPositions
points[4] = [0.7, 0.6] // pull the middle up and to the right
flag.warpGeometry = WarpGeometryGrid(columns: 2, rows: 2).replacingDestinationPositions(points)
flag.run(.warp(to: WarpGeometryGrid(columns: 2, rows: 2), duration: .seconds(1)))As measured from SpriteKit:
- Each grid cell is cut into
2^subdivisionLevelspieces each way (2 levels by default, and at most 8 pieces), with corners interpolated bilinearly between the cell's corners. - Each piece is split into triangles from its lower left corner to its upper right.
- A sprite's grid spans its frame. An effect node's grid spans the image of its children, wherever the node itself is.
warp(to:duration:)moves each point in a straight line, and a node with no grid takes the target at once.animate(withWarps:times:restore:)passes smoothly through each grid at its time, and withrestoreputs the original grid back at the end.
A fixture of warped sprites, one of them in the middle of a warp action, matches SpriteKit to
a mean channel difference of 0.05. A warp takes the place of a sprite's centerRect slicing.
An EffectNode draws its children into an offscreen image, then draws that image with its
own opacity and blend mode, like SKEffectNode without a filter:
let ghost = EffectNode()
ghost.alpha = 0.5 // fades the group as one picture
ghost.blendMode = .add // and adds it to what is behind
ghost.addChild(body)
ghost.addChild(eyes)Overlapping children fade together instead of showing through each other, and the children's
own blending happens against the transparent image, as in SpriteKit. Frames list these images
as SpriteFrame.layers, innermost first; the SDL backend renders each into a render target the
size of the window and copies the children's pixels onto the frame with premultiplied blending.
shouldEnableEffects = false draws the node like a plain node, and shouldRasterize has no effect: the image is redrawn every frame. On
SDL's software renderer, children with additive blending inside an effect node add color
without opacity, and a screen-blended effect node is approximated by addition. A fixture with
each case matches SpriteKit to a mean channel difference of 0.02.
Constraints limit a node's position and rotation each frame, after actions and physics, as
SpriteKit's SKConstraints do:
turret.constraints = [.orient(to: player, offset: ConstraintRange(constantValue: -.pi / 2))]
drone.constraints = [.distance(ConstraintRange(lowerLimit: 50, upperLimit: 120), to: player)]
cameraNode.constraints = [.positionX(ConstraintRange(lowerLimit: 480, upperLimit: 1568))]Each node applies its constraints in order, parents before children, then the scene's
didApplyConstraints() runs. They work in the node's parent's coordinates; position and
rotation limits can use a referenceNode's instead. Orientation faces +x toward the target,
reporting angles from 0 to 2π, and its offset range limits the node's rotation relative to
that; rotation ranges don't wrap. A constrained physics body keeps its velocity. The tests
check these rules against SpriteKit. SpriteKit's rotation limit with a rotated reference node
sets the rotation to the reference's plus the lower limit even when it is already within
range; the engine leaves it unchanged.
import SpriteFormats
// Decoding runs off the main actor; uploading uses the backend.
let atlases = try await SpriteKitAtlas.decode(at: url.appending(path: "Characters.atlasc"))
.makeTextureAtlases(backend: backend)
let hero = Sprite(texture: atlases[texture: "hero"]!)
let (sheet, decoded) = try await AsepriteSheet.decode(at: url.appending(path: "hero.json"))
let atlas = try decoded.makeTextureAtlases(backend: backend)[0]
hero.run(.repeatForever(sheet.animation(tag: "walk", atlas: atlas)!))
// Image sets in an Xcode asset catalog, by the names SpriteKit archives use.
let catalog = try AssetCatalog(contentsOf: url.appending(path: "Assets.xcassets"))
if let pixels = try catalog.pixels(named: "background") {
scene.addChild(Sprite(texture: try backend.makeTexture(pixels, filtering: .linear)))
}AssetCatalog indexes .imageset folders inside groups and .spriteatlas folders.
Groups that set provides-namespace prefix their images (Characters/hero). Lookups
ignore a .png extension and @2x suffix. Each set uses its lowest-scale universal
file, then any other device type. The image is not resampled and textures carry no
point scale, so a set with only a 2x file loads at twice the size wherever the size
comes from the texture. Duplicate names outside namespaces are rejected. Image sets
without a file and other asset types (app icons, colors, data sets) are skipped. Only
PNG images decode.
PNGDecoder converts images tagged with another color space to sRGB, as SpriteKit does:
an embedded ICC profile (such as the Generic RGB Profile Xcode projects often carry), or
cHRM/gAMA values. Untagged and sRGB images keep their stored bytes. Pass
convertsToSRGB: false to PNGDecoder.decode for the stored samples.
var path = Path()
path.addRoundedRect(Rect(x: -40, y: -20, width: 80, height: 40), cornerRadius: 8)
let badge = ShapeNode(path: path)
badge.fillColor = Color(red: 0.2, green: 0.5, blue: 1)
badge.strokeColor = .white
badge.lineWidth = 2
let crop = CropNode()
crop.maskNode = ShapeNode(circleOfRadius: 30) // positioned in the crop node's space
crop.addChild(badge)
scene.addChild(crop)CropNode clips on the CPU, so masking works with every render backend. The mask
limits content to the geometry it draws; texture alpha is ignored, and overlapping mask
pieces draw content under the overlap twice. ShapeNode fills each subpath
independently (no holes).
Strokes take lineCap, lineJoin and miterLimit as Core Graphics does. The defaults are
SpriteKit's: bevelled joins, and a miter limit of one half, which bevels every miter.
As measured from SpriteKit:
- A
glowWidthreplaces the stroke with a glow in the stroke color. It is solid out to 0.8 points less than half the line width from the path, and fades linearly to nothing at half the line width plus the glow width plus 0.4 points. fillTexturestretches across the path's bounds, tinted by the fill color, and stops at its edges.
A fixture of fills, strokes, every cap and join, a glow and a textured fill matches SpriteKit to a mean channel difference of 0.62. The differences:
- Edges aren't antialiased.
strokeTexturestretches across the bounds too, where SpriteKit tiles it at a scale that wasn't measured.- Fill and stroke shaders aren't supported. Scene archives don't keep them, nor a shape's blend mode.
import SpriteFormats
let map = try await TiledMap.decode(at: mapURL)
let root = try map.makeNode(backend: backend)
scene.addChild(root)
// TileMap coordinates are Y-up, with row zero at the bottom.
if let ground = root.children.first as? TileMap {
ground[0, 0] = nil
let center = ground.centerOfTile(column: 1, row: 1)
}The initial Tiled loader supports finite orthogonal maps with right-down render order, uncompressed CSV layers, inline or external TSX tilesets, PNG sheets, margin/spacing, all eight flip combinations, and layer names, visibility, opacity, and pixel offsets. Tileset tile dimensions must match the map grid. Infinite maps, other orientations, compressed/base64 data, groups, object/image layers, per-tile metadata/animation, tile offsets, transparency keys, and layer tint/parallax are not supported and produce errors. Editor metadata and custom properties are ignored.
Each map caches local quads in 16×16 chunks; editing a cell invalidates its chunk. The existing batcher still constructs frame vertices each frame; viewport culling and persistent GPU chunk buffers are future work. Textures remain owned by the backend.
Preview the included fixture from the repository root:
swift run sprite-viewer --tmx Tests/SpriteFormatsTests/Fixtures/Tiled/sample.tmxlet archive = try await SpriteKitSceneArchive.decode(at: sceneURL)
let root = try archive.makeNode(
textureResolver: { reference in textures[reference.imageName] },
fontResolver: { name in fonts[name] }
)Foundation's PropertyListSerialization reads binary and XML keyed archives.
The loader maps SKScene, SKNode, SKSpriteNode, SKCameraNode, SKLabelNode, SKEmitterNode, and SKTileMapNode
to engine nodes, preserving child order, transforms, opacity, visibility, scene settings,
camera identity, sprite geometry/tint, and label layout. A root Scene can be presented
directly; other root nodes can be attached to an existing scene.
Applications supply named texture and bitmap/SDF font resolvers; missing resources throw
explicit errors. Texture references include image, atlas, subtexture, and filtering information.
Resolvers return the named image or atlas entry before the archive's unit-rectangle crop.
Returned textures remain owned by the application's backend. To draw what SpriteKit draws
for an image it can't find, upload SpriteKitSceneArchive.missingImage (a red cross on
white, 128 pixels square) and return that texture.
Named SKReferenceNode instances use an explicit archive resolver:
let root = try archive.makeNode(
textureResolver: { textures[$0.imageName] },
referenceResolver: { archivesByReferenceName[$0] }
)referenceNames lists direct references. Names are passed through unchanged (some
include .sks); the loader never opens referenced files automatically. Each instance
gets independent nodes and actions. Referenced scene roots become plain nodes under
the reference wrapper; their scene-only background, camera selection, and physics-world
settings do not replace the containing scene's settings. Resource caches are shared
across the expanded tree. Missing references, cycles, more than 31 nested reference
levels, and expansions beyond 100,000 nodes throw errors. A reference resolver can return
SpriteKitSceneArchive.missingReference to leave a node empty instead, as SpriteKit does
when the referenced scene isn't found. URL-based references and
physics bodies under scaled reference hierarchies remain unsupported.
This is an initial archive subset tested against fixtures generated with macOS SpriteKit, not a guarantee of compatibility with every Xcode editor or OS archive version. Custom node classes require an explicit mapping when decoding, for example:
let archive = try SpriteKitSceneArchive.decode(data,
customNodeClasses: ["GameScene": .scene, "GameSprite": .sprite])Mappings restore the selected standard node layout and report each substitution in
diagnostics. They do not execute custom code or restore custom fields. The caller
must choose the correct layout, since editor archives can omit superclass metadata.
Built-in classes cannot be remapped. Pass mappings separately when decoding referenced
archives in a reference resolver. An unmapped class loads as the SpriteKit class the Scene
Editor recorded in the node's _originalClass field, also reported in diagnostics;
without one it remains unsupported.
Reach constraints (joint angle limits for inverse kinematics) are skipped, since the engine
has no reach actions; limits other than SpriteKit's unrestricted defaults are reported in
diagnostics. Position, distance, orientation and rotation constraints are restored, including
their reference nodes and targets in the archive. Effect nodes are restored with their blend
mode, whether effects are enabled, and their shader; a scene with effects enabled draws through
its shader, if it has one, and otherwise as usual.
Light nodes, with their shadow colors, and sprites' lighting and shadow masks and normal maps
are restored, and so are sprites' warp grids and subdivision levels and warp actions; SpriteKit
doesn't archive an effect node's warp. Sprite shaders are restored with their
uniforms, attributes and each sprite's attribute values, sharing one Shader where the archive
does, and so are emitter, effect node and scene shaders; a shader archived by file name is read through makeNode's shaderResolver, and
sprite-viewer finds .fsh files in the scene's resource folders. As SpriteKit decodes vec4
uniforms as zero, so does the loader, noting each in diagnostics.
Labels with attributed text load as runs with each one's font and size, color, kerning, and
paragraph alignment and line spacing; text without a font is Helvetica at 12 points, and
without a color is black, as in SpriteKit. As measured, the runs keep their colors whatever the
label's font color, multiplied by its color as far as its colorBlendFactor. Other attributes,
such as underlines, shadows and other paragraph settings, aren't drawn and are noted in
diagnostics; so are system colors, which draw with the components the archive keeps for them.
labelFonts lists every run's font at the largest size it is used at.
A texture made from an image or from pixel data keeps its pixels in the archive, as an
uncompressed TIFF; TIFFDecoder reads it, and the texture reference carries the image for the
resolver to upload. SpriteKit keeps neither pixels nor a name for part of such a texture, so
that fails to load. A texture from an atlas names its atlas and entry, with SpriteKit's own
trimming and rotation of the entry in its page; the resolver supplies the entry whole and
upright, and those are ignored. A part of an atlas texture, which SpriteKit measures across its
whole page, loads as the whole entry. atlasNames lists the atlases an archive's textures name.
A node's userData holds UserDataValues, and archives restore what the Scene Editor saves:
booleans, numbers, strings and colors, as well as data, arrays and dictionaries an app keeps
there. Colors keep the components of their own color space. Integers and floating-point
numbers are both numbers, as NSNumber holds them; intValue reads a whole one. Other values,
such as dates and NSNull, and entries whose key isn't a string, are left out and noted in
diagnostics.
Circle, rectangle, convex counterclockwise polygon, and compound physics bodies are restored with local centers, mass, friction, restitution, damping, velocity, dynamic/gravity/rotation flags, and all 32 bits of collision/contact masks. Scene gravity and simulation speed are imported. SpriteKit density is converted from kilograms per square meter to the engine's per-square-point density using SpriteKit's 150 points per meter; gravity is converted to points per second squared using the same scale. Linear velocity remains in points per second. Imported scenes use the existing Box2D solver and fixed timestep; this does not promise identical SpriteKit simulation results.
Compound bodies support archived circles and convex polygon components, including their local offsets; polygon components are converted from meters to points. Loading is limited to 256 components and 4,096 polygon vertices per compound body.
Edge segments, chains, and loops load as static, two-sided collision boundaries, even when the archive's dynamic flag is set. Edge paths support up to 1,025 straight-line points and may be concave; zero-length segments are rejected. Loops connect the final point to the first, while chains preserve their archived endpoints.
The archived precise-collision flag maps to PhysicsBody.usesContinuousCollisionDetection.
This enables Box2D bullet sweeps against non-bullet dynamic bodies and can be changed
while a body is in a world. Static collisions already use continuous detection; sensors
and bullet-to-bullet pairs are excluded. This reduces tunneling without guaranteeing
SpriteKit's collision timing or preventing every missed collision.
Pinned bodies restore PhysicsBody.isPinned, which holds the node origin at a pivot
while allowing rotation, including shapes with offset centers of mass. Moving the node
or explicitly transforming its parent moves the pivot. Unpinning releases it, and
removing the body cleans up its internal anchor. Pinning does not physically couple
the body to a dynamic parent; use an explicit PinJoint for that behavior.
Texture bodies load as the convex polygons SpriteKit traced, which archives store instead of the image. SpriteKit archives what it made of a body's path:
- It flattens curves into points, which can repeat. Repeated points make no edge.
- It splits a concave polygon into convex pieces.
Joints load as PinJoints (with angle limits), FixedJoints, SpringJoints, SlidingJoints
and rope DistanceJoints. Their anchors are in scene coordinates, connecting bodies where the
archive placed them.
As measured from SpriteKit, a body is scaled by its node's ancestors but not by the node's own scale. That is how SpriteKit's decoding leaves it: the node has its scale before its body is attached, and only then joins its parent. A reference node's scale scales the scene it references the same way. Points, centers and sizes scale along each axis, and a circle's radius scales by the root mean square of the two scales. Rotations between scaled ancestors are not taken into account.
A fixture with a joint of each kind, scaled bodies, a ball in a bowl flattened from a curve and a concave block settles within 3 points of SpriteKit after ten seconds. SpriteKit keeps a skin of a point or two around bodies, and a welded pair lands 10 points away after bouncing differently. Internal collision skin radii are not imported, and the engine uses its own collision geometry. Bodies keep their charge and field mask, and field nodes are restored with their kind, settings and region. SpriteKit archives a region as at most two shapes and one operation, so the reader rejects anything else. A velocity field made from a texture is archived without its texture. Physics fixtures cover binary/XML decoding and simulation without requiring SpriteKit at test time.
Archived actions support relative/absolute movement (including single-axis movement),
color-and-blend or blend-only colorization,
Z rotation, two-axis scaling, single-axis absolute scaling, scaling sprites to a display size, absolute/relative sprite resizing (including independent width/height targets), fading, node-speed changes, waits, hide/unhide, removal, sequences, groups,
finite repeats, repeat-forever, relative and root-relative child-path action dispatch with current/parent traversal, SKAnimate texture flipbooks and instantaneous texture replacement, and SKPlaySound callbacks. The ordered action list and keys are restored without
duplicating keyed actions. Each makeNode() creates independent playback state, and
standard timing modes use the engine's easing curves. Size-based scaling resolves the
sprite's base size when playback starts; zero-sized dimensions retain their scale,
and nonsprite nodes are unaffected.
Node.childNode(withName:), Node.nodes(matching:), and child-action dispatch share
the same path resolver. nodes(matching:) returns all matches once each, in lookup
order, as a snapshot that can be iterated while modifying the tree.
enumerateNodes(matching:_:) visits that snapshot through a callback with an inout
stop flag. Removed matches are still visited; newly added nodes are excluded.
Action.run(_:onNodesMatching:) schedules independent playback on every match at
dispatch time. Each recipient retains its own pause/speed and cancellation state;
the dispatch finishes immediately. Add withKey: to replace an existing action on
each recipient under that key; other keys continue, and normal cancellation cleanup
runs for replaced actions. Action.removeAction(forKey:onNodesMatching:) cancels
that key on all matches at playback time, including paused recipients, with normal
cleanup. Action.removeAllActions(onNodesMatching:) cancels both keyed and unkeyed
actions on the matching snapshot. Missing keys or nodes are no-ops. Archived child
actions still target the first match.
Action.removeFromParent(onNodesMatching:) detaches a playback-time snapshot of
matches, including matching descendants of removed ancestors. Actions remain on
detached nodes and resume when those nodes return to an advancing tree.
Lookup returns the first match, or nil for an invalid or missing path. // starts at
the tree root (use .// for the current subtree). Child dispatch resolves at playback time.
container/target starts at the caller; /container/target starts at its current tree root. It
starts independent playback, and completes immediately. Missing children are a no-op.
. targets the current node and .. moves to its parent, so ../target
selects a sibling. Traversing above the root has no match.
//target searches from the root and .//target searches the caller's descendants,
in depth-first order. container//target searches beneath matching containers; recursive separators can
be chained with child paths. * matches zero or more characters in a name; a lone
* also matches unnamed nodes. Brackets match one character using sets ([abc],
[a,b]) or ascending ranges ([0-9]). Negated/escaped sets, keyed dispatch, and waiting for keyed actions are unsupported.
Set SPRITE_TRACE_ACTIONS in the environment to write every action a node is given to
standard error, e.g. sprite: hero runs sequence [move 2.0s, wait 0.5s, block] as patrol.
Action is CustomStringConvertible, so the same summary is available from print(action).
Actions start from their archived descriptions. Reversed relative movement, Z rotation, resizing, two-axis scaling, and relative speed changes use the reversed deltas or reciprocal factors stored by SpriteKit. The fixture SDK resets reversed speed-action duration to zero; playback honors the stored duration, including explicitly assigned durations. Reversed sequences and groups retain their archived child order. Other reversed actions, detectable partially executed state, retimed composites/flipbooks, single-axis relative scaling, paths, archived executable callbacks, and custom classes are unsupported. Native fixtures do not encode node or action speed; omitted runtime state cannot be recovered. Node speed and pause settings still apply. Speed actions animate an absolute speed or multiply the starting speed; they advance using the node's current inherited speed each frame. Speed changes affect subsequent frame time steps, and reaching zero stops timed actions. This is not a snapshot/resume mechanism for running games.
Texture flipbooks resolve every frame through the scene texture resolver and shared
cache, including atlas subrects. They support uniform frame timing, optional resizing,
and restoration on completion or cancellation, including keyed replacement and nested
actions. Only animations that have started and are still active restore their texture.
Instantaneous texture replacements honor the archived resize flag. The fixture SDK
archives setTexture with resizing enabled even when requested otherwise; the
original caller intention cannot be recovered from those archives.
Editor archives may save scenes and sprites paused. SKView unpauses a paused scene when it
presents it, and in SpriteKit unpausing a node also unpauses each paused child in turn,
stopping at children that were running. Node.resume() does the same; call it on a scene that
loaded paused to start playback as SpriteKit would.
Sound actions require an explicit host playback resolver:
let root = try archive.makeNode(
textureResolver: { textures[$0.imageName] },
soundResolver: { playbackCallbacks[$0] } // [String: Action.Block]
)The resolver prepares a main-actor playback callback; it does not start audio. The
callback receives the running node when the action begins and is called once per
repeat. Missing callbacks throw missingSound. Resolution is cached by filename
across the expanded scene. Named action libraries accept the same soundResolver.
Waiting actions use their archived duration; nonwaiting actions complete immediately.
This is action-clock timing, not an audio-device completion signal. Node/action speed
can change that timing without changing audio playback speed. The host owns audio
loading, output, and already-started playback; cancelling an action does not stop audio.
Nonzero archived sound positions are currently unsupported.
SpriteAudio plays sound files through SDL_mixer on the default audio device. Sounds are
decoded when loaded, and each play mixes a new instance, so a sound can overlap itself as
in SpriteKit. It can back a scene archive's sound resolver:
import SpriteAudio
let player = try AudioPlayer()
let root = try archive.makeNode(
textureResolver: { textures[$0.imageName] },
soundResolver: { name in
let sound = try player.sound(contentsOfFile: soundsFolder.appendingPathComponent(name).path)
return { _ in try? player.play(sound) }
}
)AudioPlayer() throws when no audio device is available. Set SDL_AUDIO_DRIVER=dummy to
play into a device that discards samples, as the tests do. Formats SDL_mixer doesn't decode,
such as CAF and AAC, fail to load.
An AudioNode plays a sound from a place in the scene, like SKAudioNode: by default it
loops as soon as it is in the scene, which suits background music.
let music = AudioNode(fileNamed: "theme.mp3")
scene.addChild(music)
let alarm = AudioNode(fileNamed: "alarm.wav")
alarm.autoplayLooped = false
scene.addChild(alarm)
alarm.run(.sequence([.play(), .wait(for: .seconds(2)), .changeVolume(to: 0, duration: .seconds(1)), .stop()]))
scene.audioOutput = SceneAudioPlayer(player: try AudioPlayer()) { name in soundsFolder.appendingPathComponent(name).path }At the end of each frame the scene describes its audio nodes to its audioOutput, and
SceneAudioPlayer plays each on its own SDL_mixer track. A node that leaves the scene stops;
play(), pause() and stop() (or the actions of the same names) control it, and volume,
stereo pan and playback rate can be set or animated with changeVolume, stereoPan and
changePlaybackRate actions. With a scene listener, positional nodes pan fully to one side
half the scene's width from it, and beyond their referenceDistance (200 points) their volume
falls off as the reference distance over the distance. SpriteKit's own falloff could not be
measured, so positional levels are not calibrated to it. Archived SKAudioNodes keep their
sound name and autoplayLooped; archives don't store whether a node is positional or the
scene's listener.
Standalone editor Actions.sks libraries can be loaded independently of a scene:
let library = try await SpriteKitActionArchive.decode(at: actionsURL)
if let pulse = try library.makeAction(named: "Pulse") {
node.run(pulse, withKey: "pulse")
}actionNames returns sorted names. makeAction(named:textureResolver:) returns nil
for an unknown name and resolves flipbook textures when needed, caching repeated
references within that call. Running the same action on different nodes creates
independent playback state. Libraries use the same supported action types and limits
as scene archives; unsupported entries reject the library during decoding.
Particle emitters restore birth rate/count, lifetime, spawn position/range, speed and emission angle, acceleration, rotation, scale, opacity, color/blend factor, size, blend mode, and particle Z position. Named particle textures use the same cached resolver as sprites. Targets must reference a node in the imported tree. Alpha/scale keyframes support linear interpolation with clamping. Standalone emitter archives are supported.
Linear, clamped color keyframes support archived NSColor RGB and grayscale values,
including alpha. The importer uses the stored RGB/white fallback directly; custom ICC
profiles are not color-managed. Other color classes and color spaces are unsupported.
A zero archived particle size uses the resolved texture dimensions, including atlas subrects. Explicit sizes are preserved; zero size without a texture stays invisible.
Starting color-blend variance is supported: each particle samples the base factor
plus a random offset within half the range, then clamps it to 0...1. The sampled
factor stays fixed for its lifetime; changes to the emitter affect future particles.
Per-channel color ranges/speeds, color-blend speeds/sequences, particle actions, speed/rotation keyframes, fields, emission distance, and Z ranges/speeds are currently unsupported. Imported emitters start with no live particles and retain the engine's 10,000-live-particle cap; simulation is not intended to reproduce SpriteKit's random particle stream exactly.
Grid tile maps restore dimensions, cell size, anchor, tint, transforms, and saved cell placement. Empty cells, shared tile definitions, and definitions selected from multiple rules are preserved. Embedded tile sets are decoded directly. For editor scenes that reference a set by name, decode the companion archive and provide a resolver:
let sets = try await SpriteKitTileSetArchive.decode(at: tileSetsURL)
let root = try archive.makeNode(
textureResolver: { reference in textures[reference.imageName] },
tileSetResolver: { name in sets.first { $0.name == name } }
)Tile definitions support static textures and looping texture arrays with a uniform
frame duration. Each map starts animations at frame zero; cells sharing a definition
stay synchronized, including newly placed cells. Playback follows scene and ancestor
pause/speed settings, and maps sharing a tile set maintain independent clocks. Native
maps can use TileSet(textures:animations:) with TileAnimation values as well.
Animated frames preserve texture subrects without rebuilding cached tile geometry.
Maps keep their tile set's layout: grid, isometric, or flat or pointy hexagons
(TileMap.Layout), with SpriteKit's cell centers, map size and drawing order, as measured.
Isometric cells are diamonds half a tile apart, and their tiles draw column by column from the
left, each column from the top, so blocks nearer the bottom cover those behind. Hexagons are
spaced by the tile's width (flat) or height (pointy) alone; SpriteKit makes a map with an odd
number of hexagonal columns (flat) or rows (pointy) a hexagon and a half narrower or shorter
than its cells, and so does size, which places the cells about the anchor point. Grids draw
their rows from the top, each from the right, and hexagonal maps their rows from the top, each
from the left. A definition of another size than its cells keeps its own size, with its
bottom-left corner at the cell's, and its rotation and flips turn its texture within that
size, as Tile(id:quarterTurns:flipHorizontally:flipVertically:) does. tileCoordinates(at:)
finds the hexagon whose center is nearest, which SpriteKit disagrees with only within a few
hundredths of a hexagon of an edge; outside the map it returns nil, where SpriteKit gives
the nearest edge cell of a grid or isometric map. Tile definitions must not have normal maps.
The importer
uses the archived definition selection; it does not implement SpriteKit automatic
adjacency updates, weighted selection, or editor stamps. Tile-set metadata and custom
properties are not imported. Without --tilesets, the viewer loads tile sets from
.sks archives in the scene's folder and up to three parent folders, nearest first.
Pass a companion archive explicitly to skip that search:
swift run sprite-viewer --sks Tests/SpriteFormatsTests/Fixtures/SceneArchives/tiles-external.sks --tilesets Tests/SpriteFormatsTests/Fixtures/SceneArchives/tilesets.sksOther editor metadata is ignored. Binary UIDs are normalized through Foundation's XML serialization without using private UID APIs or instantiating archived classes.
swift run sprite-viewer --sks Tests/SpriteFormatsTests/Fixtures/SceneArchives/scene.sksThe viewer loads loose PNGs relative to the archive. Label fonts are font files in the
scene's folder, its three parent folders or a Fonts folder in any of them, then the
system's fonts, each rasterized at the largest size it is used at. A font that isn't found
is replaced by the built-in bitmap font, with a message.
Images that aren't loose files come from .xcassets catalogs in the scene's folder or up
to three parent folders, nearest first, matching the layout of an Xcode project.
Atlas directories can also be given explicitly, as source or compiled folders:
swift run sprite-viewer --sks scene.sks --atlas Characters.atlas --atlas Backgrounds.atlascEach atlas is registered under its folder name without the extension. Duplicate names
are rejected. Uploads are cached per atlas and filtering mode and shared with referenced
scenes. Compiled atlas rotation and trim padding are restored by the atlas decoder.
An atlas the scene names that isn't given with --atlas is found as Name.atlasc or
Name.atlas in the folders searched for resources or their subfolders, as SpriteKit finds it
in its bundle. Images the archive holds are drawn from its own pixels. Like SpriteKit, the viewer draws a placeholder for a missing atlas or texture entry and
names each one once.
For custom classes the archive doesn't map to a SpriteKit class, repeat
--class CustomName=SKNodeClass as needed:
swift run sprite-viewer --sks Tests/SpriteFormatsTests/Fixtures/SceneArchives/custom-classes.sks --class FixtureGameScene=SKScene --class FixtureGameSprite=SKSpriteNodeSupported targets are SKScene, SKNode, SKSpriteNode, SKCameraNode,
SKLabelNode, SKEmitterNode, SKTileMapNode, SKReferenceNode, SKAudioNode, SKVideoNode, SKShapeNode, and
each SKFieldNode class.
Mappings require --sks; duplicate names, built-in name overrides, and unknown targets
are rejected before opening a window. The viewer prints substitution diagnostics;
custom gameplay behavior is not restored.
The viewer resolves named reference scenes from the root archive's directory, appending
.sks when the name has no extension. Nested reference names and loose textures use that
same directory as their resource root, rather than the referenced file's directory.
Custom-class mappings also apply to referenced archives, whose diagnostics include the
reference name. A missing referenced scene leaves its reference node empty, with a
message, as in SpriteKit. Cycles and excessive expansion fail explicitly.
The fixture generator is Tests/SpriteFormatsTests/Fixtures/make_scene_fixtures.swift
(macOS only); tests consume the checked-in archives and require no SpriteKit runtime.
A VideoNode shows a video, like SKVideoNode. SpriteVideo decodes the video with FFmpeg
into a texture of the render backend, and plays its sound through an AudioPlayer:
import SpriteVideo
let intro = VideoNode(fileNamed: "intro.mp4")
scene.addChild(intro)
intro.play()
scene.videoOutput = SceneVideoPlayer(backend: backend, audio: try AudioPlayer()) { name in
videosFolder.appendingPathComponent(name).path
}At the end of each frame the scene gives each video node the frame for its currentTime. As
measured from SpriteKit, a node shows its video's first frame before it plays, and takes the
video's size (after its pixel aspect ratio) unless it was given a size. It holds the last frame
once the video ends, and play() then starts it again. Setting currentTime seeks. Untagged
video converts to RGB as BT.601 video range, which gives SpriteKit's colors exactly. Tagged
video converts by its tags.
Each video's sound plays on its own SDL_mixer track while the node plays, at the node's
inherited speed. It pauses when the node or an ancestor pauses. The track is topped up each
frame with a quarter second of sound. When the sound drifts more than 0.15 seconds from the
node's time, as after a seek, it starts again at the node's time. Without an AudioPlayer,
videos are silent.
The differences from SpriteKit:
- Playback time advances with the scene's updates, following the node's inherited pause and
speed, rather than with the wall clock.
SKRendererdoesn't show a playing video's frames, so SpriteKit's playback timing could not be measured. - Rotation metadata is ignored.
Archived SKVideoNodes keep their file name and size. SpriteKit doesn't archive a video
node's anchor point and reads it back as zero, and so does the reader. Nodes made from a
video URL are unsupported.
Pass --frames N to render a bounded number of frames and exit. This mode advances
simulation by a fixed 1/60 second per frame; normal interactive playback uses elapsed
time. A completed run prints Rendered N frames..
Add --screenshot out.png (with --frames) to save the last frame as a PNG. The window
stays hidden and renders at one pixel per point, so a screenshot is 960x640 on any display.
Applications can capture frames the same way: set SDLRenderBackend.capturesFrames, read
capturedFrame after rendering, and write it with PixelBuffer.pngData(); captured frames
are opaque, as the window shows them. PNGEncoder
writes uncompressed RGBA PNGs, which are larger than compressed files but readable anywhere.
After building the viewer, run:
python3 Scripts/smoke-viewer.py "$(swift build --show-bin-path)/sprite-viewer"Like SKView, the viewer resumes a scene that loaded paused, along with its paused nodes.
The viewer plays archived sound actions. Like a resource bundle's, sound files are found in
the scene's folder, up to three parent folders and the folders directly inside them (such as
a Sounds folder), adding an extension SDL_mixer decodes when the name has none. A sound
that isn't found or can't be decoded, or a missing audio device, is reported once and stays
silent. Audio nodes are found and played the same way, and video nodes are found by their
exact file name; --mute silences them too. Archived video nodes don't play on their own,
as in SpriteKit, so the viewer shows their first frame. Use --mute with --sks to skip
audio: it reports each muted sound and audio node once and preserves archived action waits
without loading audio files.
The script uses SDL's dummy video driver and software renderer, requires clean exits
and completed frames for successful loads, and treats timeouts as failures. With SDL's dummy
audio driver, its 70 checks cover custom classes, references, effect nodes, lit and shaded sprites
without shaders, sound actions and audio nodes
(played, missing and muted), video nodes (shown and missing), screenshots, screen blending, source/compiled atlases,
asset catalogs and tile sets in parent folders, label fonts in the project or missing, attributed labels, user data, tile layouts, physics and field fixtures, warped sprites, shape nodes, filters without shaders,
and invalid options or resources. Temporary derived archives stay outside the repository.
The Viewer smoke tests workflow builds the viewer, runs the full Swift test suite,
and runs these checks on pushes and pull requests.
Download and extract 2D Apple Games by Tutorials, edition 3.0 from Kodeco's deprecated books:
python3 Scripts/download-tutorial.pyThe script requires Python 3.8 or later. It caches the approximately 632 MiB ZIP in
.build/tutorials/ and extracts it into .build/tutorials/2d-apple-games-3/.
It verifies a pinned SHA-256 checksum and checks key tile-map and particle archives.
Use --archive PATH to select the ZIP cache or --destination PATH to change the
extraction directory. Repeated runs reuse verified downloads and extracted samples.
The downloaded material remains outside version control and retains
Kodeco's license.
The Tutorial assets GitHub Actions workflow runs the script on pushes, pull requests, and manual dispatches, including cache hits. This checks asset retrieval and archive integrity; it does not claim that every tutorial scene is supported by the engine.
Loaded with --mute --frames 3, all 297 tutorial scenes (excluding action and tile set
libraries) render with both the GPU and software renderers. 7 are loose scene files whose
images and referenced scenes exist only outside their project; they draw placeholders, as
SpriteKit does.
On macOS, render scene archives with both sprite-viewer and Apple's SpriteKit and rank how far apart they look:
swift build --product sprite-viewer
python3 Scripts/compare-spritekit.py "$(swift build --show-bin-path)/sprite-viewer"Pass scene files or folders to compare; the default is the tutorial samples. A step that
takes longer than --timeout seconds (120 by default), as actool occasionally does, fails
only its scene. The script
needs Xcode. It builds Scripts/spritekit-reference.swift, which renders each scene
offscreen with SKRenderer after the same number of 1/60 second frames. Images resolve the
way they would in the scene's app: the script compiles the asset catalogs the viewer would
search with actool into an app bundle, along with loose images beside the scene and .sks
archives in the searched folders. .build/spritekit-comparison/report.tsv lists each scene's
mean channel difference (0-255) and the share of pixels differing by more than 32, largest
first, followed by scenes that couldn't be compared. images/ holds each pair side by side
with a difference image.
The reference matches the viewer's assumptions so differences point at the engine:
- Nodes with a Scene Editor custom class decode as their SpriteKit class, as in the viewer,
instead of being dropped because the app's class isn't present. Nodes archived as an app
class are renamed to their
_originalClassfirst. - A resize-fill scene is rendered at one pixel per point. Without a view,
SKRendererwould use the display's backing scale. - SpriteKit's first update has no previous time and advances the scene by up to a second, so
the clock starts with the scene and physics stopped. It starts at 1000 seconds rather than 0:
SKRendererstops simulating physics after one step when its clock starts at 0, and its physics keeps a separate clock, started by a second update with the scene running. - A scene saved paused is resumed with its paused nodes, as
SKViewdoes when presenting it. - Archives whose root isn't a scene (emitters, sprites) are shown in a 960x640 scene.
Physics, particles, and text rasterization (FreeType's glyphs are slightly lighter than
Core Text's) make some differences expected.
Of the 297 tutorial scenes, 292 have a mean difference under 1 and 286 have under 1% of
pixels differing. CatNap's physics levels match within a mean difference of 0.45, and over
120 frames bodies stay within a few points of SpriteKit's. One exception: a block resting on a
tilted seesaw, at the edge of sliding, slides faster than in SpriteKit, whatever the number of
solver substeps. Animated tiles switch frames when SpriteKit does,
as measured: an animation shows its first frame for one update and its second from the next,
then changes once a whole timePerFrame has passed since the last change, so each frame lasts
a whole number of updates. SpriteKit sometimes holds a frame one update longer, as it measures
time in single precision, and draws frames an animation swaps in from a compiled atlas a pixel
off, so PestControl's bugs still differ while their later frames show; over 40 frames its mean
difference averages 2.81, down from 3.86. Two loose CatNap levels
stretch the missing-image placeholder across the whole scene, which magnifies small offsets.
Label scenes draw their fonts at the same positions as SpriteKit, within a pixel, and so do
attributed labels and labels of several lines. Font metrics are the face's own, unrounded, as
Core Text has them; the viewer gives Helvetica, Times, Courier and Palatino lines 1.2 times their
ascent and descent, as AppKit does for its legacy Mac fonts.
actool occasionally rejects the DropCharge asset catalog's app icon set; those 2 scenes
then can't be compared.
import SpriteCore
import SpriteSDL
let window = try SDLWindow(title: "Demo", width: 800, height: 600)
let backend = SDLRenderBackend(window: window)
let texture = try backend.makeTexture(PixelBuffer(width: 32, height: 32, fill: .white), filtering: .nearest)
var batcher = SpriteBatcher(sortMode: .textureGrouped)
batcher.submit(SpriteQuad(
texture: texture,
transform: Transform2D(position: [400, 300], rotation: .pi / 4).matrix,
color: .red
))
try backend.render(batcher.makeFrame(viewTransform: .viewport(size: backend.drawableSize)), clearColor: .black)swift run sprite-viewer
swift testBlendMode.screen is supported for sprites and particles, including archived
SpriteKit screen blend modes. The SDL backend uses a custom blend mode with
premultiplied textures and vertex colors to preserve source transparency. It retains
CPU texture pixels and lazily caches a premultiplied GPU copy when a texture is first
used for screen blending; texture updates invalidate that copy. Renderers without custom
blend modes, such as SDL's software renderer, draw each screen-blended triangle in four
passes with modes every renderer supports: a multiply pass per color channel darkens the
destination by one minus the source, then an additive pass adds the source. This matches
the GPU renderer to within a step per channel, at four draws per triangle; it uses three
more cached copies of each texture, one per channel.