Kernel
======

At the very core of Chickadee, in the (chickadee game-loop) module, lies an event loop.  This loop, or ``kernel'', is responsible for ensuring that the game is updated at the desired interval, rendering the current state of the game world, and handling errors if they occur.  The kernel implements what is known as a ``fixed timestep'' game loop, meaning that the game simulation will be advanced by a fixed interval of time and will never vary from frame to frame, unlike some other styles of game loops.  The appropriately named run-game* and abort-game procedures are the entry and exit points to the Chickadee game loop kernel.

On its own, the kernel does not do very much at all.  In order to actually respond to input events, update game state, or render output, the programmer must provide an engine.  But don’t worry, you don’t have to start from scratch!  Chickadee comes with a simple engine that uses SDL to create a graphical window and handle input devices, and OpenGL to handle rendering.  This default engine is enough for most users to get started writing games quickly.  More advanced users may want to write a custom engine that uses a different I/O system. Perhaps you are writing a text adventure or roguelike that reads from and writes to a terminal instead of a graphical window.  The game loop kernel makes no assumptions.

 -- Procedure: run-game [#:update] [#:render] [#:time] [#:error]
     [#:update-hz 60]

     Start the game loop.  This procedure will not return until abort-game is called.

     The core game loop is generic and requires four additional procedures to operate:

       * UPDATE: Called UPDATE-HZ times per second to advance the game simulation.  This procedure is called with a single argument: The amount of time that has passed since the last update, in milliseconds.

       * RENDER: Called each iteration of the loop to render the game to the desired output device.  This procedure is called with a single argument: A value in the range [0, 1] which represents how much time has past since the last game state update relative to the upcoming game state update, as a percentage.  Because the game state is updated independent of rendering, it is often the case that rendering is occuring between two updates.  If the game is rendered as it was during the last update, a strange side-effect will occur that makes animation appear rough or ``choppy''.  To counter this, the ALPHA value can be used to perfrom a linear interpolation of a moving object between its current position and its previous position. This odd trick has the pleasing result of making the animation look smooth again, but requires keeping track of previous state.

       * TIME: Called to get the current time in milliseconds.  This procedure is called with no arguments.

       * ERROR: Called when an error from the UPDATE or RENDER procedures reaches the game loop.  This procedure is called with three arguments: The call stack, the error key, and the error arguments.  If no error handler is provided, the default behavior is to simply re-throw the error.

 -- Procedure: abort-game
     Stop the currently running Chickadee game loop.

Since most users will want to write 2D/3D games with hardware accelerated graphics rendering, controlled via keyboard, mouse, or game controller, Chickadee comes with an easy to use engine just for this purpose in the (chickadee) module: run-game.

 -- Procedure: run-game [#:window-title "Chickadee!"]
     [#:window-width 640] [#:window-height 480]
     [#:window-fullscreen? #f] [#:update-hz 60]
     [#:load] [#:update] [#:draw] [#:quit]
     [#:key-press] [#:key-release] [#:text-input]
     [#:mouse-press] [#:mouse-release] [#:mouse-move]
     [#:controller-add] [#:controller-remove] [#:controller-press]
     [#:controller-release] [#:controller-move] [#:error]

     Run the Chickadee game loop using the SDL engine in OpenGL mode.

     A new graphical window will be opened with WINDOW-WIDTH x WINDOW-HEIGHT as its dimensions, WINDOW-TITLE as its title, and in fullscreen mode if WINDOW-FULLSCREEN? is #t.

       * LOAD: Called with zero arguments when the game window has opened but before the game loop has started.  Can be used to perform initialization that requires an open window and OpenGL context such as loading textures.

       * UPDATE: Called UPDATE-HZ times per second with one argument: The amount of time to advance the game simulation.

       * DRAW: Called each time a frame should be rendered with a single argument known as the alpha value.  See the documentation for run-game for an explanation of this value.

       * QUIT: Called with zero arguments when the user tries to close the game window.  The default behavior is to exit the game.

       * KEY-PRESS: Called with four arguments when a key is pressed on the keyboard:

           1. KEY: The symbolic name of the ``virtual'' key that was pressed. For example: backspace.  It's called a virtual key because the operating system may map a physical keyboard key to another key entirely, such as how the author likes to bind the ``caps lock'' key to mean ``control''.

           2. SCANCODE: The symbolic name of the physical key that was pressed.

           3. MODIFIERS: A list of the symbolic names of modifier keys that were being held down when the key was pressed.  Possible values include ctrl, alt, and shift.

           4. REPEAT?: #t if this is a repeated press of the same key.

       * KEY-RELEASE: Called with three arguments when a key is released on the keyboard:

           1. KEY: The symbolic name of the ``virtual'' key that was released.

           2. SCANCODE: The symbolic name of the physical key that was released.

           3. MODIFIERS: A list of the symbolic names of modifier keys that were being held down when the key was released.

       * TEXT-INPUT: Called with a single argument, a string of text, when printable text is typed on the keyboard.

       * MOUSE-PRESS: Called with four arguments when a mouse button is pressed:

           1. BUTTON: The symbolic name of the button that was pressed, such as left, middle, or right.

           2. CLICKS: The number of times the button has been clicked in a row.

           3. X: The x coordinate of the mouse cursor.

           4. Y: The y coordinate of the mouse cursor.

       * MOUSE-RELEASE: Called with three arguments when a mouse button is released:

           1. BUTTON: The symbolic name of the button that was released.

           2. X: The x coordinate of the mouse cursor.

           3. Y: The y coordinate of the mouse cursor.

       * MOUSE-MOVE: Called with five arguments when the mouse is moved:

           1. X: The x coordinate of the mouse cursor.

           2. Y: The y coordinate of the mouse cursor.

           3. DX: The amount the mouse has moved along the x axis since the last mouse move event.

           4. DY: The amount the mouse has moved along the y axis since the last mouse move event.

           5. BUTTONS: A list of the buttons that were pressed down when the mouse was moved.

       * CONTROLLER-ADD: Called with a single argument, an SDL game controller object, when a game controller is connected.

       * CONTROLLER-REMOVE: Called with a single argument, an SDL game controller object, when a game controller is disconnected.

       * CONTROLLER-PRESS: Called with two arguments when a button on a game controller is pressed:

           1. CONTROLLER: The controller that triggered the event.

           2. BUTTON: The symbolic name of the button that was pressed. Possible buttons are:

                 * a

                 * b

                 * x

                 * y

                 * back

                 * guide

                 * start

                 * left-stick

                 * right-stick

                 * left-shoulder

                 * right-shoulder

                 * dpad-up

                 * dpad-down

                 * dpad-left

                 * dpad-right

       * CONTROLLER-RELEASE: Called with two arguments when a button on a game controller is released:

           1. CONTROLLER: The controller that triggered the event.

           2. BUTTON: The symbolic name of the button that was released.

       * CONTROLLER-MOVE: Called with three arguments when an analog stick or trigger on a game controller is moved:

           1. CONTROLLER: The controller that triggered the event.

           2. AXIS: The symbolic name of the axis that was moved.  Possible values are:

                 * left-x

                 * left-y

                 * right-x

                 * right-y

                 * trigger-left

                 * trigger-right

       * ERROR: Called with three arguments when an error occurs:

           1. STACK: The call stack at the point of error.

           2. KEY: The exception key.

           3. ARGS: The arguments thrown with the exception.

          The default behavior is to re-throw the error.

Math
====

Chickadee contains data types and procedures for performing the most common computations in video game simulations such as linear algebra with vectors and matrices and axis-aligned bounding box collision detection.

Basics
------

 -- Variable: pi
     An essential constant for all trigonometry.  Pi is the ratio of a circle's circumferences to its diameter.  Since pi is an irrational number, the PI in Chickadee is a mere floating point approximation that is ``good enough.''

 -- Variable: pi/2
     Half of PI.

 -- Procedure: cotan z
     Return the cotangent of Z.

Vectors
-------

Unlike Scheme's vector data type, which is a sequence of arbitrary Scheme objects, Chickadee's (chickadee math vector) module provides vectors in the linear algebra sense: Sequences of numbers specialized for particular coordinate spaces.  As of now, Chickadee provides 2D and 3D vectors, with 4D vector support coming in a future release.

Here's a quick example of adding two vectors:

     (define v (vec2+ (vec2 1 2) (vec2 3 4)))

Since vectors are used so frequently, the reader macro #v is used to cut down on typing:

     (define v (vec2+ #v(1 2) #v(3 4)))

A Note About Performance
........................

A lot of time has been spent making Chickadee's vector operations perform relatively efficiently in critical code paths where excessive garbage generation will cause major performance issues.  The general rule is that procedures ending with ! perform an in-place modification of one of the arguments in order to avoid allocating a new vector.  These procedures are also inlined by Guile's compiler in order to take advantage of optimizations relating to floating point math operations.  The downside is that since these are not pure functions, they do not compose well and create more verbose code.

2D Vectors
..........

 -- Procedure: vec2 x y
     Return a new 2D vector with coordinates (X, Y).

 -- Procedure: vec2/polar r theta
     Return a new 2D vector containing the Cartesian representation of the polar coordinate (R, THETA).  The angle THETA is measured in radians.

 -- Procedure: vec2? obj
     Return #t if OBJ is a 2D vector.

 -- Procedure: vec2-x v
     Return the X coordinate of the 2D vector V.

 -- Procedure: vec2-y v
     Return the Y coordinate of the 2D vector V.

 -- Procedure: vec2-copy v
     Return a fresh copy of the 2D vector V.

 -- Procedure: vec2-magnitude v
     Return the magnitude of the 2D vector V.

 -- Procedure: vec2-dot-product v1 v2
     Return the dot product of the 2D vectors V1 and V2.

 -- Procedure: vec2-normalize v
     Return the normalized form of the 2D vector V.

 -- Procedure: vec2+ v x
     Add X, either a 2D vector or a scalar (i.e. a real number), to the 2D vector V and return a new vector containing the sum.

 -- Procedure: vec2- v x
     Subtract X, either a 2D vector or a scalar, from the 2D vector V and return a new vector containing the difference.

 -- Procedure: vec2* v x
     Multiply the 2D vector V by X, a 2D vector or a scalar, and return a new vector containing the product.

 -- Procedure: set-vec2-x! v x
     Set the X coordinate of the 2D vector V to X.

 -- Procedure: set-vec2-y! v y
     Set the Y coordinate of the 2D vector V to Y.

 -- Procedure: set-vec2! v x y
     Set the X and Y coordinates of the 2D vector V to X and Y, respectively.

 -- Procedure: vec2-copy! source target
     Copy the 2D vector SOURCE into the 2D vector TARGET.

 -- Procedure: vec2-add! v x
     Perform an in-place modification of the 2D vector V by adding X, a 2D vector or a scalar.

 -- Procedure: vec2-sub! v x
     Perform an in-place modification of the 2D vector V by subtracting X, a 2D vector or a scalar.

 -- Procedure: vec2-mult! v x
     Perform an in-place modification of the 2D vector V by multiplying it by X, a 2D vector or a scalar.

3D Vectors
..........

 -- Procedure: vec3 x y
     Return a new 2D vector with coordinates (X, Y).

 -- Procedure: vec3? obj
     Return #t if OBJ is a 3D vector.

 -- Procedure: vec3-x v
     Return the X coordinate of the 3D vector V.

 -- Procedure: vec3-y v
     Return the Y coordinate of the 3D vector V.

 -- Procedure: vec3-z v
     Return the Z coordinate of the 3D vector V.

 -- Procedure: vec3-copy v
     Return a fresh copy of the 3D vector V.

 -- Procedure: vec3-magnitude v
     Return the magnitude of the 3D vector V.

 -- Procedure: vec3-dot-product v1 v2
     Return the dot product of the 3D vectors V1 and V2.

 -- Procedure: vec3-normalize v
     Return the normalized form of the 3D vector V.

 -- Procedure: vec3+ v x
     Add X, either a 3D vector or a scalar (i.e. a real number), to the 3D vector V and return a new vector containing the sum.

 -- Procedure: vec3- v x
     Subtract X, either a 3D vector or a scalar, from the 3D vector V and return a new vector containing the difference.

 -- Procedure: vec3* v x
     Multiply the 3D vector V by X, a 3D vector or a scalar, and return a new vector containing the product.

 -- Procedure: set-vec3-x! v x
     Set the X coordinate of the 3D vector V to X.

 -- Procedure: set-vec3-y! v y
     Set the Y coordinate of the 3D vector V to Y.

 -- Procedure: set-vec3-z! v z
     Set the Z coordinate of the 3D vector V to Z.

 -- Procedure: set-vec3! v x y z
     Set the X, Y, and Z coordinates of the 3D vector V to X, Y, and Z, respectively.

 -- Procedure: vec3-copy! source target
     Copy the 3D vector SOURCE into the 3D vector TARGET.

 -- Procedure: vec3-add! v x
     Perform an in-place modification of the 3D vector V by adding X, a 3D vector or a scalar.

 -- Procedure: vec3-sub! v x
     Perform an in-place modification of the 3D vector V by subtracting X, a 3D vector or a scalar.

 -- Procedure: vec3-mult! v x
     Perform an in-place modification of the 3D vector V by multiplying it by X, a 3D vector or a scalar.

Rectangles
----------

The (chickadee math rect) module provides an API for manipulating axis-aligned bounding boxes (AABBs).  AABBs are often used for collision detection in games.  Common use-cases are defining ``hitboxes'' in platformers or using them for the ``broad phase'' of a collision detection algorithm that uses a more complex (and thus slower) method of determining the actual collisions.

Like some of the other math modules, there exists a collection of functions that do in-place modification of rectangles for use in performance critical code paths.

 -- Procedure: rect x y width height
 -- Procedure: make-rect X Y WIDTH HEIGHT
     Create a new rectangle that is WIDTH by HEIGHT in size and whose bottom-left corner is located at (X, Y).

 -- Procedure: rect? obj
     Return #t if OBJ is a rectangle.

 -- Procedure: rect-within? rect1 rect2
     Return #t if RECT2 is completely within RECT1.

 -- Procedure: rect-intersects? rect1 rect2
     Return #t if RECT2 overlaps RECT1.

 -- Procedure: rect-contains? rect x y
     Return #t if the coordinates (X, Y) are within RECT.

 -- Procedure: rect-contains-vec2? rect v
     Return #t if the 2D vector V is within the bounds of RECT.

 -- Procedure: rect-x rect
     Return the X coordinate of the lower-left corner of RECT.

 -- Procedure: rect-y rect
     Return the Y coordinate of the lower-left corner of RECT.

 -- Procedure: rect-left rect
     Return the left-most X coordinate of RECT.

 -- Procedure: rect-right rect
     Return the right-most X coordinate of RECT.

 -- Procedure: rect-bottom rect
     Return the bottom-most Y coordinate of RECT.

 -- Procedure: rect-top rect
     Return the top-most Y coordinate of RECT.

 -- Procedure: rect-center-x rect
     Return the X coordinate of the center of RECT.

 -- Procedure: rect-center-y rect
     Return the Y coordinate of the center of RECT.

 -- Procedure: rect-width rect
     Return the width of RECT.

 -- Procedure: rect-height rect
     Return the height of RECT.

 -- Procedure: rect-area rect
     Return the surface area covered by RECT.

 -- Procedure: rect-clamp-x rect x
     Restrict X to the portion of the X axis covered by RECT.

 -- Procedure: rect-clamp-y rect y
     Restrict Y to the portion of the Y axis covered by RECT.

 -- Procedure: rect-clamp rect1 rect2
     Return a new rect that adjusts the location of RECT1 so that it is completely within RECT2.  An exception is thrown in the case that RECT1 cannot fit completely within RECT2.

 -- Procedure: rect-move rect x y
     Return a new rectangle based on RECT but moved to the coordinates (X, Y).

 -- Procedure: rect-move-vec2 rect v
     Return a new rectangle based on RECT but moved to the coordinates in the 2D vector V.

 -- Procedure: rect-move-by rect x y
     Return a new rectangle based on RECT but moved by (X, Y) units relative to its current location.

 -- Procedure: rect-move-by-vec2 rect v
     Return a new rectangle based on RECT but moved by the 2D vector V relative to its current location.

 -- Procedure: rect-inflate rect width height
     Return a new rectangle based on RECT, but expanded by WIDTH units on the X axis and HEIGHT units on the Y axis, while keeping the rectangle centered on the same point.

 -- Procedure: rect-union rect1 rect2
     Return a new rectangle that completely covers the area of RECT1 and RECT2.

 -- Procedure: rect-clip rect1 rect2
     Return a new rectangle that is the overlapping region of RECT1 and RECT2.  If the two rectangles do not overlap, a rectangle of 0 width and 0 height is returned.

 -- Procedure: set-rect-x! rect x
     Set the left X coordinate of RECT to X.

 -- Procedure: set-rect-y! rect y
     Set the bottom Y coordinate of RECT to Y.

 -- Procedure: set-rect-width! rect width
     Set the width of RECT to WIDTH.

 -- Procedure: set-rect-height! rect height
     Set the height of RECT to HEIGHT.

 -- Procedure: rect-move! rect x y
     Move RECT to (X, Y) in-place.

 -- Procedure: rect-move-vec2! rect v
     Move RECT to the 2D vector V in-place.

 -- Procedure: rect-move-by! rect x y
     Move RECT by (X, Y) in-place.

 -- Procedure: rect-move-by-vec2! rect v
     Move RECT by the 2D vector V in-place.

 -- Procedure: rect-inflate! rect width height
     Expand RECT by WIDTH and HEIGHT in-place.

 -- Procedure: rect-union! rect1 rect2
     Modify RECT1 in-place to completely cover the area of both RECT1 and RECT2.

 -- Procedure: rect-clip! rect1 rect2
     Modify RECT1 in-place to be the overlapping region of RECT1 and RECT2.

 -- Procedure: rect-clamp! rect1 rect2
     Adjust the location of RECT1 in-place so that its bounds are completely within RECT2.  An exception is thrown in the case that RECT1 cannot fit completely within RECT2.

 -- Procedure: vec2-clamp-to-rect! v rect
     Restrict the coordinates of the 2D vector V so that they are within the bounds of RECT.  V is modified in-place.

Grid
----

The (chickadee math grid) module provides a simple spatial partitioning system for axis-aligned bounding boxes (see Rectangles) in 2D space.  The grid divides the world into tiles and keeps track of which rectangles occupy which tiles.  When there are lots of moving objects in the game world that need collision detection, the grid greatly speeds up the process.  Instead of checking collisions of each object against every other object (an O(n^2) operation), the grid quickly narrows down which objects could possibly be colliding and only performs collision testing against a small set of objects.

In addition to checking for collisions, the grid also handles the resolution of collisions.  Exactly how each collision is resolved is user-defined.  A player bumping into a wall may slide against it.  An enemy colliding with a projectile shot by the player may get pushed back in the opposite direction.  Two players colliding may not need resolution at all and will just pass through each other.  The way this works is that each time an object (A) is moved within the grid, the grid looks for an object (B) that may possibly be colliding with A.  A user-defined procedure known as a ``filter'' is then called with both A and B.  If the filter returns #f, it means that even if A and B are colliding, no collision resolution is needed.  In this case the grid won't waste time checking if they really do collide because it doesn't matter.  If A and B are collidable, then the filter returns a procedure that implements the resolution technique.  The grid will then perform a collision test.  If A and B are colliding, the resolver procedure is called.  It's the resolvers job to adjust the objects such that they are no longer colliding.  The grid module comes with a very simple resolution procedure, slide, that adjusts object A by the smallest amount so that it no longer overlaps with B.  By using this filtering technique, a game can resolve collisions between different objects in different ways.

 -- Procedure: make-grid [cell-size 64]
     Return a new grid partitioned into CELL-SIZE tiles.

 -- Procedure: grid? obj
     Return #t if OBJ is a grid.

 -- Procedure: cell? obj
     Return #t if OBJ is a grid cell.

 -- Procedure: cell-count cell
     Return the number of items in CELL.

 -- Procedure: grid-cell-size grid
     Return the cell size of GRID.

 -- Procedure: grid-cell-count grid
     Return the number of cells currently in GRID.

 -- Procedure: grid-item-count grid
     Return the number of items in GRID.

 -- Procedure: grid-add grid item x y
     width height

     Add ITEM to GRID represented by the axis-aligned bounding box whose lower-left corner is at (X, Y) and is WIDTH x HEIGHT in size.

 -- Procedure: grid-remove grid item
     Return ITEM from GRID.

 -- Procedure: grid-clear grid
     Remove all items from GRID.

 -- Procedure: grid-move grid item position filter
     Attempt to move ITEM in GRID to POSITION (a 2D vector) and check for collisions.  For each collision, FILTER will be called with two arguments: ITEM and the item it collided with.  If a collision occurs, POSITION may be modified to resolve the colliding objects.

 -- Procedure: for-each-cell proc grid [rect]
     Call PROC with each cell in GRID that intersects RECT, or every cell if RECT is #f.

 -- Procedure: for-each-item proc grid
     Call PROC for each item in GRID.

 -- Procedure: slide item item-rect other other-rect goal

     Resolve the collision that occurs between ITEM and OTHER when moving ITEM-RECT to GOAL by sliding ITEM-RECT the minimum amount needed to make it no longer overlap OTHER-RECT.

Matrices
--------

The (chickadee math matrix) module provides an interface for working with the most common type of matrices in game development: 4x4 transformation matrices.

Another Note About Performance
..............................

Much like the vector API, the matrix API is commonly used in performance critical code paths.  In order to reduce the amount of garbage generated and improve matrix multiplication performance, there are many procedures that perform in-place modifications of matrix objects.

Matrix Operations
.................

 -- Procedure: make-matrix4 aa ab ac ad
     ba bb bc bd
     ca cb cc cd
     da db dc dd

     Return a new 4x4 matrix initialized with the given 16 values in column-major format.

 -- Procedure: make-null-matrix4
     Return a new 4x4 matrix with all values initialized to 0.

 -- Procedure: make-identity-matrix4
     Return a new 4x4 identity matrix.  Any matrix multiplied by the identity matrix yields the original matrix.  This procedure is equivalent to the following code:

          (make-matrix4 1 0 0 0
                        0 1 0 0
                        0 0 1 0
                        0 0 0 1)

 -- Procedure: matrix4? obj
     Return #t if OBJ is a 4x4 matrix.

 -- Procedure: matrix4* . matrices
     Return a new 4x4 matrix containing the product of multiplying all of the given MATRICES.

     Note: Remember that matrix multiplication is not commutative!

 -- Procedure: orthographic-projection left right top bottom near far

     Return a new 4x4 matrix that represents an orthographic (2D) projection for the horizontal clipping plane TOP and BOTTOM, the vertical clipping plane TOP and BOTTOM, and the depth clipping plane NEAR and FAR.

 -- Procedure: perspective-projection fov aspect-ratio near far

     Return a new 4x4 matrix that represents a perspective (3D) projection with a field of vision of FOV radians, an aspect ratio of ASPECT-RATIO, and a depth clipping plane defined by NEAR and FAR.

 -- Procedure: matrix4-translate x
     Return a new 4x4 matrix that represents a translation by X, a 2D vector, a 3D vector, or a rectangle (in which case the bottom-left corner of the rectangle is used).

 -- Procedure: matrix4-scale s
     Return a new 4x4 matrix that represents a scaling along the X, Y, and Z axes by the scaling factor S, a real number.

 -- Procedure: matrix4-rotate q
     Return a new 4x4 matrix that represents a rotation about an arbitrary axis defined by the quaternion Q.

 -- Procedure: matrix4-rotate-z theta
     Return a new 4x4 matrix that represents a rotation about the Z axis by THETA radians.

 -- Procedure: matrix4-identity! matrix
     Modify MATRIX in-place to contain the identity matrix.

 -- Procedure: matrix4-mult! dest a b
     Multiply the 4x4 matrix A by the 4x4 matrix B and store the result in the 4x4 matrix DEST.

 -- Procedure: matrix4-translate! matrix x
     Modify MATRIX in-place to contain a translation by X, a 2D vector, a 3D vector, or a rectangle (in which case the bottom-left corner of the rectangle is used).

 -- Procedure: matrix4-scale! matrix s
     Modify MATRIX in-place to contain a scaling along the X, Y, and Z axes by the scaling factor S, a real number.

 -- Procedure: matrix4-rotate! matrix q
     Modify MATRIX in-place to contain a rotation about an arbitrary axis defined by the quaternion Q.

 -- Procedure: matrix4-rotate-z! matrix theta
     Modify MATRIX in-place to contain a rotation about the Z axis by THETA radians.

 -- Procedure: matrix4-2d-transform! matrix [#:origin]
     [#:position] [#:rotation]
     [#:scale] [#:skew]

     Modify MATRIX in-place to contain the transformation described by POSITION, a 2D vector or rectangle, ROTATION, a scalar representing a rotation about the Z axis, SCALE, a 2D vector, and SKEW, a 2D vector.  The transformation happens with respect to ORIGIN, a 2D vector.  If an argument is not provided, that particular transformation will not be included in the result.

 -- Procedure: transform! matrix v
     Modify the 2D vector V in-place by multiplying it by the 4x4 matrix MATRIX.

Quaternions
-----------

In game development, the quaternion is most often used to represent rotations.  Why not use a matrix for that, you may ask.  Unlike matrices, quaternions can be interpolated (animated) and produce a meaningful result.  When interpolating two quaternions, there is a smooth transition from one rotation to another, whereas interpolating two matrices would yield garbage.

 -- Procedure: quaternion x y z w
     Return a new quaternion with values X, Y, Z, and W.

 -- Procedure: quaternion? obj
     Return #t if OBJ is a quaternion.

 -- Procedure: quaternion-w q
     Return the W component of the quaternion Q.

 -- Procedure: quaternion-x q
     Return the X component of the quaternion Q.

 -- Procedure: quaternion-y q
     Return the Y component of the quaternion Q.

 -- Procedure: quaternion-z q
     Return the Z component of the quaternion Q.

 -- Procedure: make-identity-quaternion
     Return the identity quaternion.

Easings
-------

Easing functions are essential for animation.  Each easing function provides a different path to go from an initial value to a final value.  These functions make an excellent companion to the tween procedure (see Tweening).  Experiment with them to figure out which function makes an animation look the best.

Pro tip: smoothstep provides nice results most of the time and creates smoother animation than using linear.

 -- Procedure: linear t

 -- Procedure: smoothstep t

 -- Procedure: ease-in-quad t

 -- Procedure: ease-out-quad t

 -- Procedure: ease-in-out-quad t

 -- Procedure: ease-in-cubic t

 -- Procedure: ease-out-cubic t

 -- Procedure: ease-in-out-cubic t

 -- Procedure: ease-in-quart t

 -- Procedure: ease-out-quart t

 -- Procedure: ease-in-out-quart t

 -- Procedure: ease-in-quint t

 -- Procedure: ease-out-quint t

 -- Procedure: ease-in-out-quint t

 -- Procedure: ease-in-sine t

 -- Procedure: ease-out-sine t

 -- Procedure: ease-in-out-sine t

Bezier Curves
-------------

The (chickadee math bezier) module provides an API for describing cubic Bezier curves in 2D space.  These curves are notably used in font description, vector graphics programs, and when it comes to games: path building.  With Bezier curves, it's somewhat easy to create a smooth looking path for an enemy to move along, for example. Bezier curves become particularly interesting when they are chained together to form a Bezier ``path'', where the end point of one curve becomes the starting point of the next.

Currently, the rendering of Bezier curves is rather crude and provided mostly for visualizing and debugging curves that would be unseen in the final game.  See Lines and Shapes for more information.

 -- Procedure: make-bezier-curve p0 p1 p2 p3
     Return a new Bezier curve object whose starting point is P0, ending point is P3, and control points are P1 and P2.  All points are 2D vectors.

 -- Procedure: bezier-curve? obj
     Return #t if OBJ is a Bezier curve.

 -- Procedure: bezier-curve-p0 bezier
     Return the starting point of BEZIER.

 -- Procedure: bezier-curve-p1 bezier
     Return the first control point of BEZIER.

 -- Procedure: bezier-curve-p2 bezier
     Return the second control point of BEZIER.

 -- Procedure: bezier-curve-p3 bezier
     Return the end point of BEZIER.

 -- Procedure: bezier-path . control-points
     Return a list of connected bezier curves defined by CONTROL-POINTS.  The first curve is defined by the first 4 arguments and every additional curve thereafter requires 3 additional arguments.

 -- Procedure: bezier-curve-point-at bezier t
     Return the coordinates for BEZIER at T (a value in the range [0, 1] representing how far from the start of the curve to check) as a 2D vector.

 -- Procedure: bezier-curve-point-at! dest bezier t
     Modify the 2D vector DEST in-place to contain the coordinates for BEZIER at T.

Path Finding
------------

Most game worlds have maps.  Often, these games have a need to move non-player characters around in an unscripted fashion.  For example, in a real-time strategy game, the player may command one of their units to attack something in the enemy base.  To do so, the unit must calculate the shortest route to get there.  It wouldn't be a very fun game if units didn't know how to transport themselves efficiently. This is where path finding algorithms come in handy.  The (chickadee math path-finding) module provides a generic implementation of the popular A* path finding algorithm.  Just add a map implementation!

The example below defines a very simple town map and finds the quickest way to get from the town common to the school.

     (define world-map
       '((town-common . (town-hall library))
         (town-hall . (town-common school))
         (library . (town-common cafe))
         (school . (town-hall cafe))
         (cafe . (library school))))
     (define (neighbors building)
       (assq-ref town-map building))
     (define (cost a b) 1)
     (define (distance a b) 1)
     (define pf (make-path-finder))
     (a* pf 'town-common 'school neighbors cost distance)

In this case, the a* procedure will return the list (town-common town-hall school), which is indeed the shortest route.  (The other possible route is (town-common library cafe school).)

The a* procedure does not know anything about about any kind of map and therefore must be told how to look up neighboring nodes, which is what the neighbors procedure in the example does. To simulate different types of terrain, a cost procedure is used.  In this example, it is just as easy to move between any two nodes because cost always returns 1.  In a real game, perhaps moving from from a field to a rocky hill would cost a lot more than moving from one field to another.  Finally, a heuristic is used to calculate an approximate distance between two nodes on the map.  In this simple association list based graph it is tough to calculate a distance between nodes, so the distance procedure isn't helpful and always returns 1.  In a real game with a tile-based map, for example, the heuristic could be a quick Manhattan distance calculation based on the coordinates of the two map tiles.  Choose an appropriate heuristic for optimal path finding!

 -- Procedure: make-path-finder
     Return a new path finder object.

 -- Procedure: path-finder? obj
     Return #t if OBJ is a path finder.

 -- Procedure: a* path-finder start goal neighbors cost distance

     Return a list of nodes forming a path from START to GOAL using PATH-FINDER to hold state.  NEIGHBORS is a procedure that accepts a node and returns a list of nodes that neighbor it. COST is a procedure that accepts two neighboring nodes and returns the cost of moving from the first to the second as a real number.  DISTANCE is a procedure that accepts two nodes and returns an approximate distance between them.

Graphics
========

Chickadee aims to make hardware-accelerated graphics rendering as simple and efficient as possible by providing high-level APIs that interact with the low-level OpenGL API under the hood.  Anyone that has worked with OpenGL directly knows that it has a steep learning curve and a lot of effort is needed to render even a single triangle. The Chickadee rendering engine attempts to make it easy to do common tasks like rendering a sprite while also providing all of the building blocks to implement additional rendering techniques.

Textures
--------

 -- Procedure: load-image file [#:min-filter nearest]
     [#:mag-filter nearest] [#:wrap-s repeat] [#:wrap-t repeat]

     Load the image data from FILE and return a new texture object.

     MIN-FILTER and MAG-FILTER describe the method that should be used for minification and magnification when rendering, respectively.  Possible values are nearest and linear.

     WRAP-S and WRAP-T describe how to interpret texture coordinates that are greater than 1.0.  Possible values are repeat, clamp, clamp-to-border, and clamp-to-edge.

 -- Procedure: texture? obj
     Return #t if OBJ is a texture.

 -- Procedure: texture-region? obj
     Return #t if OBJ is a texture region.

 -- Procedure: texture-parent texture
     If TEXTURE is a texture region, return the full texture that it is based upon.  Otherwise, return #f.

 -- Procedure: texture-min-filter texture
     Return the minification filter for TEXTURE, either nearest or linear.

 -- Procedure: texture-mag-filter texture
     Return the magnification filter for TEXTURE, either nearest or linear.

 -- Procedure: texture-wrap-s texture
     Return the method used for wrapping texture coordinates along the X axis for TEXTURE.

     Possible wrapping methods:

       * repeat

       * clamp

       * clamp-to-border

       * clamp-to-edge

 -- Procedure: texture-wrap-t texture
     Return the method used for wrapping texture coordinates along the Y axis for TEXTURE.

 -- Procedure: texture-width texture
     Return the width of TEXTURE in pixels.

 -- Procedure: texture-height texture
     Return the height of TEXTURE in pixels.

It is common practice to combine multiple bitmap images into a single texture, known as a ``tile atlas'' or ``tile set'', because it is more efficient to render many regions of a large texture than it is to render a bunch of small textures.  Chickadee provides a tile atlas data type for collecting texture regions into a single vector.

 -- Procedure: split-texture texture tile-width tile-height
     [#:margin 0] [#:spacing 0]

     Return a new texture atlas that splits TEXTURE into a grid of TILE-WIDTH by TILE-HEIGHT rectangles.  Optionally, each tile may have SPACING pixels of horizontal and vertical space between surrounding tiles and the entire image may have MARGIN pixels of empty space around its border.

     This type of texture atlas layout is very common for 2D tile maps. See Tile Maps for more information.

 -- Procedure: texture-atlas? obj
     Return #t if OBJ is a texture atlas.

 -- Procedure: texture-atlas-texture atlas
     Return the texture that all texture regions in ATLAS have been created from.

 -- Procedure: texture-atlas-ref atlas index
     Return the texture region in ATLAS at INDEX.

Sprites
-------

For those who are new to this game, a sprite is a 2D rectangular bitmap that is rendered to the screen.  For 2D games, sprites are the most essential graphical abstraction.  They are used for drawing maps, players, NPCs, items, particles, text, etc.  In Chickadee, bitmaps are stored in textures (see Textures) and can be used to draw sprites via the draw-sprite procedure.

 -- Procedure: draw-sprite texture position
     [#:tint white] [#:origin] [#:scale] [#:rotation] [#:blend-mode alpha]
     [#:rect]

     Draw TEXTURE at POSITION.

     Optionally, other transformations may be applied to the sprite. ROTATION specifies the angle to rotate the sprite, in radians. SCALE specifies the scaling factor as a 2D vector.  All transformations are applied relative to ORIGIN, a 2D vector, which defaults to the lower-left corner.

     TINT specifies the color to multiply against all the sprite's pixels.  By default white is used, which does no tinting at all.

     Alpha blending is used by default but the blending method can be changed by specifying BLEND-MODE.

     The area drawn to is as big as the texture, by default.  To draw to an arbitrary section of the screen, specify RECT.

It's not uncommon to need to draw hundreds or thousands of sprites each frame.  However, GPUs (graphics processing units) are tricky beasts that prefer to be sent few, large chunks of data to render rather than many, small chunks.  Using draw-sprite on its own will involve at least one GPU call per sprite.  This is fine for rendering a few dozen sprites, but will become a serious bottleneck when rendering hundreds or thousands of sprites.  To deal with this, a technique known as ``sprite batching'' is used.  Instead of drawing each sprite immediately, the sprite batch will build up a large of buffer of sprites to draw and send them to the GPU all at once.  There is one caveat, however.  Batching only works if the sprites being drawn share a common texture.  A good strategy for reducing the number of different textures is to stuff many bitmaps into a single image file and create a ``texture atlas'' (see Textures) to access the sub-images within.

 -- Procedure: make-sprite-batch texture [#:capacity 256]
     Create a new sprite batch for TEXTURE with initial space for CAPACITY sprites.  Sprite batches automatically resize when they are full to accomodate as many sprites as necessary.

 -- Procedure: sprite-batch? obj
     Return #t if OBJ is a sprite batch.

 -- Procedure: sprite-batch-texture batch
     Return the texture for BATCH.

 -- Procedure: set-sprite-batch-texture! batch texture
     Set texture for BATCH to TEXTURE.

 -- Procedure: sprite-batch-add! batch position
     [#:origin] [#:scale] [:rotation]
     [#:tint white] [#:texture-region]

     Add sprite located at POSITION to BATCH.

     To render a subsection of the batch's texture, a texture object whose parent is the batch texture may be specified as TEXTURE-REGION.

     See draw-sprite for information about the other arguments.

 -- Procedure: sprite-batch-clear! batch
     Reset size of BATCH to 0.

 -- Procedure: draw-sprite-batch batch [#:blend-mode alpha]
     Render BATCH using BLEND-MODE.  Alpha blending is used by default.

With a basic sprite abstraction in place, it's possible to build other abstractions on top of it.  One such example is the ``nine patch''.  A nine patch is a sprite that can be rendered at various sizes without becoming distorted.  This is achieved by dividing up the sprite into nine regions:

  * the center, which can be scaled horizontally and vertically

  * the four corners, which can never be scaled

  * the left and right sides, which can be scaled vertically

  * the top and bottom sides, which can be scaled horizontally

The one caveat is that the bitmap regions must be designed in such a way so that they are not distorted when stretched along the affected axes.  For example, that means that the top and bottom sides could have varying colored pixels vertically, but not horizontally.

The most common application of this technique is for graphical user interface widgets like buttons and dialog boxes.  By using a nine patch, they can be rendered at any size without unappealing scaling artifacts.

 -- Procedure: draw-nine-patch texture rect
     [#:margin 0] [#:top-margin margin] [#:bottom-margin margin]
     [#:left-margin margin] [#:right-margin margin]
     [#:origin] [#:scale] [#:rotation] [#:blend-mode alpha]
     [#:tint white]

     Draw a nine patch sprite.  A nine patch sprite renders TEXTURE as a WIDTH x HEIGHT rectangle whose stretchable areas are defined by the given margin measurements TOP-MARGIN, BOTTOM-MARGIN, LEFT-MARGIN, and RIGHT-MARGIN. The MARGIN argument may be used to configure all four margins at once.

     Refer to draw-sprite (see Sprites) for information about the other arguments.

Tile Maps
---------

A tile map is a scene created by composing lots of small sprites, called ``tiles'', into a larger image.  One program for editing such maps is called Tiled (http://mapeditor.org).  Chickadee has native support for loading and rendering Tiled maps in the (chickadee render tiled) module.

 -- Procedure: load-tile-map file-name
     Load the Tiled formatted map in FILE-NAME and return a new tile map object.

 -- Procedure: draw-tile-map tile-map [#:layers] [#:region]
     [#:origin] [#:position] [#:scale] [#:rotation]

     Draw the layers of TILE-MAP.  By default, all layers are drawn. To draw a subset of the available layers, pass a list of layer ids using the LAYERS keyword argument.

     Refer to draw-sprite (see Sprites) for information about the other arguments.

Lines and Shapes
----------------

Sprites are fun, but sometimes simple, untextured lines and polygons are desired.  That's where the (chickadee render shapes) module comes in!

 -- Procedure: draw-line start end
     [#:thickness 0.5] [#:feather 1.0] [#:cap round] [#:color]
     [#:shader]

     Draw a line segment from START to END. The line will be THICKNESS pixels thick with an antialiased border FEATHER pixels wide.  The line will be colored COLOR. CAP specifies the type of end cap that should be used to terminate the lines, either none, butt, square, round, triangle-in, or triangle-out.  Advanced users may use the SHADER argument to override the built-in line segment shader.

 -- Procedure: draw-bezier-curve bezier [#:segments 32]
     [#:control-points?] [#:tangents?]
     [#:control-point-size 8]
     [#:control-point-color yellow]
     [#:tangent-color yellow]
     [#:thickness 0.5] [#:feather 1.0]
     [#:matrix]

     Draw the curve defined by BEZIER using a resolution of N SEGMENTS.  When CONTROL-POINTS? is #t, the control points are rendered as squares of size CONTROL-POINT-SIZE pixels and a color of CONTROL-POINT-COLOR.  When TANGENTS? is #t, the tangent lines from terminal point to control point are rendered using the color TANGENT-COLOR.

     All line segments rendered use draw-line, and thus the arguments THICKNESS and FEATHER have the same effect as in that procedure.

     A custom MATRIX may be passed for applications that require more control over the final output.

 -- Procedure: draw-bezier-path path [#:segments 32]
     [#:control-points?] [#:tangents?]
     [#:control-point-size 8]
     [#:control-point-color yellow]
     [#:tangent-color yellow]
     [#:thickness 0.5] [#:feather 1.0]
     [#:matrix]

     Render PATH, a list of bezier curves.  See the documentation for draw-bezier-curve for an explanation of all the keyword arguments.

Fonts
-----

Printing text to the screen is quite easy:

     (draw-text "Hello, world" (vec2 100.0 100.0))

Chickadee loads and renders bitmap fonts in the Angel Code format (http://www.angelcode.com/products/bmfont/doc/file_format.html).  A default font named ``Good Neighbors'' is built-in to Chickadee and is used for all text rendering operations where a font is not specified, as is the case in the above example.

The following procedures can be found in the (chickadee render font) module:

 -- Procedure: load-font file
     Load the Angel Code font (in either XML or FNT format) in FILE and return a new font object.

 -- Procedure: font? obj
     Return #t if OBJ is a font object.

 -- Procedure: font-face font
     Return the name of FONT.

 -- Procedure: font-line-height font
     Return the line height of FONT.

 -- Procedure: font-line-height font
     Return the line height of FONT.

 -- Procedure: font-bold? font
     Return #t if FONT is a bold font.

 -- Procedure: font-italic? font
     Return #t if FONT is an italicized font.

 -- Procedure: draw-text text position
     [#:font] [#:origin] [#:scale] [#:rotation] [#:blend-mode] [#:start 0] [#:end (string-length text)]

     Draw the string TEXT with the first character starting at POSITION using FONT.  If FONT is not specified, a built-in font is used.

          (draw-text font "Hello, world!" (vec2 128.0 128.0))

     To render a substring of TEXT, use the START and END arguments.

     Refer to draw-sprite (see Sprites) for information about the other arguments.

Particles
---------

Effects like smoke, fire, sparks, etc. are often achieved by animating lots of little, short-lived sprites known as ``particles''.  In fact, all of these effects, and more, can be accomplished by turning a few configuration knobs in a ``particle system''.  A particle system takes care of managing the many miniscule moving morsels so the developer can quickly produce an effect and move on with their life.  The (chickadee render particles) module provides an API for manipulating particle systems.

Below is an example of a very simple particle system that utilizes nearly all of the default configuration settings:

     (use-modules (chickadee render particles))
     (define texture (load-image "particle.png"))
     (define particles (make-particles 2000 #:texture texture))

In order to put particles into a particle system, a particle ``emitter'' is needed.  Emitters know where to spawn new particles, how many of them to spawn, and for how long they should do it.

Below is an example of an emitter that spawns 16 particles per frame at the coordinates (320, 240):

     (use-modules (chickadee math vector))
     (define emitter (make-particle-emitter (vec2 320.0 240.0) 16))
     (add-particle-emitter particles emitter)

To see all of the tweakable knobs and switches, read on!

 -- Procedure: make-particles capacity [#:blend-mode alpha]
     [#:color white] [#:end-color transparent] [#:texture]
     [#:animation-rows 1] [#:animation-columns 1] [#:width] [#:height]
     [#:speed-range (vec2 0.1 1.0)] [#:acceleration-range (vec2 0.0 0.1)]
     [#:direction-range (vec2 0 (* 2 pi))] [#:lifetime 30] [#:sort]

     Return a new particle system that may contain up to CAPACITY particles.  Achieving the desired particle effect involves tweaking the following keyword arguments as needed:

     - BLEND-MODE: Pixel blending mode.  alpha by default. (see Blending for more about blend modes).

     - START-COLOR: The tint color of the particle at the beginning of its life.  White by default.

     - END-COLOR: The tint color of the particle at the end of of its life.  Completely transparent by default for a fade-out effect.  The color in the middle of a particle's life will be an interpolation of START-COLOR and END-COLOR.

     - TEXTURE: The texture applied to the particles.  The texture may be subdivided into many animation frames.

     - ANIMATION-ROWS: How many animation frame rows there are in the texture.  Default is 1.

     - ANIMATION-COLUMNS: How many animation frame columns there are in the texture.  Default is 1.

     - WIDTH: The width of each particle.  By default, the width of an animation frame (in pixels) is used.

     - HEIGHT: The height of each particle.  By default, the height of an animation frame (in pixels) is used.

     - SPEED-RANGE: A 2D vector containing the min and max particle speed.  Each particle will have a speed chosen at random from this range.  By default, speed ranges from 0.1 to 1.0.

     - ACCELERATION-RANGE: A 2D vector containing the min and max particle acceleration.  Each particle will have an acceleration chosen at random from this range.  By default, acceleration ranges from 0.0 to 0.1.

     - DIRECTION-RANGE: A 2D vector containing the min and max particle direction as an angle in radians.  Each particle will have a direction chosen at random from this range.  By default, the range covers all possible angles.

     - LIFETIME: How long each particle lives, measured in updates. 30 by default.

     - SORT: youngest if youngest particle should be drawn last or oldest for the reverse.  By default, no sorting is applied at all.

 -- Procedure: particles? obj
     Return #t if OBJ is a particle system.

 -- Procedure: update-particles particles
     Advance the simulation of PARTICLES.

 -- Procedure: draw-particles particles
     Render PARTICLES.

 -- Procedure: draw-particles* particles matrix
     Render PARTICLES with MATRIX applied.

 -- Procedure: make-particle-emitter spawn-area rate [duration]

     Return a new particle emitter that spawns RATE particles per frame within SPAWN-AREA (a rectangle or 2D vector) for DURATION frames.  If DURATION is not specified, the emitter will spawn particles indefinitely.

 -- Procedure: particle-emitter? obj
     Return #t if OBJ is a particle emitter.

 -- Procedure: particle-emitter-spawn-area emitter
     Return the spawn area for EMITTER.

 -- Procedure: particle-emitter-rate emitter
     Return the number of particles that EMITTER will spawn per frame.

 -- Procedure: particle-emitter-life emitter
     Return the number of frames remaining in EMITTER's lifespan.

 -- Procedure: particle-emitter-done? emitter
     Return #t if EMITTER has finished spawning particlces.

 -- Procedure: add-particle-emitter particles emitter
     Add EMITTER to PARTICLES.

 -- Procedure: remove-particle-emitter particles emitter
     Remove EMITTER to PARTICLES

Blending
--------

Rendering a scene often involves drawing layers of objects that overlap each other.  Blending determines how two overlapping pixels are combined in the final image that is rendered to the screen. Chickadee provides the following blend modes:

  * replace Use the latest color, ignoring all others.

  * alpha Blend pixels according to the values of their alpha channels.  This is the most commonly used blend mode and thus is Chickadee's default mode.

  * add Add all pixel color values together.  The more colors blended together, the more white the final color becomes.

  * subtract Subtract all pixel color values.  The more colors blended together, the more black the final color becomes.

  * multiply

  * darken

  * lighten

  * screen

Framebuffers
------------

A framebuffer is a chunk of memory that the GPU can render things onto.  By default, the framebuffer that is used for rendering is the one belonging to the game window, but custom framebuffers can be used as well.  A common use-case for custom framebuffers is applying post-processing effects: The entire scene is rendered to a framebuffer, and then the contents of that framebuffer are applied to a post-processing shader and rendered to the game window.  The post-processing shader could do any number of things: scaling, antialiasing, motion blur, etc.

 -- Procedure: make-framebuffer width height
     [#:min-filter linear]
     [#:mag-filter linear]
     [#:wrap-s repeat]
     [#:wrap-t repeat]

     Create a new framebuffer that is WIDTH pixels wide and HEIGHT pixels high.

     MIN-FILTER and MAG-FILTER determine the scaling algorithm applied to the framebuffer when rendering.  By default, linear scaling is used in both cases. To perform no smoothing at all, use nearest for simple nearest neighbor scaling.  This is typically the best choice for pixel art games.

 -- Procedure: framebuffer? obj
     Return #t if OBJ is a framebuffer.

 -- Procedure: framebuffer-texture fb
     Return the texture backing the framebuffer FB.

 -- Procedure: framebuffer-viewport fb
     Return the default viewport (see Viewports) used by the framebuffer FB.

 -- Procedure: null-framebuffer
     The default framebuffer.

Viewports
---------

A viewport represents a subset of the screen (or framebuffer).  When rendering a frame, the resulting image will only appear within that viewport.  These aren't often needed, and Chickadee's default viewport occupies the entire screen, but there are certain situations where they are useful.  For example, a split-screen multiplayer game may render to two different viewports, each occupying a different half of the screen.  For information about how to set the current viewport, see with-viewport in Rendering Engine.

The (chickadee render viewport) module provides the following API:

 -- Procedure: make-viewport x y width height
     [#:clear-color] [#:clear-flags]

     Create a viewport that covers an area of the window starting from coordinates (X, Y) and spanning WIDTH x HEIGHT pixels.  Fill the viewport with CLEAR-COLOR when clearing the screen.  Clear the buffers denoted by the list of symbols in CLEAR-FLAGS.

     Possible values for CLEAR-FLAGS are COLOR-BUFFER, DEPTH-BUFFER, ACCUM-BUFFER, and STENCIL-BUFFER.

 -- Procedure: viewport? obj
     Return #t if OBJ is a viewport.

 -- Procedure: viewport-x viewport
     Return the left edge of VIEWPORT.

 -- Procedure: viewport-y viewport
     Return the bottom edge of VIEWPORT.

 -- Procedure: viewport-width viewport
     Return the width of VIEWPORT.

 -- Procedure: viewport-height viewport
     Return the height of VIEWPORT.

 -- Procedure: viewport-clear-color viewport
     Return the clear color for VIEWPORT.

 -- Procedure: viewport-clear-flags viewport
     Return the list of clear flags for VIEWPORT.

Rendering Engine
----------------

Chickadee defines rendering using a metaphor familiar to Scheme programmers: procedure application.  A shader (see Shaders) is like a procedure for the GPU to apply.  Shaders are passed arguments: A vertex array containing the geometry to render (see Buffers) and zero or more keyword arguments that the shader understands.  Similar to how Scheme has apply for calling procedures, Chickadee provides gpu-apply for calling shaders.

Additionally, there is some dynamic state that effects how gpu-apply will behave.  Things like the current viewport, framebuffer, and blend mode are stored as dynamic state because it would be tedious to have to have to specify them each time gpu-apply is called.

The following procedures and syntax can be found in the (chickadee render) module.

 -- Syntax: gpu-apply shader vertex-array
     [#:uniform-key uniform-value ...]
 -- Syntax: gpu-apply* shader vertex-array count
     [#:uniform-key uniform-value ...]

     Render VERTEX-ARRAY using SHADER with the uniform values specified in the following keyword arguments.

     While gpu-apply will draw every vertex in VERTEX-ARRAY, gpu-apply* will only draw COUNT vertices.

 -- Syntax: gpu-apply/instanced shader vertex-array
     n [#:uniform-key uniform-value ...]
 -- Syntax: gpu-apply/instanced shader vertex-array
     count n [#:uniform-key uniform-value ...]

     Render VERTEX-ARRAY N times using SHADER with the uniform values specified in the following keyword arguments.

     Instanced rendering is very beneficial for rendering the same object many times with only small differences for each one.  For example, the particle effects described in Particles use instanced rendering.

     While gpu-apply/instanced will draw every vertex in VERTEX-ARRAY, gpu-apply* will only draw COUNT vertices.

 -- Procedure: current-viewport
     Return the currently bound viewport (see Viewports).

 -- Procedure: current-framebuffer
     Return the currently bound framebuffer (see Framebuffers).

 -- Procedure: current-blend-mode
     Return the currently bound blend mode (see Blending).

 -- Procedure: current-depth-test
     Return #t if depth testing is currently enabled (see Blending).

 -- Procedure: current-texture
     Return the currently bound texture (see Textures).

 -- Procedure: current-projection
     Return the currently bound projection matrix (see Matrices).

 -- Syntax: with-viewport viewport body ...
     Evaluate BODY with the current viewport bound to VIEWPORT (see Viewports).

 -- Syntax: with-framebuffer framebuffer body ...
     Evaluate BODY with the current framebuffer bound to FRAMEBUFFER (see Framebuffers).

 -- Syntax: with-blend-mode blend-mode body ...
     Evaluate BODY with the current blend mode bound to BLEND-MODE (see Blending).

 -- Syntax: with-depth-test depth-test? body ...
     Evaluate BODY with the depth-test disabled if DEPTH-TEST? is #f, or enabled otherwise (see Blending).

 -- Syntax: with-texture texture body ...
     Evaluate BODY with the current texture bound to TEXTURE (see Textures).

 -- Syntax: with-projection projection body ...
     Evaluate BODY with the current projection matrix bound to PROJECTION (see Matrices).

Buffers
-------

Alright, let's brush aside all of those pretty high level abstractions and discuss what is going on under the hood.  The GPU exists as a discrete piece of hardware separate from the CPU.  In order to make it draw things, we must ship lots of data out of our memory space and into the GPU.  The (chickadee render buffer) module provides an API for manipulating GPU buffers.

In OpenGL terminology, a chunk of data allocated on the GPU is a ``vertex buffer object'' or VBO.  For example, here is a bytevector that could be transformed into a GPU buffer that packs together vertex position and texture coordinates:

     (use-modules (chickadee render buffer) (srfi srfi-4))
     (define data
       (f32vector -8.0 -8.0 ; 2D vertex
                  0.0 0.0   ; 2D texture coordinate
                  8.0 -8.0  ; 2D vertex
                  1.0 0.0   ; 2D texture coordinate
                  8.0 8.0   ; 2D vertex
                  1.0 1.0   ; 2D texture coordinate
                  -8.0 8.0  ; 2D vertex
                  0.0 1.0)) ; 2D texture coordinate

This data represents a textured 16x16 square centered on the origin. To send this data to the GPU, the make-buffer procedure is needed:

     (define buffer (make-buffer data #:stride 16))

The #:stride keyword argument indicates how many bytes make up each element of the buffer.  In this case, there are 4 floats per element: 2 for the vertex, and 2 for the texture coordinate.  A 32-bit float is 4 bytes in length, so the buffer's stride is 16.

Within a VBO, one or more ``attributes'', as OpenGL calls them, may be present.  Attributes are subregions within the buffer that have a particular data type.  In this case, there are two attributes packed into the buffer.  To provided a typed view into a buffer, the make-buffer-view procedure is needed:

     (define vertices
       (make-buffer-view #:buffer buffer
                         #:type 'vec2
                         #:component-type 'float
                         #:length 4))
     (define texcoords
       (make-buffer-view #:buffer buffer
                         #:type 'vec2
                         #:component-type 'float
                         #:length 4
                         #:offset 8))

To render a square, the GPU needs to draw two triangles, which means we need 6 vertices in total.  However, the above buffer only contains data for 4 vertices.  This is becase there are only 4 unique vertices for a square, but 2 of them must be repeated for each triangle.  To work with deduplicated vertex data, an ``index buffer'' must be created.

     (define index-buffer
       (make-buffer (u32vector 0 3 2 0 2 1)
                    #:target 'index)
     (define indices
       (make-buffer-view #:type 'scalar
                         #:component-type 'unsigned-int
                         #:buffer index-buffer))

Note the use of the #:target keyword argument.  It is required because the GPU treats index data in a special way and must be told which data is index data.

Now that the buffer views representing each attribute have been created, all that's left is to bind them all together in a ``vertex array object'', or VAO.  Vertex arrays associate each buffer view with an attribute index on the GPU.  The indices that are chosen must correspond with the indices that the shader (see Shaders) expects for each attribute.

     (define vertex-array
       (make-vertex-array #:indices indices
                          #:attributes `((0 . ,vertices)
                                         (1 . ,texcoords))))

With the vertex array created, the GPU is now fully aware of how to interpret the data that it has been given in the original buffer. Actually rendering this square is left as an exercise to the reader. See the Shaders section and the gpu-apply procedure in Rendering Engine for the remaining pieces of a successful draw call.  Additionally, consider reading the source code for sprites, shapes, or particles to see GPU buffers in action.

Without further ado, the API reference:

 -- Procedure: make-buffer data [#:name "anonymous"]
     [#:length] [#:offset 0] [#:stride 0] [#:target vertex]
     [#:usage static]

     Upload DATA, a bytevector, to the GPU.  By default, the entire bytevector is uploaded.  A subset of the data may be uploaded by specifying the OFFSET, the index of the first byte to be uploaded, and LENGTH, the number of bytes to upload.

     If DATA is #f, allocate LENGTH bytes of fresh GPU memory instead.

     TARGET and USAGE are hints that tell the GPU how the buffer is intended to be used.

     TARGET may be:

       * vertex Vertex attribute data.

       * index Index buffer data.

     USAGE may be:

       * static The buffer data will not be modified after creation.

       * stream The buffer data will be modified frequently.

     NAME is simply an arbitrary string for debugging purposes that is never sent to the GPU.

 -- Procedure: buffer? obj
     Return #t if OBJ is a GPU buffer.

 -- Procedure: index-buffer? buffer
     Return #t if BUFFER is an index buffer.

 -- Variable: null-buffer
     Represents the absence of a buffer.

 -- Procedure: buffer-name buffer
     Return the name of BUFFER.

 -- Procedure: buffer-length buffer
     Return the length of BUFFER.

 -- Procedure: buffer-stride buffer
     Return the amount of space, in bytes, between each element in BUFFER.

 -- Procedure: buffer-target buffer
     Return the the intended usage of BUFFER, either vertex or index.

 -- Procedure: buffer-usage buffer
     Return the intended usage of BUFFER, either static for buffer data that will not change once sent to the GPU, or stream for buffer data that will be frequently updated from the client-side.

 -- Procedure: buffer-data buffer
     Return a bytevector containing all the data within BUFFER.  If BUFFER has not been mapped (see with-mapped-buffer) then this procedure will return #f.

 -- Syntax: with-mapped-buffer buffer body ...
     Evaluate BODY in the context of BUFFER having its data synced from GPU memory to RAM.  In this context, buffer-data will return a bytevector of all the data stored in BUFFER.  When program execution exits this form, the data (including any modifications) is synced back to the GPU.

     This form is useful for streaming buffers that need to update their contents dynamically, such as a sprite batch.

 -- Procedure: make-buffer-view #:buffer #:type
     #:component-type #:length [#:offset 0] [#:divisor 1]
     [#:name "anonymous"]

     Return a new buffer view for BUFFER starting at byte index OFFSET of LENGTH elements, where each element is of TYPE and composed of COMPONENT-TYPE values.

     Valid values for TYPE are:

       * scalar single number

       * vec2 2D vector

       * vec3 3D vector

       * vec4 4D vector

       * mat2 2x2 matrix

       * mat3 3x3 matrix

       * mat4 4x4 matrix

     Valid values for COMPONENT-TYPE are:

       * byte

       * unsigned-byte

       * short

       * unsigned-short

       * int

       * unsigned-int

       * float

       * double

     DIVISOR is only needed for instanced rendering applications (see gpu-apply/instanced in Rendering Engine) and represents how many instances each vertex element applies to.  A divisor of 0 means that a single element is used for every instance and is used for the data being instanced.  A divisor of 1 means that each element is used for 1 instance.  A divisor of 2 means that each element is used for 2 instances, and so on.

 -- Procedure: buffer-view? obj
     Return #t if OBJ is a buffer view.

 -- Procedure: buffer-view->buffer buffer-view
     Return the buffer that BUFFER-VIEW is using.

 -- Procedure: buffer-view-name buffer-view
     Return the name of BUFFER-VIEW.

 -- Procedure: buffer-view-offset buffer-view
     Return the byte offset of BUFFER-VIEW.

 -- Procedure: buffer-view-type buffer-view
     Return the data type of BUFFER-VIEW.

 -- Procedure: buffer-view-component-type buffer-view
     Return the component data type of BUFFER-VIEW

 -- Procedure: buffer-view-divisor buffer-view
     Return the instance divisor for BUFFER-VIEW.

 -- Syntax: with-mapped-buffer-view buffer-view body ...

     Evaluate BODY in the context of BUFFER-VIEW having its data synced from GPU memory to RAM.  See with-mapped-buffer for more information.

 -- Procedure: make-vertex-array #:indices #:attributes
     [#:mode triangles]

     Return a new vertex array using the index data within the buffer view INDICES and the vertex attribute data within ATTRIBUTES.

     ATTRIBUTES is an alist mapping shader attribute indices to typed buffers containing vertex data:

          `((1 . ,buffer-view-a)
            (2 . ,buffer-view-b)
            ...)

     By default, the vertex array is interpreted as containing a series of triangles.  If another primtive type is desired, the MODE keyword argument may be overridden.  The following values are supported:

       * points

       * lines

       * line-loop

       * line-strip

       * triangles

       * triangle-strip

       * triangle-fan

 -- Variable: null-vertex-array
     Represents the absence of a vertex array.

 -- Procedure: vertex-array? obj
     Return #t if OBJ is a vertex array.

 -- Procedure: vertex-array-indices vertex-array
     Return the buffer view containing index data for VERTEX-ARRAY.

 -- Procedure: vertex-array-attributes vertex-array
     Return the attribute index -> buffer view mapping of vertex attribute data for VERTEX-ARRAY.

 -- Procedure: vertex-array-mode vertex-array
     Return the primitive rendering mode for VERTEX-ARRAY.

Shaders
-------

Shaders are programs that the GPU can evaluate that allow the programmer to completely customized the final output of a GPU draw call.  The (chickadee render shader) module provides an API for building custom shaders.

Shaders are written in the OpenGL Shading Language, or GLSL for short. Chickadee aspires to provide a domain specific language for writing shaders in Scheme, but we are not there yet.

Shader programs consist of two components: A vertex shader and a fragment shader.  A vertex shader receives vertex data (position coordinates, texture coordinates, normals, etc.) and transforms them as desired, whereas a fragment shader controls the color of each pixel.

Sample vertex shader:

     #version 130

     in vec2 position;
     in vec2 tex;
     out vec2 fragTex;
     uniform mat4 mvp;

     void main(void) {
         fragTex = tex;
         gl_Position = mvp * vec4(position.xy, 0.0, 1.0);
     }

Sample fragment shader:

     #version 130

     in vec2 fragTex;
     uniform sampler2D colorTexture;

     void main (void) {
         gl_FragColor = texture2D(colorTexture, fragTex);
     }

This manual will not cover GLSL features and syntax as there is lots of information already available about this topic.

One way to think about rendering with shaders, and the metaphor Chickadee uses, is to think about it as a function call: The shader is a function, and it is applied to some ``attributes'' (positional arguments), and some ``uniforms'' (keyword arguments).

     (define my-shader (load-shader "vert.glsl" "frag.glsl"))
     (define vertices (make-vertex-array ...))
     (gpu-apply my-shader vertices #:color red)

See Rendering Engine for more details about the gpu-apply procedure.

Shaders are incredibly powerful tools, and there's more information about them than we could ever fit into this manual, so we highly recommend searching the web for more information and examples.  What we can say, though, is how to use our API:

 -- Procedure: strings->shader vertex-source fragment-source
     Compile VERTEX-SOURCE, the GLSL code for the vertex shader, and FRAGMENT-SOURCE, the GLSL code for the fragment shader, into a GPU shader program.

 -- Procedure: load-shader vertex-source-file fragment-source-file
     Compile the GLSL source code within VERTEX-SOURCE-FILE and FRAGMENT-SOURCE-FILE into a GPU shader program.

 -- Procedure: make-shader vertex-port fragment-port
     Read GLSL source from VERTEX-PORT and FRAGMENT-PORT and compile them into a GPU shader program.

 -- Procedure: shader? obj
     Return #t if OBJ is a shader.

 -- Variable: null-shader
     Represents the absence shader program.

 -- Procedure: shader-uniform shader name
     Return the metadata for the uniform NAME in SHADER.

 -- Procedure: shader-uniforms shader
     Return a hash table of uniforms for SHADER.

 -- Procedure: shader-attributes shader
     Return a hash table of attributes for SHADER.

 -- Procedure: uniform? obj
     Return #t if OBJ is a uniform.

 -- Procedure: uniform-name uniform
     Return the variable name of UNIFORM.

 -- Procedure: uniform-type uniform
     Return the data type of UNIFORM.

 -- Procedure: uniform-value uniform
     Return the current value of UNIFORM.

 -- Procedure: uniform-default-value uniform
     Return the default value of UNIFORM.

 -- Procedure: attribute? obj
     Return #t if OBJ is an attribute.

 -- Procedure: attribute-name attribute
     Return the variable name of ATTRIBUTE.

 -- Procedure: attribute-location attribute
     Return the binding location of ATTRIBUTE.

 -- Procedure: attribute-type attribute
     Return the data type of ATTRIBUTE.

Scripting
=========

Game logic is a web of asynchronous events that are carefully coordinated to bring the game world to life.  In order to make an enemy follow and attack the player, or move an NPC back and forth in front of the item shop, or do both at the same time, a scripting system is a necessity.  Chickadee comes with an asynchronous programming system in the (chickadee scripting) module. Lightweight, cooperative threads known as ``scripts'' allow the programmer to write asynchronous code as if it were synchronous, and allow many such ``threads'' to run concurrently.

But before we dig deeper into scripts, let's discuss the simple act of scheduling tasks.

Agendas
-------

To schedule a task to be performed later, an ``agenda'' is used. There is a default, global agenda that is ready to be used, or additional agendas may be created for different purposes.  The following example prints the text ``hello'' when the agenda has advanced to time unit 10.

     (at 10 (display "hello\n"))

Most of the time it is more convenient to schedule tasks relative to the current time.  This is where after comes in handy:

     (after 10 (display "hello\n"))

Time units in the agenda are in no way connected to real time.  It's up to the programmer to decide what agenda time means.  A simple and effective approach is to map each call of the update procedure (see Kernel) to 1 unit of agenda time, like so:

     (define (update dt)
       (update-agenda 1))

It is important to call update-agenda periodically, otherwise no tasks will ever be run!

In addition to using the global agenda, it is useful to have multiple agendas for different purposes.  For example, the game world can use a different agenda than the user interface, so that pausing the game is a simple matter of not updating the world's agenda while continuing to update the user interface's agenda.  The current agenda is dynamically scoped and can be changed using the with-agenda special form:

     (define game-world-agenda (make-agenda))

     (with-agenda game-world-agenda
       (at 60 (spawn-goblin))
       (at 120 (spawn-goblin))
       (at 240 (spawn-goblin-king)))

 -- Procedure: make-agenda
     Return a new task scheduler.

 -- Procedure: agenda? obj
     Return #t if OBJ is an agenda.

 -- Procedure: current-agenda
 -- Procedure: current-agenda agenda
     When called with no arguments, return the current agenda.  When called with one argument, set the current agenda to AGENDA.

 -- Syntax: with-agenda agenda body ...
     Evaluate BODY with the current agenda set to AGENDA.

 -- Procedure: agenda-time
     Return the current agenda time.

 -- Procedure: update-agenda dt
     Advance the current agenda by DT.

 -- Procedure: schedule-at time thunk
     Schedule THUNK, a procedure of zero arguments, to be run at TIME.

 -- Procedure: schedule-after delay thunk
     Schedule THUNK, a procedure of zero arguments, to be run after DELAY.

 -- Procedure: schedule-every interval thunk [n]
     Schedule THUNK, a procedure of zero arguments, to be run every INTERVAL amount of time.  Repeat this N times, or indefinitely if not specified.

 -- Syntax: at time body ...
     Schedule BODY to be evaluated at TIME.

 -- Syntax: after delay body ...
     Schedule BODY to be evaluated after DELAY.

 -- Syntax: every interval body ...
 -- Syntax: every (interval n) body ...
     Schedule BODY to be evaluated every INTERVAL amount of time.  Repeat this N times, or indefinitely if not specified.

Scripts
-------

Now that we can schedule tasks, let's take things to the next level. It sure would be great if we could make procedures that described a series of actions that happened over time, especially if we could do so without contorting our code into a nest of callback procedures. This is where scripts come in.  With scripts we can write code in a linear way, in a manner that appears to be synchronous, but with the ability to suspend periodically in order to let other scripts have a turn and prevent blocking the game loop.  Building on top of the scheduling that agendas provide, here is a script that models a child trying to get their mother's attention:

     (script
       (while #t
         (display "mom!")
         (newline)
         (sleep 60))) ; where 60 = 1 second of real time

This code runs in an endless loop, but the sleep procedure suspends the script and schedules it to be run later by the agenda. So, after each iteration of the loop, control is returned back to the game loop and the program is not stuck spinning in a loop that will never exit.  Pretty neat, eh?

Scripts can suspend to any capable handler, not just the agenda. The yield procedure will suspend the current script and pass its ``continuation'' to a handler procedure.  This handler procedure could do anything.  Perhaps the handler stashes the continuation somewhere where it will be resumed when the user presses a specific key on the keyboard, or maybe it will be resumed when the player picks up an item off of the dungeon floor; the sky is the limit.

Sometimes it is necessary to abruptly terminate a script after it has been started.  For example, when an enemy is defeated their AI routine needs to be shut down.  When a script is spawned, a handle to that script is returned that can be used to cancel it when desired.

     (define script (script (while #t (display "hey\n") (sleep 60))))
     ;; sometime later
     (cancel-script script)

 -- Procedure: spawn-script thunk
     Apply THUNK as a script and return a handle to it.

 -- Syntax: script body ...
     Evaluate BODY as a script and return a handle to it.

 -- Procedure: script? obj
     Return #t if OBJ is a script handle.

 -- Procedure: script-cancelled? obj
     Return #t if OBJ has been cancelled.

 -- Procedure: script-running? obj
     Return #t if OBJ has not yet terminated or been cancelled.

 -- Procedure: script-complete? obj
     Return #t if OBJ has terminated.

 -- Procedure: cancel-script co
     Prevent further execution of the script CO.

 -- Procedure: yield handler
     Suspend the current script and pass its continuation to the procedure HANDLER.

 -- Procedure: sleep duration
     Wait DURATION before resuming the current script.

 -- Syntax: forever body ...
     Evaluate BODY in an endless loop.

Tweening
--------

Tweening is the process of transitioning something from an initial state to a final state over a pre-determined period of time.  In other words, tweening is a way to create animation.  The tween procedure can be used within any script like so:

     (define x 0)
     (script
       ;; 0 to 100 in 60 ticks of the agenda.
       (tween 60 0 100 (lambda (y) (set! x y))))

 -- Procedure: tween duration start end proc
     [#:step 1] [#:ease smoothstep]
     #:interpolate lerp]
     Transition a value from START to END over DURATION, sending each succesive value to PROC.  STEP controls the amount of time between each update of the animation.

     To control how the animation goes from the initial to final state, an ``easing'' procedure may be specified.  By default, the smoothstep easing is used, which is a more pleasing default than a simplistic linear function.  See Easings for a complete list of available easing procedures.

     The INTERPOLATE procedure computes the values in between START and END.  By default, linear interpolation (``lerp'' for short) is used.

Channels
--------

Channels are a tool for communicating amongst different scripts.  One script can write a value to the channel and another can read from it. Reading or writing to a channel suspends that script until there is someone on the other end of the line to complete the transaction.

Here's a simplistic example:

     (define c (make-channel))

     (script
      (forever
       (let ((item (channel-get c)))
         (pk 'got item))))

     (script
      (channel-put c 'sword)
      (channel-put c 'shield)
      (channel-put c 'potion))

 -- Procedure: make-channel
     Return a new channel

 -- Procedure: channel? obj
     Return #t if OBJ is a channel.

 -- Procedure: channel-get channel
     Retrieve a value from CHANNEL.  The current script suspends until a value is available.

 -- Procedure: channel-put channel data
     Send DATA to CHANNEL.  The current script suspends until another script is available to retrieve the value.

A low-level API also exists for using channels outside of a script via callback procedures:

 -- Procedure: channel-get! channel proc
     Asynchronously retrieve a value from CHANNEL and call PROC with that value.

 -- Procedure: channel-put! channel data [thunk]
     Asynchronously send DATA to CHANNEL and call THUNK after it has been received.