flix

0.81.0

Surface

A lightweight, Processing-shaped drawing surface built on Swing and Java2D.

This is the only module in src/ that opens a window, and the vocabulary it offers is deliberately the one a Processing sketch already knows: background, fill, rect from its top-left corner, ellipse from its centre, text on its baseline. Keeping those names and those conventions is what let the Canvas handler above it stay a one-line-per-operation translation when Processing Core was dropped.

It comes in two halves, and the seam between them is the point. A Sheet is somewhere to draw -- a back buffer, the graphics that writes to it, and the current colour and font -- and knows nothing about a display, so offscreen hands one out on a machine with no screen at all and test/TestSurface.flix checks the rasteriser against real pixels. A Window is a sheet with a frame around it, a keyboard, and a frame loop.

It is a surface, not a framework: no sketch lifecycle, no setup/draw pair to subclass, and no global state -- everything it knows travels in the records it hands back. The frame loop lives one layer up, in Sketch, where it can be read as ordinary functions. The one policy it does impose is that Escape closes the window, which is what a sketch of this shape has always done.

Drawing goes to an offscreen BufferedImage of exactly the requested size, which present then blits to the window through a BufferStrategy. That fixes the geometry at one image pixel per sketch pixel on every display, HiDPI or not -- the job Processing's pixelDensity(1) used to do -- so a sketch that lines up on one machine lines up on all of them.

Type Aliases

type alias Sheet[rc: Eff] = { base = java.awt.Font, ellipse = java.awt.geom.Ellipse2D.Float, graphics = java.awt.Graphics2D, height = Int32, image = java.awt.image.BufferedImage, rectangle = java.awt.geom.Rectangle2D.Float, sized = Ref[(Float32, java.awt.Font), rc], width = Int32 }§ Source

A drawing surface, with no display behind it.

image is the buffer and graphics the one Graphics2D that writes to it, made once and kept: Java2D carries the current colour and font on the graphics object, which is exactly the "set it, then draw with it" model the Canvas effect is written in.

rectangle and ellipse are two mutable shapes reused for every call rather than allocated per shape. They are what makes drawing sub-pixel: the formation marches at 0.65 pixels a tick, so rounding a rectangle to whole pixels would turn a glide into a stutter.

sized remembers the font the last textSize derived, so a screen that sets the same size before every line of text derives the font once instead of twenty times. Its Float32 is the size of the Font beside it, and seeding it with anything else would make textSize skip a derivation it owed.

type alias Window[rc: Eff] = { canvas = java.awt.Canvas, closing = java.util.concurrent.atomic.AtomicBoolean, frame = javax.swing.JFrame, keys = Ref[Set[Int32], rc], sheet = Sheet[rc], strategy = java.awt.image.BufferStrategy }§ Source

An open window and everything showing a sheet in it needs.

keys is written by the AWT listeners and read by the frame -- both on the event dispatch thread, so it needs no locking. closing is set when the window is shut, and is the one value the parked thread reads while the event thread may still be writing it, which is why it is an AtomicBoolean and not a Ref.

Definitions

def afterPress(held: Set[Int32], code: Int32): Option[Set[Int32]]§ Source

The keys held after a press of code, or None if the window took that press.

The decision lives here rather than inside the listener because a listener is an anonymous JVM method with a window behind it, and nothing about which key does what needs either.

def afterRelease(held: Set[Int32], code: Int32): Set[Int32]§ Source

The keys held after a release of code.

def background(sheet: Sheet[r], c: Color): Unit \ IO§ Source

Fills the whole sheet with c, erasing what was there.

Leaves c as the fill colour, as Processing's background does.

def close(win: Window[r]): Unit \ IO§ Source

Closes the window and releases everything it was drawing through.

def closesWindow(code: Int32): Bool§ Source

Whether a key press closes the window rather than reaching the sketch.

Escape does, which is the convention every windowed sketch of this shape has had -- Processing built it into PApplet, and a window that could only be dismissed with the mouse would be a regression rather than a simplification. The consequence is worth stating plainly: Key.Escape never reaches a step, so nothing above the runtime may use it for anything else.

def ellipse(sheet: Sheet[r], x: Float32, y: Float32, w: Float32, h: Float32): Unit \ IO§ Source

Draws an ellipse centred on (x, y).

def fill(sheet: Sheet[r], c: Color): Unit \ IO§ Source

Sets the colour subsequent shapes and text are drawn in.

def fillAlpha(sheet: Sheet[r], c: Color, alpha: Int32): Unit \ IO§ Source

Sets a translucent fill, with alpha from 0 (invisible) to 255 (opaque).

def firstDelay(periodNs: Int64): Int32§ Source

How long the timer waits for the very first frame.

Never zero, however short a period is asked for: a Swing timer with no delay saturates the event thread before the first frame has drawn, and the window never becomes responsive enough to be closed. Every frame after this one is scheduled by reschedule, which may legitimately ask for no wait at all -- by then there is a window, and a frame that is already late should not be delayed further.

def keysHeld(win: Window[r]): Set[Int32] \ r§ Source

The AWT key codes currently held down.

Codes rather than named keys: this layer knows about a keyboard and not about a game, and Key.fromCode one layer up is where a number becomes a name.

def loop(win: Window[r], periodNs: Int64, frame: Unit -> Unit \ { IO, r }): Unit \ IO§ Source

Calls frame once every periodNs until the window closes.

Nanoseconds and not a rate: what a frame is worth is the frame loop's business, and Sketch is where the rate a Config asks for is brought into range. Asking twice, in two units, is how the two would come to disagree.

The callback runs on AWT's event dispatch thread, which is also the thread the key listeners run on and the only thread Swing may be touched from. One thread owns input, simulation and drawing, so none of them needs a lock.

This call blocks the thread it is made on, which is therefore not the event thread: it parks until the window reports that it has closed, and only then stops the timer. A frame that arrives after the close is dropped rather than run, so the last world the caller reads is the one the last drawn frame produced.

The region effect r does not appear in the result: the callback is compiled into a fixed JVM method on an anonymous ActionListener, so what it does to the caller's region is invisible from out here. That is the same boundary limit that keeps Sketch.start from being effect-polymorphic.

def millisOf(ns: Int64): Int32§ Source

A nanosecond span as the whole milliseconds a timer can be asked to wait.

Swing's timer counts in milliseconds, so 16.67 of them is asked for as 16 and the third that is dropped would drift the display fast. That is what reschedule exists to correct: the rounding happens once per frame and against a deadline, rather than accumulating.

def offscreen(rc: Region[r], width: { width = Int32 }, height: { height = Int32 }, fontPath: Option[String]): Sheet[r] \ { IO, r }§ Source

A sheet of exactly width by height pixels, with no window anywhere near it.

This is what open builds its back buffer with, and what the rasteriser's tests draw on: nothing here needs a display, a toolkit peer, or a graphics device, so it runs on a CI machine with no screen.

A fontPath that is missing or unreadable costs you looks, not a crash -- the sheet keeps the platform's default font and says so.

def open(rc: Region[r], title: String, width: { width = Int32 }, height: { height = Int32 }, fontPath: Option[String]): Window[r] \ { IO, r }§ Source

Opens a window showing a sheet of exactly width by height sketch pixels.

The window is not resizable, because the sheet is not: every coordinate a sketch draws at is an image pixel, and a window that could be dragged wider would have to answer what that means.

def pixelAt(sheet: Sheet[r], x: Int32, y: Int32): Color \ IO§ Source

The colour of one pixel, as it currently stands.

The read-back that makes the rasteriser testable: with offscreen there is no window to look at, so this is how a test asks what was actually drawn rather than what was asked for. The buffer has no alpha channel, so what comes back is already composited.

def present(win: Window[r]): Unit \ IO§ Source

Shows everything drawn on the sheet since the last call.

Blitting the finished buffer and flipping, rather than asking the toolkit to repaint: the frame is complete now, and a queued repaint would land somewhere inside the next one -- which shows up as tearing and makes the cost of drawing impossible to measure.

A buffer the display driver has reclaimed is not retried. Every frame redraws the whole sheet, so the next one restores it in sixteen milliseconds, and a retry here would cost that on every frame to save it on almost none.

The sync is for X11, where the toolkit is a client of a display server and may hold a finished frame in its request buffer until it has some other reason to flush -- which is how a game that is comfortably inside its budget still looks jerky. It is close to free where it is not needed: measured here at 0.03 to 0.06ms on top of a present of about 0.1ms, against a frame of 16.7.

def rect(sheet: Sheet[r], x: Float32, y: Float32, w: Float32, h: Float32): Unit \ IO§ Source

Draws a rectangle with its top-left corner at (x, y).

def release(sheet: Sheet[r]): Unit \ IO§ Source

Releases the graphics a sheet was drawing through.

def requestClose(win: Window[r]): Unit \ IO§ Source

Asks the loop to stop, as though the window had been closed.

This is how a bounded run ends: FLIX_SKETCH_MAX_FRAMES gives a sketch a frame budget so it terminates on a machine nobody is sitting in front of.

def reschedule(dueNs: Int64, nowNs: Int64, periodNs: Int64): (Int64, Int32)§ Source

Moves the deadline on by one frame and says how long to wait for it, in milliseconds.

Swing's timer measures its delay from the moment it fires, so whatever a frame costs is added to every period after it and the display settles a few frames a second below the rate asked for. Aiming at a deadline instead spends an overrun once rather than compounding it, which is what keeps the average rate on target.

A frame more than a whole period late abandons the ones it missed rather than firing them back to back: they are gone, and running them now would only put the next frame further behind. The simulation loses nothing by it -- the accumulator still owes the ticks that time was worth, and Sketch clamps how many of them one frame may run.

def sheet(win: Window[r]): Sheet[r]§ Source

The sheet this window is showing.

def size(sheet: Sheet[r]): (Int32, Int32)§ Source

The sheet's size, in sketch pixels.

Held rather than asked of the buffer, so the frame loop can read it without reaching into the toolkit: a sheet cannot be resized, so it never changes.

def text(sheet: Sheet[r], str: String, x: Float32, y: Float32): Unit \ IO§ Source

Draws str with its baseline starting at (x, y).

def textSize(sheet: Sheet[r], px: Float32): Unit \ { IO, r }§ Source

Sets the text size in pixels.

Deriving a font allocates, and a screen that sets the same size before each of its twenty labels would pay for it twenty times, so the last one derived is kept.